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.ServiceAdapters.java

/**
 * Returns factory which transforms Closeable object to ConcurrentService. On starting it doing nothing, on stopping it close Closeable.
 *///  ww  w.  j a v  a2s . c  o  m
public static ServiceAdapter<Closeable> forCloseable() {
    return new ServiceAdapter<Closeable>() {
        @Override
        public Service toService(final Closeable closeable, final Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    return Futures.immediateFuture(null);
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                closeable.close();
                                future.set(null);
                            } catch (IOException e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }
            };
        }
    };
}

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

/**
 * Returns factory which transforms blocking Service to asynchronous non-blocking ConcurrentService. It runs blocking operations from other thread from executor.
 *///from   ww  w .ja  v  a2  s.co m
public static ServiceAdapter<BlockingService> forBlockingService() {
    return new ServiceAdapter<BlockingService>() {
        @Override
        public Service toService(final BlockingService service, final Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    final SettableFuture<?> future = SettableFuture.create();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                service.start();
                                future.set(null);
                            } catch (Exception e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                service.stop();
                                future.set(null);
                            } catch (Exception e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }
            };
        }
    };
}

From source file:com.continuuity.loom.common.zookeeper.ZKClientExt.java

/**
 * Acts as {@link ZKClient#create(String, byte[], org.apache.zookeeper.CreateMode, boolean)
 * create(path, null, CreateMode.PERSISTENT, true)} if node doesn't exist. Otherwise has no affect.
 * In latter case sets {@code null} in returned future.
 *//*from  w  w  w  . j av a  2 s.c om*/
public static ListenableFuture<String> ensureExists(final ZKClient zkClient, final String path) {
    final SettableFuture<String> resultFuture = SettableFuture.create();
    OperationFuture<String> createFuture = zkClient.create(path, null, CreateMode.PERSISTENT, true);
    Futures.addCallback(createFuture, new FutureCallback<String>() {
        @Override
        public void onSuccess(String result) {
            resultFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (causedBy(t, KeeperException.NodeExistsException.class)) {
                resultFuture.set(path);
            } else {
                resultFuture.setException(t);
            }
        }
    });

    return resultFuture;
}

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

public static ServiceAdapter<EventloopServer> forEventloopServer() {
    return new ServiceAdapter<EventloopServer>() {
        @Override//w ww . java 2s  .c  om
        public Service toService(final EventloopServer instance, Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                instance.listen();
                                future.set(null);
                            } catch (IOException e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            instance.close();
                            future.set(null);
                        }
                    });
                    return future;
                }
            };
        }
    };
}

From source file:dk.ilios.spanner.internal.ExperimentingSpannerRun.java

public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
        Iterable<? extends ListenableFuture<? extends T>> futures) {
    final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
    ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
    Executor executor = MoreExecutors.sameThreadExecutor();
    for (final ListenableFuture<? extends T> future : futures) {
        SettableFuture<T> delegate = SettableFuture.create();
        // Must make sure to add the delegate to the queue first in case the future is already done
        delegates.add(delegate);//ww  w  .  j a  v  a2 s.  c  o m
        future.addListener(new Runnable() {
            @Override
            public void run() {
                SettableFuture<T> delegate = delegates.remove();
                try {
                    delegate.set(Uninterruptibles.getUninterruptibly(future));
                } catch (ExecutionException e) {
                    delegate.setException(e.getCause());
                } catch (CancellationException e) {
                    delegate.cancel(true);
                }
            }
        }, executor);
        listBuilder.add(delegate);
    }
    return listBuilder.build();
}

From source file:com.facebook.buck.rules.modern.builders.grpc.GrpcRemoteExecution.java

private static ListenableFuture<ByteString> readByteStream(String instanceName, Protocol.Digest digest,
        ByteStreamStub byteStreamStub) {
    String name = getReadResourceName(instanceName, digest);
    SettableFuture<ByteString> future = SettableFuture.create();
    byteStreamStub.read(ReadRequest.newBuilder().setResourceName(name).setReadLimit(0).setReadOffset(0).build(),
            new StreamObserver<ReadResponse>() {
                ByteString data = ByteString.EMPTY;

                @Override/*from  www .j a va2  s  . c o  m*/
                public void onNext(ReadResponse value) {
                    data = data.concat(value.getData());
                }

                @Override
                public void onError(Throwable t) {
                    future.setException(t);
                }

                @Override
                public void onCompleted() {
                    future.set(data);
                }
            });
    return future;
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * Returns a future that fails with a {@link TimeoutException} if the parent future has not
 * finished before the timeout. The new returned future will always be executed on the provided
 * scheduledExecutorService, even when the parent future does not timeout.
 *
 * @param scheduledExecutorService executor that runs the timeout code. If the future times out,
 *                                 this is also the thread any callbacks will run on.
 * @param future                   the future to wrap as a timeout future.
 * @param timeout                  how long to wait before timing out a future
 * @param unit                     unit of the timeout
 * @return a future that may timeout before the parent future is done.
 *///from   w w w  .ja v a  2 s  .  c  om
public static <T> ListenableFuture<T> makeTimeoutFuture(ScheduledExecutorService scheduledExecutorService,
        ListenableFuture<T> future, final long timeout, final TimeUnit unit) {
    final SettableFuture<T> promise = SettableFuture.create();

    scheduledExecutorService.schedule(new Runnable() {
        @Override
        public void run() {
            String message = "Future timed out after " + timeout + " " + unit.name();
            promise.setException(new TimeoutException(message));
        }
    }, timeout, unit);

    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            promise.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            promise.setException(t);
        }
    }, scheduledExecutorService);

    return promise;
}

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

public static <T> ListenableFuture<T> addTimeout(final ListenableFuture<T> future,
        final Callable<T> timeoutTask, Duration timeout, ScheduledExecutorService executorService) {
    // if the future is already complete, just return it
    if (future.isDone()) {
        return future;
    }/* w w w  .  j a  v a2 s. com*/

    // wrap the future, so we can set the result directly
    final SettableFuture<T> settableFuture = SettableFuture.create();

    // schedule a task to complete the future when the time expires
    final ScheduledFuture<?> timeoutTaskFuture = executorService.schedule(
            new TimeoutFutureTask<>(settableFuture, timeoutTask, future), timeout.toMillis(),
            TimeUnit.MILLISECONDS);

    // add a listener to the core future, which simply updates the settable future
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(@Nullable T result) {
            settableFuture.set(result);
            timeoutTaskFuture.cancel(true);
        }

        @Override
        public void onFailure(Throwable t) {
            settableFuture.setException(t);
            timeoutTaskFuture.cancel(true);
        }
    }, executorService);

    return settableFuture;
}

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

/**
 * Returns factory which transforms DataSource object to ConcurrentService. On starting it checks connecting , on stopping it close DataSource.
 *///from   ww  w  .j  a  v  a 2s . c  o  m
public static ServiceAdapter<DataSource> forDataSource() {
    return new ServiceAdapter<DataSource>() {
        @Override
        public Service toService(final DataSource dataSource, final Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    final SettableFuture<?> future = SettableFuture.create();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Connection connection = dataSource.getConnection();
                                connection.close();
                                future.set(null);
                            } catch (Exception e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    if (!(dataSource instanceof Closeable)) {
                        return Futures.immediateFuture(null);
                    }
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ((Closeable) dataSource).close();
                                future.set(null);
                            } catch (IOException e) {
                                future.setException(e);
                            }
                        }
                    });
                    return future;
                }
            };
        }
    };
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private static void uploadBlob(List<TestCase> tests, String blobAccessToken) {
    String urlBlob = "https://daylight.blob.core.windows.net/attachments";

    for (TestCase test : tests) {
        String blobName = test.getFileName();
        String body = test.getLog();

        URI requestUrl = null;// w ww.  ja v  a  2 s . c o m

        try {
            requestUrl = new URI(urlBlob + "/" + blobName + "?" + blobAccessToken);
        } catch (URISyntaxException e) {
        }

        test.setFileName(blobName);

        HttpPut request = new HttpPut(requestUrl);
        request.addHeader("x-ms-blob-type", "BlockBlob");

        try {
            request.setEntity(new StringEntity(body, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
        }

        final SettableFuture<Void> externalFuture = SettableFuture.create();

        ListenableFuture<HttpURLConnection> internalFuture = execute(request);

        Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
            @Override
            public void onFailure(Throwable throwable) {
                externalFuture.setException(throwable);
            }

            @Override
            public void onSuccess(HttpURLConnection connection) {
                try {
                    connection.getInputStream();
                    externalFuture.set(null);
                } catch (Throwable throwable) {
                    externalFuture.setException(throwable);
                }
            }
        });

        try {
            externalFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}