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(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:org.opendaylight.sxp.route.core.RouteReactorZipImpl.java

/**
 * @return callback containing logic for mapping configuration into system routing
 *//*from   ww  w  . j a v a  2  s  .com*/
private Callable<Void> createUpdateRoutingTask() {
    return () -> {
        try {
            queueGuard.acquire();

            final Pair<SxpClusterRoute, SxpClusterRoute> latestPair = compressionQueue.poll();
            final ListenableFuture<Void> futureResult;
            if (WIPE_ROUTING_MARK == latestPair.getRight()) {
                futureResult = delegate.wipeRouting();
            } else {
                futureResult = delegate.updateRouting(latestPair.getLeft(), latestPair.getRight());
            }

            queueGuard.release();

            futureResult.get(60, TimeUnit.SECONDS);
            LOG.debug("Route update was finished");
        } catch (InterruptedException e) {
            LOG.warn("failed to get lock upon compression queue: {}", e.getMessage());
        } catch (ExecutionException | TimeoutException e) {
            LOG.warn("failed to propagate route update: {}", e.getMessage());
        }

        return null;
    };
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void getCounters(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<Counter>> future = metricService.findCounters(
            (String) queryParam.getParameters().get(QueryParam.METRIC_NAME),
            (String) queryParam.getParameters().get(QueryParam.GROUP_ID));
    try {/*from   ww  w . j  a  va  2 s  . c o m*/
        List<Counter> counters = future.get(5000, TimeUnit.MILLISECONDS);
        String result = counterResultWriter.writeValueAsString(counters);
        response.getWriter().print(result);
        response.setContentLength(result.length());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TimeoutException e) {
        response.getWriter().print(QUERY_CASSANDRA_TIMEOUT);
        response.setContentLength(QUERY_CASSANDRA_TIMEOUT.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ExecutionException e) {
        response.getWriter().print(QUERY_CASSANDRA_ERROR);
        response.setContentLength(QUERY_CASSANDRA_ERROR.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.spotify.helios.testing.HeliosDeploymentResource.java

/** Ensure that the HeliosDeployment is up. */
@Override/*w w w. j  av  a  2s.  c om*/
public void before() throws Throwable {
    super.before();

    // wait for the helios master to be available
    Polling.awaitUnchecked(30, TimeUnit.SECONDS,
            "Could not connect to HeliosDeployment at " + deployment.address() + " after %d %s",
            new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    final HostAndPort hap = deployment.address();
                    final SocketAddress address = new InetSocketAddress(hap.getHostText(), hap.getPort());
                    log.debug("attempting to connect to {}", address);

                    try {
                        final Socket s = new Socket();
                        s.connect(address, 100);
                        log.info("successfully connected to address {} for {}", address, deployment);
                        return true;
                    } catch (SocketTimeoutException | ConnectException e) {
                        log.debug("could not yet connect to HeliosDeployment: {}", e.toString());
                        return null;
                    }
                }
            });

    // Ensure that at least one agent is available and UP in this HeliosDeployment.
    // This prevents continuing with the test when starting up helios-solo before the agent is
    // registered.
    final HeliosClient client = client();
    Polling.awaitUnchecked(30, TimeUnit.SECONDS,
            "No agents were available at HeliosDeployment at " + deployment.address() + " after %d %s",
            new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    final ListenableFuture<List<String>> future = client.listHosts();

                    final List<String> hosts;
                    try {
                        // use a short timeout to allow this request to be retried a few times by the
                        // Polling.await loop
                        hosts = future.get(1, TimeUnit.SECONDS);
                    } catch (TimeoutException | InterruptedException e) {
                        log.debug("timed out waiting for listHosts request to finish, will retry");
                        return null;
                    }

                    if (hosts.isEmpty()) {
                        log.debug("0 agents in {}, will retry", deployment);
                        return null;
                    }

                    // Check that at least one host is UP (is maintaining a reasonably reliable
                    // connection to ZK) in addition to registering.
                    final ListenableFuture<Map<String, HostStatus>> statusFuture = client.hostStatuses(hosts);
                    final Map<String, HostStatus> hostStatuses;
                    try {
                        hostStatuses = statusFuture.get(1, TimeUnit.SECONDS);
                    } catch (TimeoutException | InterruptedException e) {
                        log.debug("timed out waiting for hostStatuses to finish, will retry");
                        return null;
                    }

                    for (final HostStatus hostStatus : hostStatuses.values()) {
                        if (hostStatus != null && hostStatus.getStatus() == HostStatus.Status.UP) {
                            log.info("Ensured that at least one agent is UP in this HeliosDeployment, "
                                    + "continuing with test!");
                            return true;
                        }
                    }

                    return null;
                }
            });
}

From source file:org.grycap.gpf4med.cloud.CloudService.java

/**
 * Starts new Gpf4Med study servers in the specified group, creating the group if necessary. The servers 
 * will be created with the specified configuration.
 * @param group the group to which the servers will be created.
 * @param count number of servers to be created in the group.
 * @param config optional configuration. If undefined, default configuration will be applied as defined 
 *        in: {@link DefaultNodeConfiguration}.
 */// w  w  w  .  ja  v a 2s . c  o  m
public void addServers(final String group, final int count, final @Nullable NodeConfiguration config) {
    checkArgument(StringUtils.isNotBlank(group), "Uninitialized or invalid group");
    checkArgument(count > 0, "Invalid number of servers");
    final NodeConfiguration config2 = (config != null ? config : fromDefaults());
    final Gpf4MedServiceController controller = controller();
    // quietly bypass node creation on providers that don't support it
    if (!controller.nodesCanBeAcquired()) {
        LOGGER.info("Bypassing unsupported node creation");
        return;
    }
    // create nodes asynchronously
    final ListeningExecutorService executorService = listeningDecorator(newCachedThreadPool());
    final List<ListenableFuture<HostAndPort>> futures = synchronizedList(
            new ArrayList<ListenableFuture<HostAndPort>>());
    for (final UnmodifiableIterator<Integer> it = create(closed(1, count), integers()).iterator(); it
            .hasNext(); it.next()) {
        final ListenableFuture<HostAndPort> future = executorService.submit(new Callable<HostAndPort>() {
            @Override
            public HostAndPort call() throws Exception {
                return controller.add(group, config2);
            }
        });
        futures.add(future);
    }
    final ListenableFuture<List<HostAndPort>> nodesFuture = successfulAsList(futures);
    List<HostAndPort> nodes = null;
    try {
        nodes = nodesFuture.get(MILLISECONDS.convert(ADD_SERVERS_TIMEOUT_MINUTES, MINUTES), MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOGGER.warn("Failed to acquire servers in group: " + group, e);
    }
    // create a mutable copy to remove null entries (failed nodes)
    if (nodes != null && !nodes.isEmpty()) {
        nodes = new ArrayList<HostAndPort>(nodes);
        nodes.removeAll(singleton(null));
    }
    // register group
    if (nodes != null && !nodes.isEmpty()) {
        groups.add(group);
    }
    LOGGER.info(String.format("Server(s) acquired in the group %s (%s)", group, nodes));
}

From source file:io.druid.query.groupby.epinephelinae.GroupByMergingQueryRunnerV2.java

private void waitForFutureCompletion(GroupByQuery query, ListenableFuture<List<Boolean>> future, long timeout) {
    try {/* w w  w .  j  a  v  a2  s  . co  m*/
        if (queryWatcher != null) {
            queryWatcher.registerQuery(query, future);
        }

        if (timeout <= 0) {
            throw new TimeoutException();
        }

        final List<Boolean> results = future.get(timeout, TimeUnit.MILLISECONDS);

        for (Boolean result : results) {
            if (!result) {
                future.cancel(true);
                throw new ResourceLimitExceededException("Grouping resources exhausted");
            }
        }
    } catch (InterruptedException e) {
        log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId());
        future.cancel(true);
        throw new QueryInterruptedException(e);
    } catch (CancellationException e) {
        throw new QueryInterruptedException(e);
    } catch (TimeoutException e) {
        log.info("Query timeout, cancelling pending results for query id [%s]", query.getId());
        future.cancel(true);
        throw new QueryInterruptedException(e);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    }
}

From source file:com.yeetor.adb.AdbServer.java

public AdbForward[] getForwardList() {
    ListenableFuture<List<AdbForward>> future = executeGetForwardList();
    try {/*from   w  w  w .jav a  2  s .  c  o m*/
        List<AdbForward> s = future.get(1, TimeUnit.SECONDS);
        AdbForward[] ret = new AdbForward[s.size()];
        s.toArray(ret);
        return ret;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new AdbForward[0];
}

From source file:com.facebook.swift.service.async.AsyncClient.java

@Test
public void testAsyncOutOfOrder() throws Exception {
    ListenableFuture<String> getFuture;
    ListenableFuture<Void> putFuture;

    try (DelayedMap.AsyncClient client = createClient(DelayedMap.AsyncClient.class, syncServer).get()) {
        getFuture = client.getValueSlowly(500, TimeUnit.MILLISECONDS, "testKey");
        putFuture = client.putValueSlowly(250, TimeUnit.MILLISECONDS, "testKey", "testValue");

        assertEquals(getFuture.get(1, TimeUnit.SECONDS), "testValue");
        putFuture.get(1, TimeUnit.SECONDS);
    }/*w ww  . j  ava  2 s  . c  om*/
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.RollupHandler.java

/**
 * This method gets the points from the DB and then rolls them up according to the granularity.
 *
 * Breaks up the number of ranges into buckets based on ROLLUP_ON_READ_REPAIR_SIZE_PER_THREAD and executes
 * the buckets in parallel.//www . java2 s .c o  m
 *
 * @param locator metric key within the DB
 * @param g the granularity
 * @param from the starting timestamp of the range (ms)
 * @param to the ending timestamp of the range (ms)
 *
 * @return a list of rolled-up points
 */
private List<Points.Point> repairRollupsOnRead(final Locator locator, Granularity g, long from, long to) {
    Timer.Context c = timerRepairRollupsOnRead.time();

    List<Points.Point> repairedPoints = new ArrayList<Points.Point>();
    List<ListenableFuture<List<Points.Point>>> futures = new ArrayList<ListenableFuture<List<Points.Point>>>();

    for (final Iterable<Range> ranges : divideRangesByGroup(g, from, to)) {
        futures.add(

                createRepairPointsExecutor.submit(new Callable() {

                    @Override
                    public List<Points.Point> call() throws Exception {
                        return createRepairPoints(ranges, locator);
                    }
                }));
    }

    ListenableFuture<List<List<Points.Point>>> aggregateFuture = Futures.allAsList(futures);

    try {
        for (List<Points.Point> subList : aggregateFuture.get(rollupOnReadTimeout.getValue(),
                rollupOnReadTimeout.getUnit())) {

            repairedPoints.addAll(subList);
        }
    } catch (Exception e) {
        aggregateFuture.cancel(true);
        exceededQueryTimeout.mark();
        log.warn("Exception encountered while doing rollups on read, incomplete rollups will be returned.", e);
    }

    c.stop();

    return repairedPoints;
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.RollupHandler.java

public Map<Locator, MetricData> getRollupByGranularity(final String tenantId, final List<String> metrics,
        final long from, final long to, final Granularity g) {

    final Timer.Context ctx = metrics.size() == 1 ? plotTimers.SPLOT_TIMER.timer.time()
            : plotTimers.MPLOT_TIMER.timer.time();
    Future<List<SearchResult>> unitsFuture = null;
    List<SearchResult> units = null;
    List<Locator> locators = new ArrayList<Locator>();

    Timer.Context c = timerRorCalcUnits.time();

    for (String metric : metrics) {
        locators.add(Locator.createLocatorFromPathComponents(tenantId, metric));
    }//from w  w  w .  j  av  a2s. co m

    queriesSizeHist.update(locators.size());

    if (Util.shouldUseESForUnits()) {
        unitsFuture = ESUnitExecutor.submit(new Callable() {

            @Override
            public List<SearchResult> call() throws Exception {
                DiscoveryIO discoveryIO = (DiscoveryIO) ModuleLoader.getInstance(DiscoveryIO.class,
                        CoreConfig.DISCOVERY_MODULES);

                if (discoveryIO == null) {
                    log.warn("USE_ES_FOR_UNITS has been set to true, but no discovery module found."
                            + " Please check your config");
                    return null;
                }
                return discoveryIO.search(tenantId, metrics);
            }
        });
    }

    MetricsRWDelegator delegator = new MetricsRWDelegator();
    final Map<Locator, MetricData> metricDataMap = delegator.getDatapointsForRange(locators,
            new Range(g.snapMillis(from), to), g);

    if (unitsFuture != null) {
        try {
            units = unitsFuture.get();
            for (SearchResult searchResult : units) {
                Locator locator = Locator.createLocatorFromPathComponents(searchResult.getTenantId(),
                        searchResult.getMetricName());
                if (metricDataMap.containsKey(locator))
                    metricDataMap.get(locator).setUnit(searchResult.getUnit());
            }
        } catch (Exception e) {
            log.warn(
                    "Exception encountered while getting units from ES, unit will be set to unknown in query results",
                    e);
        }
    }

    c.stop();

    if (locators.size() == 1) {
        for (final Map.Entry<Locator, MetricData> metricData : metricDataMap.entrySet()) {
            Timer.Context context = rollupsOnReadTimers.RR_SPLOT_TIMER.timer.time();
            repairMetrics(metricData.getKey(), metricData.getValue(), from, to, g);
            context.stop();
        }
    } else if (locators.size() > 1
            && Configuration.getInstance().getBooleanProperty(CoreConfig.TURN_OFF_RR_MPLOT) == false) {
        Timer.Context context = rollupsOnReadTimers.RR_MPLOT_TIMER.timer.time();
        ArrayList<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>();
        for (final Map.Entry<Locator, MetricData> metricData : metricDataMap.entrySet()) {
            futures.add(rollupsOnReadExecutor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() {
                    return repairMetrics(metricData.getKey(), metricData.getValue(), from, to, g);
                }
            }));
        }
        ListenableFuture<List<Boolean>> aggregateFuture = Futures.allAsList(futures);
        try {
            aggregateFuture.get(rollupOnReadTimeout.getValue(), rollupOnReadTimeout.getUnit());
        } catch (Exception e) {
            aggregateFuture.cancel(true);
            exceededQueryTimeout.mark();
            log.warn("Exception encountered while doing rollups on read, incomplete rollups will be returned.",
                    e);
        }
        context.stop();
    }

    for (MetricData metricData : metricDataMap.values()) {

        // we used to track enum queries here,
        // but since enum is removed, this currently is
        // a no op, doesn't track any queries
        markQueryByRollupType(metricData);
    }

    ctx.stop();
    return metricDataMap;
}

From source file:de.blizzy.documentr.search.PageFinder.java

private SearchResult findPages(String searchText, int page, Authentication authentication,
        IndexSearcher searcher) throws ParseException, IOException, TimeoutException {

    Future<Query> queryFuture = taskExecutor.submit(new ParseQueryTask(searchText, analyzer));
    ListenableFuture<Bits> visibleDocIdsFuture = taskExecutor.submit(
            new GetVisibleDocIdsTask(searcher, authentication, userStore, permissionEvaluator, taskExecutor));

    Query query;// w  ww . ja  v  a 2s  .  c  om
    TopDocs docs;
    try {
        query = queryFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS);
        Bits visibleDocIds = visibleDocIdsFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS);
        docs = searcher.search(query, new PagePermissionFilter(visibleDocIds), HITS_PER_PAGE * page);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ParseException) {
            throw (ParseException) cause;
        } else {
            throw Util.toRuntimeException(cause);
        }
    } finally {
        queryFuture.cancel(false);
        visibleDocIdsFuture.cancel(false);
    }

    int start = HITS_PER_PAGE * (page - 1);
    int end = Math.min(HITS_PER_PAGE * page, docs.scoreDocs.length);
    IndexReader reader = searcher.getIndexReader();
    List<ListenableFuture<SearchHit>> hitFutures = Lists.newArrayList();
    for (int i = start; i < end; i++) {
        ListenableFuture<SearchHit> hitFuture = taskExecutor
                .submit(new GetSearchHitTask(query, reader, docs.scoreDocs[i].doc, analyzer));
        hitFutures.add(hitFuture);
    }

    try {
        ListenableFuture<List<SearchHit>> allHitsFuture = Futures.allAsList(hitFutures);
        List<SearchHit> hits = allHitsFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS);
        return new SearchResult(hits, docs.totalHits, HITS_PER_PAGE);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw Util.toRuntimeException(cause);
        }
    } finally {
        for (ListenableFuture<SearchHit> hitFuture : hitFutures) {
            hitFuture.cancel(false);
        }
    }
}