Example usage for com.google.common.util.concurrent FutureCallback FutureCallback

List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback

Introduction

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

Prototype

FutureCallback

Source Link

Usage

From source file:com.facebook.presto.server.AsyncResponseUtils.java

private static <T> FutureCallback<T> toAsyncResponse(final AsyncResponse asyncResponse) {
    return new FutureCallback<T>() {
        @Override/*from   ww w.j  av a 2 s  .  c  o  m*/
        public void onSuccess(T value) {
            checkArgument(!(value instanceof ResponseBuilder),
                    "Value is a ResponseBuilder. Did you forget to call build?");
            asyncResponse.resume(value);
        }

        @Override
        public void onFailure(Throwable t) {
            asyncResponse.resume(t);
        }
    };
}

From source file:com.microsoft.office.integration.test.MiscellaneousAsyncTestCase.java

public void testFetch() {
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.getDraftsAsync(), new FutureCallback<IFolder>() {
        public void onFailure(Throwable t) {
            reportError(t);/*from   w  w  w. j a  v a2  s .c om*/
            counter.countDown();
        }

        public void onSuccess(IFolder drafts) {
            try {
                final IMessages messages = drafts.getMessagesAsync().get();
                // actual server request for messages will be executed in this line by calling size; response will be cached
                final int size = messages.size();

                final IMessage message = Messages.newMessage();
                message.setSubject("fetch test");
                Me.flush();

                // verify that local cache has no changes after flush (size will return old value)
                assertEquals(size, messages.size());

                final CountDownLatch cdl = new CountDownLatch(1);
                Futures.addCallback(messages.fetchAsync(), new FutureCallback<Void>() {
                    public void onFailure(Throwable t) {
                        reportError(t);
                        cdl.countDown();
                    }

                    public void onSuccess(Void result) {
                        try {
                            assertEquals(size + 1, messages.size());
                            Me.getMessages().delete(message.getId());
                            Me.flush();
                        } catch (Throwable t) {
                            reportError(t);
                        }

                        cdl.countDown();
                    }
                });

                cdl.await();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testSize() timed out");
        }
    } catch (InterruptedException e) {
        fail("testSize() has been interrupted");
    }
}

From source file:com.msopentech.o365.outlookServices.OutlookServicesMethodsImpl.java

/**
 * Adds default callback that send future's result back to plugin
 *
 * @param future Future to add callback to
 * @param context Plugin context used to send future result back to plugin
 * @param resolver Dependency resolver, that used to serialize future results
 *//*from   ww  w .  j av  a  2s.co  m*/
static <T> void addCordovaCallback(final ListenableFuture<T> future, final CallbackContext context,
        final DependencyResolver resolver) {
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T t) {
            if (t != null) {
                String result = resolver.getJsonSerializer().serialize(t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
            } else {
                context.sendPluginResult(new PluginResult(PluginResult.Status.OK));
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, throwable.getMessage()));
        }
    });
}

From source file:com.microsoft.sharepointservices.http.JavaHttpConnection.java

@Override
public ListenableFuture<Response> execute(final Request request) {

    request.addHeader(USER_AGENT_HEADER, Platform.getUserAgent());

    final SettableFuture<Response> future = SettableFuture.create();
    final NetworkRunnable target = new NetworkRunnable(request, future);

    final NetworkThread networkThread = new NetworkThread(target) {
        @Override/*  w w  w. j a  va2 s .  c  om*/
        void releaseAndStop() {
            try {
                target.closeStreamAndConnection();
            } catch (Throwable error) {
            }
        }
    };

    Futures.addCallback(future, new FutureCallback<Response>() {
        @Override
        public void onFailure(Throwable arg0) {
            networkThread.releaseAndStop();
        }

        @Override
        public void onSuccess(Response response) {
        }
    });

    networkThread.start();
    return future;
}

From source file:net.flutterflies.fwapaderp.discord.Bot.java

/**
 * Bot constructor// w  ww .  j  a v  a 2  s  .  c o  m
 * @param plugin The instance of the plugin
 * @param email Email address of the Discord account
 * @param password Password of the Discord account
 */
public Bot(FwapaDerp plugin, String email, String password) {
    // Try to log in with the credentials out of the configuration file
    bot = Javacord.getApi(email, password);

    // Try to connect
    bot.connect(new FutureCallback<DiscordAPI>() {
        @Override
        public void onSuccess(final DiscordAPI api) {
            // Print the token, mainly for debug and health check
            String token = api.getToken();
            plugin.getLogger().info("[DISCORD] Token: " + token);

            // Get the channel and server the bot is connected to
            general = api.getChannelById(plugin.getGameManager().getSettings().getChannelID());
            server = general.getServer();

            // Send a message signifying the successful login attempt
            general.sendMessage(plugin.getGameManager().getSettings().getMsgOnJoin());
        }

        @Override
        public void onFailure(Throwable t) {
            // login failed
            t.printStackTrace();
        }
    });
}

From source file:io.bitsquare.trade.protocol.trade.tasks.taker.BroadcastTakeOfferFeeTx.java

@Override
protected void run() {
    try {// ww  w.  ja  v a2s .  c o  m
        runInterceptHook();
        processModel.getTradeWalletService().broadcastTx(processModel.getTakeOfferFeeTx(),
                new FutureCallback<Transaction>() {
                    @Override
                    public void onSuccess(Transaction transaction) {
                        log.debug("Trading fee published successfully. Transaction ID = "
                                + transaction.getHashAsString());

                        trade.setState(Trade.State.TAKER_FEE_PAID);
                        complete();
                    }

                    @Override
                    public void onFailure(@NotNull Throwable t) {
                        appendToErrorMessage(
                                "Trading fee payment failed. Maybe your network connection was lost. Please try again.");
                        failed(t);
                    }
                });
    } catch (Throwable t) {
        failed(t);
    }
}

From source file:com.microsoft.office.integration.test.NavigationPropertiesAsyncTestCase.java

public void testCreateEntityAndAccessNavigationPropertyFailure() {
    // succeeded if got IllegalStateException
    counter = new CountDownLatch(1);
    Futures.addCallback(Messages.newMessage().getAttachmentsAsync(), new FutureCallback<IAttachments>() {
        public void onFailure(Throwable t) {
            if (!(t instanceof IllegalStateException)) {
                reportError(t);//from  w  w  w . ja  va 2  s. c om
            }
            counter.countDown();
        }

        public void onSuccess(IAttachments result) {
            reportError(new Exception("createEntityAndAccessNavigationPropertyFailureTest failed"));
            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testSize() timed out");
        }
    } catch (InterruptedException e) {
        fail("testSize() has been interrupted");
    }
}

From source file:org.glowroot.central.util.MoreFutures.java

public static <V> ListenableFuture<V> onFailure(ListenableFuture<V> future, Runnable onFailure) {
    SettableFuture<V> outerFuture = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override// www  .j a  va2s  .  c  o  m
        public void onSuccess(V result) {
            outerFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            logger.debug(t.getMessage(), t);
            onFailure.run();
            outerFuture.setException(t);
        }
    }, MoreExecutors.directExecutor());
    return outerFuture;
}

From source file:de.btobastian.javacordbot.commands.DownloadAvatarCommand.java

@Command(aliases = {
        "+downloadAvatar" }, description = "Downloads the avatar of the user!", usage = "+downloadAvatar <@user>")
public String onCommand(DiscordAPI api, String command, String[] args, Message message) {
    if (args.length != 1 || message.getMentions().size() != 1) {
        return "The first argument must be a user!";
    }/* ww w.  j av  a  2  s. c om*/
    message.getMentions().get(0).getAvatarAsByteArray(new FutureCallback<byte[]>() {
        @Override
        public void onSuccess(byte[] bytes) {
            try {
                message.replyFile(new ByteArrayInputStream(bytes), "avatar.jpg", "Avatar:",
                        new FutureCallback<Message>() {
                            @Override
                            public void onSuccess(Message message) {

                            }

                            @Override
                            public void onFailure(Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        });
            } catch (Exception e) {
                message.reply("Error: " + e.getMessage());
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            message.reply("Error: " + throwable.getMessage());
        }
    });
    return null;
}

From source file:net.javacrumbs.futureconverter.java8guava.FutureConverter.java

private static <T> CompletableFuture<T> buildCompletableFutureFromListenableFuture(
        final ListenableFuture<T> listenableFuture) {
    CompletableFuture<T> completable = new CompletableListenableFuture<T>(listenableFuture);
    Futures.addCallback(listenableFuture, new FutureCallback<T>() {
        @Override/*from w  w  w.  ja va  2  s. c o  m*/
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    }, MoreExecutors.directExecutor());
    return completable;
}