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:co.cask.cdap.cli.command.ExecuteQueryCommand.java

@Override
public void perform(Arguments arguments, PrintStream output) throws Exception {
    String query = arguments.get(ArgumentName.QUERY.toString());
    long timeOutMins = arguments.getLong(ArgumentName.TIMEOUT.toString(), DEFAULT_TIMEOUT_MIN);

    ListenableFuture<ExploreExecutionResult> future = queryClient.execute(cliConfig.getCurrentNamespace(),
            query);/* w w  w  . j a va2 s  . c  o m*/
    try {
        ExploreExecutionResult executionResult = future.get(timeOutMins, TimeUnit.MINUTES);
        if (!executionResult.canContainResults()) {
            output.println("SQL statement does not output any result.");
            executionResult.close();
            return;
        }

        final List<ColumnDesc> schema = executionResult.getResultSchema();
        String[] header = new String[schema.size()];
        for (int i = 0; i < header.length; i++) {
            ColumnDesc column = schema.get(i);
            // Hive columns start at 1
            int index = column.getPosition() - 1;
            header[index] = column.getName() + ": " + column.getType();
        }
        List<QueryResult> rows = Lists.newArrayList(executionResult);
        executionResult.close();

        QueryStatus.OpStatus opStatus = executionResult.getStatus().getStatus();
        if (opStatus != QueryStatus.OpStatus.FINISHED) {
            throw new SQLException(
                    String.format("Query '%s' execution did not finish successfully. " + "Got final state - %s",
                            query, opStatus));
        }

        Table table = Table.builder().setHeader(header).setRows(rows, new RowMaker<QueryResult>() {
            @Override
            public List<?> makeRow(QueryResult object) {
                return object.getColumns();
            }
        }).build();
        cliConfig.getTableRenderer().render(cliConfig, output, table);

        output.printf("Fetched %d rows", rows.size()).println();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        Throwable t = Throwables.getRootCause(e);
        if (t instanceof HandleNotFoundException) {
            throw Throwables.propagate(t);
        } else if (t instanceof UnexpectedQueryStatusException) {
            UnexpectedQueryStatusException sE = (UnexpectedQueryStatusException) t;
            throw new SQLException(
                    String.format("Query '%s' execution did not finish successfully. " + "Got final state - %s",
                            query, sE.getStatus().toString()));
        }
        throw new SQLException(Throwables.getRootCause(e));
    } catch (CancellationException e) {
        throw new RuntimeException("Query has been cancelled on ListenableFuture object.");
    } catch (TimeoutException e) {
        output.println("Couldn't obtain results after " + timeOutMins + "mins.");
    }

}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpMetricsIngestionHandler.java

@Override
public void handle(ChannelHandlerContext ctx, HttpRequest request) {
    try {/*from www .  java 2 s.c om*/
        requestCount.inc();
        final String tenantId = request.getHeader("tenantId");
        JSONMetricsContainer jsonMetricsContainer = null;
        final Timer.Context jsonTimerContext = jsonTimer.time();

        final String body = request.getContent().toString(Constants.DEFAULT_CHARSET);
        try {
            jsonMetricsContainer = createContainer(body, tenantId);
            if (!jsonMetricsContainer.isValid()) {
                throw new IOException("Invalid JSONMetricsContainer");
            }
        } catch (JsonParseException e) {
            log.warn("Exception parsing content", e);
            sendResponse(ctx, request, "Cannot parse content", HttpResponseStatus.BAD_REQUEST);
            return;
        } catch (JsonMappingException e) {
            log.warn("Exception parsing content", e);
            sendResponse(ctx, request, "Cannot parse content", HttpResponseStatus.BAD_REQUEST);
            return;
        } catch (IOException e) {
            log.warn("IO Exception parsing content", e);
            sendResponse(ctx, request, "Cannot parse content", HttpResponseStatus.BAD_REQUEST);
            return;
        } catch (Exception e) {
            log.warn("Other exception while trying to parse content", e);
            sendResponse(ctx, request, "Failed parsing content", HttpResponseStatus.INTERNAL_SERVER_ERROR);
            return;
        }

        if (jsonMetricsContainer == null) {
            log.warn(ctx.getChannel().getRemoteAddress() + " No valid metrics");
            sendResponse(ctx, request, "No valid metrics", HttpResponseStatus.BAD_REQUEST);
            return;
        }

        List<Metric> containerMetrics;
        try {
            containerMetrics = jsonMetricsContainer.toMetrics();
            forceTTLsIfConfigured(containerMetrics);
        } catch (InvalidDataException ex) {
            // todo: we should measure these. if they spike, we track down the bad client.
            // this is strictly a client problem. Someting wasn't right (data out of range, etc.)
            log.warn(ctx.getChannel().getRemoteAddress() + " " + ex.getMessage());
            sendResponse(ctx, request, "Invalid data " + ex.getMessage(), HttpResponseStatus.BAD_REQUEST);
            return;
        } catch (Exception e) {
            // todo: when you see these in logs, go and fix them (throw InvalidDataExceptions) so they can be reduced
            // to single-line log statements.
            log.warn("Exception converting JSON container to metric objects", e);
            // This could happen if clients send BigIntegers as metric values. BF doesn't handle them. So let's send a
            // BAD REQUEST message until we start handling BigIntegers.
            sendResponse(ctx, request, "Error converting JSON payload to metric objects",
                    HttpResponseStatus.BAD_REQUEST);
            return;
        } finally {
            jsonTimerContext.stop();
        }

        if (containerMetrics == null || containerMetrics.isEmpty()) {
            log.warn(ctx.getChannel().getRemoteAddress() + " No valid metrics");
            sendResponse(ctx, request, "No valid metrics", HttpResponseStatus.BAD_REQUEST);
        }

        final MetricsCollection collection = new MetricsCollection();
        collection.add(new ArrayList<IMetric>(containerMetrics));
        final Timer.Context persistingTimerContext = persistingTimer.time();
        try {
            ListenableFuture<List<Boolean>> futures = processor.apply(collection);
            List<Boolean> persisteds = futures.get(timeout.getValue(), timeout.getUnit());
            for (Boolean persisted : persisteds) {
                if (!persisted) {
                    sendResponse(ctx, request, null, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    return;
                }
            }
            sendResponse(ctx, request, null, HttpResponseStatus.OK);
        } catch (TimeoutException e) {
            sendResponse(ctx, request, "Timed out persisting metrics", HttpResponseStatus.ACCEPTED);
        } catch (Exception e) {
            log.error("Exception persisting metrics", e);
            sendResponse(ctx, request, "Error persisting metrics", HttpResponseStatus.INTERNAL_SERVER_ERROR);
        } finally {
            persistingTimerContext.stop();
        }
    } finally {
        requestCount.dec();
    }
}

From source file:org.apache.heron.spi.statemgr.SchedulerStateManagerAdaptor.java

/**
 * Waits for ListenableFuture to terminate. Cancels on timeout
 *//* w  ww.ja v  a  2s.  com*/
protected <V> V awaitResult(ListenableFuture<V> future, int time, TimeUnit unit) {
    try {
        return future.get(time, unit);
    } catch (ExecutionException e) {
        LOG.log(Level.WARNING, "Exception processing future: " + e.getMessage());
        future.cancel(true);
        return null;
    } catch (InterruptedException | TimeoutException e) {
        LOG.log(Level.SEVERE, "Exception processing future ", e);
        future.cancel(true);
        return null;
    }
}

From source file:com.facebook.buck.io.watchman.WatchmanTransportClient.java

private Optional<Map<String, Object>> waitForQueryNotifyingUserIfSlow(
        ListenableFuture<Optional<Map<String, Object>>> future, long timeoutNanos, List<Object> query)
        throws InterruptedException, ExecutionException {
    long queryStartNanos = clock.nanoTime();
    try {// ww w .j a  v a 2  s .c  o m
        return future.get(Math.min(timeoutNanos, POLL_TIME_NANOS), TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        long remainingNanos = timeoutNanos - (clock.nanoTime() - queryStartNanos);
        if (remainingNanos > 0) {
            LOG.debug("Waiting for Watchman query [%s]...", query);
            if (!console.getVerbosity().isSilent()) {
                console.getStdErr().getRawStream().format("Waiting for watchman query...\n");
            }
            try {
                return future.get(remainingNanos, TimeUnit.NANOSECONDS);
            } catch (TimeoutException te) {
                LOG.debug("Timed out");
            }
        }
        LOG.warn("Watchman did not respond within %d ms, disabling.",
                TimeUnit.NANOSECONDS.toMillis(timeoutNanos));
        showDisabledWarning(timeoutNanos);
        return Optional.empty();
    }
}

From source file:org.apache.druid.query.GroupByMergedQueryRunner.java

private void waitForFutureCompletion(GroupByQuery query, ListenableFuture<?> future,
        IncrementalIndex<?> closeOnFailure) {
    try {//from  w ww . java2 s . c o  m
        queryWatcher.registerQuery(query, future);
        if (QueryContexts.hasTimeout(query)) {
            future.get(QueryContexts.getTimeout(query), TimeUnit.MILLISECONDS);
        } else {
            future.get();
        }
    } catch (InterruptedException e) {
        log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId());
        future.cancel(true);
        closeOnFailure.close();
        throw new QueryInterruptedException(e);
    } catch (CancellationException e) {
        closeOnFailure.close();
        throw new QueryInterruptedException(e);
    } catch (TimeoutException e) {
        closeOnFailure.close();
        log.info("Query timeout, cancelling pending results for query id [%s]", query.getId());
        future.cancel(true);
        throw new QueryInterruptedException(e);
    } catch (ExecutionException e) {
        closeOnFailure.close();
        throw Throwables.propagate(e.getCause());
    }
}

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

private void getMetrics(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<RawNumericMetric>> future = metricService.findData(queryParam);

    try {/*  w w  w.j ava 2s  . c  o m*/
        List<RawNumericMetric> metrics = future.get(5000, TimeUnit.MILLISECONDS);
        String result = metricResultWriter.writeValueAsString(metrics);
        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.facebook.buck.io.WatchmanTransportClient.java

private Optional<Map<String, Object>> waitForQueryNotifyingUserIfSlow(
        ListenableFuture<Optional<Map<String, Object>>> future, long timeoutNanos, long pollTimeNanos,
        List<Object> query) throws InterruptedException, ExecutionException {
    long queryStartNanos = clock.nanoTime();
    try {//from   w ww .  j a va 2s  . c o m
        return future.get(Math.min(timeoutNanos, pollTimeNanos), TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        long remainingNanos = timeoutNanos - (clock.nanoTime() - queryStartNanos);
        if (remainingNanos > 0) {
            console.getStdErr().getRawStream().format("Waiting for Watchman query [%s]...\n", query);
            try {
                return future.get(remainingNanos, TimeUnit.NANOSECONDS);
            } catch (TimeoutException te) {
                LOG.debug("Timed out");
            }
        }
        LOG.warn("Watchman did not respond within %d ms, disabling.",
                TimeUnit.NANOSECONDS.toMillis(timeoutNanos));
        console.getStdErr().getRawStream().format(
                "Timed out after %d ms waiting for Watchman command [%s]. Disabling Watchman.\n",
                TimeUnit.NANOSECONDS.toMillis(timeoutNanos), query);
        return Optional.empty();
    }
}

From source file:org.opendaylight.controller.cluster.datastore.IntegrationTestKit.java

void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
        throws Exception {
    Boolean canCommit = canCommitFuture.get(7, TimeUnit.SECONDS);
    assertEquals("canCommit", true, canCommit);
    cohort.preCommit().get(5, TimeUnit.SECONDS);
    cohort.commit().get(5, TimeUnit.SECONDS);
}

From source file:org.grycap.gpf4med.reflect.AsyncHandler.java

@Override
protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
        throws Throwable {
    final Group group = groupFromArgs(args, fromDefaultGroup());
    if ("create".equals(method.getName())) {
        checkArgument(group != null, "Uninitialized group");
        // check and create group
        final Iterable<HostAndPort> servers = CloudService.INSTANCE.list(group.getGroup());
        checkState(servers == null || !servers.iterator().hasNext(), "A previous group exists");
        final int numServers = numServers(fromDefaults(), reportsCount(args), type);
        CloudService.INSTANCE.addServers(group.getGroup(), numServers);
    }// w  w w .j  ava2  s  .  c o  m
    final Iterable<HostAndPort> servers = CloudService.INSTANCE.list(group.getGroup());
    checkState(servers != null, "No servers were found in the group");
    // execute the operation on the servers
    final List<ListenableFuture<Object>> futures = synchronizedList(new ArrayList<ListenableFuture<Object>>());
    for (final Iterator<HostAndPort> it = servers.iterator(); it.hasNext();) {
        final ListenableFuture<Object> future = executorService.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                final HostAndPort hostAndPort = it.next();
                final String baseURL = "http://" + hostAndPort.getHostText() + ":"
                        + hostAndPort.getPortOrDefault(80);
                final Path path = type.getAnnotation(Path.class);
                final T underlying = newResourceProxyClient(baseURL, path.value(), type);
                return method.invoke(underlying, args);
            }
        });
        futures.add(future);
    }
    // handle results
    final ListenableFuture<List<Object>> resultsFuture = successfulAsList(futures);
    List<Object> results = null;
    try {
        results = resultsFuture.get(MILLISECONDS.convert(EXEC_TIMEOUT_MINUTES, MINUTES), MILLISECONDS);
    } catch (InterruptedException | TimeoutException e) {
        LOGGER.warn("Failed to execute method " + method.getName() + " on group: " + group, e);
    } catch (ExecutionException e) {
        throw e.getCause();
    }
    if (method.getReturnType() == void.class) {
        return null;
    }
    return mergeResults(results);
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpAggregatedMultiIngestionHandler.java

@Override
public void handle(ChannelHandlerContext ctx, FullHttpRequest request) {

    Tracker.getInstance().track(request);

    requestCount.inc();/*from  w  ww.  j  a v a 2 s .  c  o m*/

    final Timer.Context timerContext = handlerTimer.time();
    long ingestTime = clock.now().getMillis();

    // this is all JSON.
    String body = null;
    try {
        String submitterTenantId = request.headers().get(HttpMetricsIngestionServer.TENANT_ID_HEADER);

        body = request.content().toString(Constants.DEFAULT_CHARSET);
        List<AggregatedPayload> bundleList = createBundleList(body);

        if (bundleList.size() > 0) {
            // has aggregated metric bundle in body
            // convert and add metric bundle to MetricsCollection if valid
            MetricsCollection collection = new MetricsCollection();
            List<ErrorResponse.ErrorData> errors = new ArrayList<ErrorResponse.ErrorData>();

            // for each metric bundle
            int delayedMetricsCount = 0;
            int metricsCount = 0;
            for (AggregatedPayload bundle : bundleList) {
                // validate, convert, and add to collection
                List<ErrorResponse.ErrorData> bundleValidationErrors = bundle.getValidationErrors();
                if (bundleValidationErrors.isEmpty()) {
                    // no validation error, add to collection
                    collection.add(PreaggregateConversions.buildMetricsCollection(bundle));
                } else {
                    // failed validation, add to error
                    errors.addAll(bundleValidationErrors);
                }

                if (bundle.hasDelayedMetrics(ingestTime)) {
                    Tracker.getInstance().trackDelayedAggregatedMetricsTenant(bundle.getTenantId(),
                            bundle.getTimestamp(), bundle.getDelayTime(ingestTime), bundle.getAllMetricNames());
                    bundle.markDelayMetricsReceived(ingestTime);
                    delayedMetricsCount += bundle.getAllMetricNames().size();
                } else {
                    metricsCount += bundle.getAllMetricNames().size();
                }
            }

            // if has validation errors and no valid metrics
            if (!errors.isEmpty() && collection.size() == 0) {
                // return BAD_REQUEST and error
                DefaultHandler.sendErrorResponse(ctx, request, errors, HttpResponseStatus.BAD_REQUEST);
                return;
            }

            // process valid metrics in collection
            ListenableFuture<List<Boolean>> futures = processor.apply(collection);
            List<Boolean> persisteds = futures.get(timeout.getValue(), timeout.getUnit());
            for (Boolean persisted : persisteds) {
                if (!persisted) {
                    DefaultHandler.sendErrorResponse(ctx, request, "Internal error persisting data",
                            HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    return;
                }
            }

            recordPerTenantMetrics(submitterTenantId, metricsCount, delayedMetricsCount);

            // return OK or MULTI_STATUS response depending if there were validation errors
            if (errors.isEmpty()) {
                // no validation error, response OK
                DefaultHandler.sendResponse(ctx, request, null, HttpResponseStatus.OK);
                return;
            } else {
                // has some validation errors, response MULTI_STATUS
                DefaultHandler.sendErrorResponse(ctx, request, errors, HttpResponseStatus.MULTI_STATUS);
                return;
            }

        } else {
            // no aggregated metric bundles in body, response OK
            DefaultHandler.sendResponse(ctx, request, "No valid metrics", HttpResponseStatus.BAD_REQUEST);
            return;
        }
    } catch (JsonParseException ex) {
        log.debug(String.format("BAD JSON: %s", body));
        DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST);
    } catch (InvalidDataException ex) {
        log.debug(String.format("Invalid request body: %s", body));
        DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST);
    } catch (TimeoutException ex) {
        DefaultHandler.sendErrorResponse(ctx, request, "Timed out persisting metrics",
                HttpResponseStatus.ACCEPTED);
    } catch (Exception ex) {
        log.debug(String.format("Exception processing: %s", body));
        log.error("Other exception while trying to parse content", ex);
        DefaultHandler.sendErrorResponse(ctx, request, "Internal error saving data",
                HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        timerContext.stop();
        requestCount.dec();
    }

}