Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

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

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

From source file:io.datakernel.service.ServiceGraphModule.java

private static ListenableFuture<?> combineFutures(List<ListenableFuture<?>> futures, final Executor executor) {
    final SettableFuture<?> resultFuture = SettableFuture.create();
    final AtomicInteger count = new AtomicInteger(futures.size());
    final AtomicReference<Throwable> exception = new AtomicReference<>();
    for (ListenableFuture<?> future : futures) {
        final ListenableFuture<?> finalFuture = future != null ? future : Futures.immediateFuture(null);
        finalFuture.addListener(new Runnable() {
            @Override//from   w  w w .j  a va  2 s . c  o m
            public void run() {
                try {
                    finalFuture.get();
                } catch (InterruptedException | ExecutionException e) {
                    exception.set(Throwables.getRootCause(e));
                }
                if (count.decrementAndGet() == 0) {
                    if (exception.get() != null)
                        resultFuture.setException(exception.get());
                    else
                        resultFuture.set(null);
                }
            }
        }, executor);
    }
    return resultFuture;
}

From source file:com.microsoft.tooling.msservices.serviceexplorer.RefreshableNode.java

protected void refreshItems(SettableFuture<List<Node>> future) {
    setLoading(true);//from ww w .j a v a 2s . c  o  m
    try {
        refreshItems();
        future.set(getChildNodes());
    } catch (AzureCmdException e) {
        future.setException(e);
    } finally {
        setLoading(false);
    }
}

From source file:com.google.caliper.runner.ServerSocketService.java

@Override
protected void shutDown() throws Exception {
    serverSocket.close();//from   w w  w  .jav  a  2s  .co m
    // Now we have either been asked to stop or have failed with some kind of exception, we want to
    // notify all pending requests, so if there are any references outside of this class they will
    // notice.
    lock.lock();
    try {
        for (SettableFuture<OpenedSocket> future : halfFinishedConnections.values()) {
            future.setException(new Exception("The socket has been closed"));
        }
        halfFinishedConnections.clear();
        connectionState.clear();
    } finally {
        lock.unlock();
    }
}

From source file:org.freeswitch.esl.client.internal.AbstractEslClientHandler.java

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {

    for (final SettableFuture<EslMessage> apiCall : apiCalls) {
        apiCall.setException(e.getCause());
    }//  w w  w  .j  a v a  2s.  com

    for (final SettableFuture<EslEvent> backgroundJob : backgroundJobs.values()) {
        backgroundJob.setException(e.getCause());
    }

    close(ctx.getChannel());

    ctx.sendUpstream(e);

}

From source file:com.tinspx.util.net.Requests.java

private static Runnable apply(final @NonNull AsyncFunction<? super Request, Response> context,
        final @NonNull Request request, final @NonNull SettableFuture<Response> future) {
    return new Runnable() {
        @Override//from   w w  w  .j  ava2  s  .  co  m
        public void run() {
            try {
                ListenableFuture<Response> result = context.apply(request);
                FutureUtils.linkFutures(result, future);
                FutureUtils.linkFailure(future, result, false);
            } catch (Throwable t) {
                future.setException(t);
                Throwables.propagateIfInstanceOf(t, Error.class);
            }
        }
    };
}

From source file:com.google.enterprise.adaptor.sharepoint.AsyncCacheLoader.java

@Override
public ListenableFuture<V> reload(final K key, V oldValue) {
    final SettableFuture<V> future = SettableFuture.create();
    executor().execute(new Runnable() {
        @Override/* w w w .  j  av a2 s. c om*/
        public void run() {
            try {
                future.set(load(key));
            } catch (Throwable t) {
                future.setException(t);
            }
        }
    });
    return future;
}

From source file:org.whispersystems.websocket.WebSocketResourceProvider.java

@Override
public void onWebSocketClose(int statusCode, String reason) {
    if (context != null) {
        context.notifyClosed(statusCode, reason);

        for (long requestId : requestMap.keySet()) {
            SettableFuture outstandingRequest = requestMap.remove(requestId);

            if (outstandingRequest != null) {
                outstandingRequest.setException(new IOException("Connection closed!"));
            }/*from ww  w  .j a v a 2 s  .com*/
        }
    }
}

From source file:org.apache.gobblin.r2.D2ClientProxy.java

private D2Client buildClient(D2ClientBuilder builder) {
    D2Client d2 = builder.build();//  w  ww.  ja  va2  s. co m
    final SettableFuture<None> d2ClientFuture = SettableFuture.create();
    d2.start(new Callback<None>() {
        @Override
        public void onError(Throwable e) {
            d2ClientFuture.setException(e);
        }

        @Override
        public void onSuccess(None none) {
            d2ClientFuture.set(none);
        }
    });

    try {
        // Synchronously wait for d2 to start
        d2ClientFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
    return d2;
}

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

public ListenableFuture<Map<String, Object>> run(final Object command) {
    if (!processing.get()) {
        SettableFuture<Map<String, Object>> die = SettableFuture.create();
        die.setException(new WatchmanException("connection closing down"));
        return die;
    }// w w  w  .j a va  2s .  co  m
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Map<String, Object>> resultRef = new AtomicReference<Map<String, Object>>();
    final AtomicReference<Exception> errorRef = new AtomicReference<Exception>();
    QueuedCommand queuedCommand = new QueuedCommandBuilder().command(command).latch(latch).resultRef(resultRef)
            .errorRef(errorRef).build();
    commandQueue.add(queuedCommand);
    return outgoingMessageExecutor.submit(new Callable<Map<String, Object>>() {
        @Override
        public Map<String, Object> call() throws Exception {
            if (commandListener.isPresent()) {
                commandListener.get().onStart();
            }
            if (processing.get()) {
                bserSerializer.serializeToStream(command, outputStream);
            }
            if (commandListener.isPresent()) {
                commandListener.get().onSent();
            }
            latch.await();
            if (commandListener.isPresent()) {
                commandListener.get().onReceived();
            }
            if (resultRef.get() != null)
                return resultRef.get();
            throw errorRef.get();
        }
    });
}

From source file:org.glassfish.jersey.process.internal.RequestInvoker.java

/**
 * Transform request data of a given type into a response result of the
 * different type./*  ww w.  ja  v a 2s.c  o m*/
 * <p/>
 * After the result is produced the provided {@link InvocationCallback result callback}
 * is invoked. The result callback can be invoked on a different thread but
 * still in the same {@link InvocationContext request invocation context}.
 *
 * @param request  request data to be transformed into a response result.
 * @param callback result callback called when the request transformation is
 *                 done. Must not be {@code null}.
 * @return future response.
 */
public ListenableFuture<RESPONSE> apply(final REQUEST request, final InvocationCallback<RESPONSE> callback) {
    final Instance instance = requestScope.createInstance();
    final SettableFuture<RESPONSE> result = SettableFuture.create();

    final Runnable requester = new Runnable() {

        @Override
        public void run() {
            final AsyncInflectorAdapter<REQUEST, RESPONSE> asyncAdapter = asyncAdapterBuilder
                    .create(new AcceptingInvoker(), callback);
            final ResponseProcessor<RESPONSE> responseProcessor = responseProcessorBuilder.build(asyncAdapter,
                    result, callback, instance);
            invocationContextReferenceFactory.get().set(asyncAdapter);
            try {
                asyncAdapter.apply(request);
            } finally {
                asyncAdapter.addListener(responseProcessor, executorsFactory.getRespondingExecutor());
            }
        }
    };

    try {
        try {
            executorsFactory.getRequestingExecutor().submit(new Runnable() {

                @Override
                public void run() {
                    requestScope.runInScope(instance, requester);
                }
            });
            return result;
        } catch (RejectedExecutionException ex) {
            throw new ProcessingException(LocalizationMessages.REQUEST_EXECUTION_FAILED(), ex);
        }
    } catch (ProcessingException ex) {
        try {
            SettableFuture<RESPONSE> failedResponse = SettableFuture.create();
            failedResponse.setException(ex);
            return failedResponse;
        } finally {
            callback.failure(ex);
        }
    }
}