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

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

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListenableScheduledFuture 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:eu.eubrazilcc.lvl.service.rest.TaskResource.java

@Path("progress/{id}")
@GET/*from w ww.  j  a va2  s  .  co  m*/
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents(final @PathParam("id") String id,
        final @QueryParam("refresh") @DefaultValue("30") int refresh,
        final @QueryParam("token") @DefaultValue("") String token, final @Context HttpServletRequest request,
        final @Context HttpHeaders headers) {
    if (isBlank(id) || !REFRESH_RANGE.contains(refresh)) {
        throw new WebApplicationException("Missing required parameters", Response.Status.BAD_REQUEST);
    }
    OAuth2SecurityManager.login(request, null, isBlank(token) ? headers : ssehHttpHeaders(token), RESOURCE_NAME)
            .requiresPermissions("tasks:*:*:" + id.trim() + ":view");
    // get from task storage
    final CancellableTask<?> task = TASK_STORAGE.get(fromString(id));
    if (task == null) {
        throw new WebApplicationException("Element not found", Response.Status.NOT_FOUND);
    }
    final String client = getClientAddress(request);
    LOGGER.info("Subscribed to progress events: " + client);
    final AtomicLong eventId = new AtomicLong(0l);
    final EventOutput eventOutput = new EventOutput();
    TASK_RUNNER.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                do {
                    final ListenableScheduledFuture<?> future = TASK_SCHEDULER.schedule(
                            checkTaskProgress(eventOutput, eventId, task),
                            eventId.getAndIncrement() == 0 ? 0 : refresh, SECONDS);
                    future.get();
                } while (!task.isDone());
            } catch (Exception e) {
                LOGGER.error("Failed to get task status", e);
            } finally {
                try {
                    eventOutput.close();
                } catch (Exception ignored) {
                }
                LOGGER.info("Closing progress events where subscriber is: " + client);
            }
            return null;
        }
    });
    return eventOutput;
}

From source file:com.google.devtools.build.lib.remote.ByteStreamUploader.java

private void startAsyncUploadWithRetry(Chunker chunker, Retrier.Backoff backoffTimes,
        SettableFuture<Void> overallUploadResult) {

    AsyncUpload.Listener listener = new AsyncUpload.Listener() {
        @Override//from  ww w  .j a v  a 2  s .c o m
        public void success() {
            overallUploadResult.set(null);
        }

        @Override
        public void failure(Status status) {
            StatusException cause = status.asException();
            long nextDelayMillis = backoffTimes.nextDelayMillis();
            if (nextDelayMillis < 0 || !retrier.isRetriable(status)) {
                // Out of retries or status not retriable.
                RetryException error = new RetryException(cause, backoffTimes.getRetryAttempts());
                overallUploadResult.setException(error);
            } else {
                retryAsyncUpload(nextDelayMillis, chunker, backoffTimes, overallUploadResult);
            }
        }

        private void retryAsyncUpload(long nextDelayMillis, Chunker chunker, Retrier.Backoff backoffTimes,
                SettableFuture<Void> overallUploadResult) {
            try {
                ListenableScheduledFuture<?> schedulingResult = retryService.schedule(
                        Context.current().wrap(
                                () -> startAsyncUploadWithRetry(chunker, backoffTimes, overallUploadResult)),
                        nextDelayMillis, MILLISECONDS);
                // In case the scheduled execution errors, we need to notify the overallUploadResult.
                schedulingResult.addListener(() -> {
                    try {
                        schedulingResult.get();
                    } catch (Exception e) {
                        overallUploadResult
                                .setException(new RetryException(e, backoffTimes.getRetryAttempts()));
                    }
                }, MoreExecutors.directExecutor());
            } catch (RejectedExecutionException e) {
                // May be thrown by .schedule(...) if i.e. the executor is shutdown.
                overallUploadResult.setException(new RetryException(e, backoffTimes.getRetryAttempts()));
            }
        }
    };

    try {
        chunker.reset();
    } catch (IOException e) {
        overallUploadResult.setException(e);
        return;
    }

    AsyncUpload newUpload = new AsyncUpload(channel, callCredentials, callTimeoutSecs, instanceName, chunker,
            listener);
    overallUploadResult.addListener(() -> {
        if (overallUploadResult.isCancelled()) {
            newUpload.cancel();
        }
    }, MoreExecutors.directExecutor());
    newUpload.start();
}