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:de.xaniox.heavyspleef.core.stats.StatisticRecorder.java

@Subscribe
public void onGameStart(GameStartEvent event) {
    gameStartedAt = System.currentTimeMillis();
    Game game = event.getGame();//  w  w w.j  av a  2 s. c  o  m

    Set<SpleefPlayer> players = game.getPlayers();
    String[] playerNames = new String[players.size()];

    int i = 0;
    for (SpleefPlayer player : players) {
        playerNames[i++] = player.getName();
    }

    AsyncReadWriteHandler databaseHandler = heavySpleef.getDatabaseHandler();
    databaseHandler.getStatistics(playerNames, new FutureCallback<Map<String, Statistic>>() {

        @Override
        public void onSuccess(Map<String, Statistic> statistics) {
            loadedStatistics = statistics;
        }

        @Override
        public void onFailure(Throwable t) {
            logger.log(Level.SEVERE, "Could not load statistics for players when computing the rating: ", t);
        }
    });
}

From source file:org.hawkular.metrics.api.jaxrs.TenantsHandler.java

@POST
@ApiOperation(value = "Create a new tenant. ", notes = "Clients are not required to create explicitly create a "
        + "tenant before starting to store metric data. It is recommended to do so however to ensure that there "
        + "are no tenant id naming collisions and to provide default data retention settings. ")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tenant has been succesfully created."),
        @ApiResponse(code = 400, message = "Retention properties are invalid. ", response = Error.class),
        @ApiResponse(code = 409, message = "Given tenant id has already been created.", response = Error.class),
        @ApiResponse(code = 500, message = "An unexpected error occured while trying to create a tenant.", response = Error.class) })
public void createTenant(@Suspended AsyncResponse asyncResponse, @ApiParam(required = true) Tenant params) {
    ListenableFuture<Void> insertFuture = metricsService.createTenant(params);
    Futures.addCallback(insertFuture, new FutureCallback<Void>() {
        @Override/*from w  ww .  j  a v  a2 s.  c  o m*/
        public void onSuccess(Void result) {
            asyncResponse.resume(Response.ok().type(APPLICATION_JSON_TYPE).build());
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof TenantAlreadyExistsException) {
                TenantAlreadyExistsException exception = (TenantAlreadyExistsException) t;
                Error errors = new Error("A tenant with id [" + exception.getTenantId() + "] already exists");
                asyncResponse.resume(
                        Response.status(Status.CONFLICT).entity(errors).type(APPLICATION_JSON_TYPE).build());
                return;
            }
            Error errors = new Error("Failed to create tenant due to an " + "unexpected error: "
                    + Throwables.getRootCause(t).getMessage());
            asyncResponse.resume(Response.status(Status.INTERNAL_SERVER_ERROR).entity(errors)
                    .type(APPLICATION_JSON_TYPE).build());
        }
    });
}

From source file:io.bitsquare.trade.protocol.trade.tasks.buyer.SignAndPublishDepositTxAsBuyer.java

@Override
protected void run() {
    try {/*from  ww  w.j  a v a 2  s.  co  m*/
        runInterceptHook();

        log.debug("\n\n------------------------------------------------------------\n" + "Contract as json\n"
                + trade.getContractAsJson()
                + "\n------------------------------------------------------------\n");

        byte[] contractHash = Hash.getHash(trade.getContractAsJson());
        trade.setContractHash(contractHash);
        ArrayList<RawTransactionInput> buyerInputs = processModel.getRawTransactionInputs();
        WalletService walletService = processModel.getWalletService();
        AddressEntry buyerMultiSigAddressEntry = walletService
                .getOrCreateAddressEntry(processModel.getOffer().getId(), AddressEntry.Context.MULTI_SIG);
        Coin buyerInput = Coin.valueOf(buyerInputs.stream().mapToLong(input -> input.value).sum());
        buyerMultiSigAddressEntry.setCoinLockedInMultiSig(
                buyerInput.subtract(FeePolicy.getFixedTxFeeForTrades(trade.getOffer())));
        TradingPeer tradingPeer = processModel.tradingPeer;
        Transaction depositTx = processModel.getTradeWalletService().takerSignsAndPublishesDepositTx(false,
                contractHash, processModel.getPreparedDepositTx(), buyerInputs,
                tradingPeer.getRawTransactionInputs(), buyerMultiSigAddressEntry.getPubKey(),
                tradingPeer.getMultiSigPubKey(), trade.getArbitratorPubKey(),
                new FutureCallback<Transaction>() {
                    @Override
                    public void onSuccess(Transaction transaction) {
                        log.trace("takerSignAndPublishTx succeeded " + transaction);

                        trade.setDepositTx(transaction);
                        trade.setState(Trade.State.TAKER_PUBLISHED_DEPOSIT_TX);

                        complete();
                    }

                    @Override
                    public void onFailure(@NotNull Throwable t) {
                        failed(t);
                    }
                });
        trade.setDepositTx(depositTx);
    } catch (Throwable t) {
        failed(t);
    }
}

From source file:org.blackbananacoin.ext.curconvert.testlog.CurFutureMix.java

public void run() throws Exception {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }//from   w  w w .  j  a v  a  2 s.  c om
    });
    final GenericUrl urlBlockchain = new GenericUrl(EXURL_BLOCKCHAIN);
    final GenericUrl urlYahooTwd = new GenericUrl(EXURL_YAHOO_USDTWD);
    final HttpRequest requestBlockChain = requestFactory.buildGetRequest(urlBlockchain);

    final ListenableFuture<GenericJson> futureReqBlockChain = pool.submit(new Callable<GenericJson>() {
        public GenericJson call() throws Exception {
            GenericJson json = requestBlockChain.execute().parseAs(GenericJson.class);
            return json;
        }
    });

    Futures.addCallback(futureReqBlockChain, new FutureCallback<GenericJson>() {

        public void onSuccess(GenericJson result) {
            GenericJson json = result;
            System.out.println(json);
            Map ntdJson = (Map) json.get("USD");
            System.out.println(ntdJson.put("buy", 119.001));
            json.put("NTD", ntdJson);
            System.out.println(json);
        }

        public void onFailure(Throwable t) {
            // TODO Auto-generated method stub

        }
    });

    final HttpRequest requestYahoo = requestFactory.buildGetRequest(urlYahooTwd);
    final ListenableFuture<GenericJson> futureYahoo = pool.submit(new Callable<GenericJson>() {
        public GenericJson call() throws Exception {
            GenericJson json = requestYahoo.execute().parseAs(GenericJson.class);
            return json;
        }
    });

    Futures.addCallback(futureYahoo, new FutureCallback<GenericJson>() {

        public void onSuccess(GenericJson result) {
            GenericJson jsonYahoo = result;
            System.out.println(jsonYahoo);
            Map query = (Map) jsonYahoo.get("query");
            Map results = (Map) query.get("results");
            Map row = (Map) results.get("row");
            double twd = Double.parseDouble((String) row.get("col1"));
            System.out.println(twd);
        }

        public void onFailure(Throwable t) {
            // TODO Auto-generated method stub

        }
    });

}

From source file:org.apache.twill.internal.zookeeper.RewatchOnExpireWatcher.java

private void exists() {
    Futures.addCallback(client.exists(path, this), new FutureCallback<Stat>() {
        @Override//ww w  .  j  a  v a2 s. co m
        public void onSuccess(Stat stat) {
            // Since we know all callbacks and watcher are triggered from single event thread, there is no race condition.
            Object oldResult = lastResult.getReference();
            lastResult.compareAndSet(oldResult, null, true, false);

            if (stat != oldResult && (stat == null || !stat.equals(oldResult))) {
                if (stat == null) {
                    // previous stat is not null, means node deleted
                    process(new WatchedEvent(Event.EventType.NodeDeleted, Event.KeeperState.SyncConnected,
                            path));
                } else if (oldResult == null) {
                    // previous stat is null, means node created
                    process(new WatchedEvent(Event.EventType.NodeCreated, Event.KeeperState.SyncConnected,
                            path));
                } else {
                    // Otherwise, something changed on the node
                    process(new WatchedEvent(Event.EventType.NodeDataChanged, Event.KeeperState.SyncConnected,
                            path));
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (RetryUtils.canRetry(t)) {
                exists();
            } else {
                lastResult.set(null, false);
                LOG.error("Fail to re-set watch on exists for path " + path, t);
            }
        }
    });
}

From source file:de.schildbach.wallet.util.ChainServiceTransactionBroadcaster.java

private synchronized void doBroadcast(final Transaction tx) {
    log.info("Doing channel close broadcast for transaction with hash " + tx.getHashAsString());
    final ListenableFuture<Transaction> broadcastFuture;
    if (service != null)
        broadcastFuture = service.broadcastTransaction(tx);
    else/*w  w w. j a  va 2  s . c  o m*/
        broadcastFuture = null;
    if (broadcastFuture != null) {
        setBroadcastFutures.add(broadcastFuture);
        Futures.addCallback(broadcastFuture, new FutureCallback<Transaction>() {
            @Override
            public void onSuccess(Transaction result) {
                log.info("Channel close transaction broadcast successfully: " + tx.getHashAsString());
                setBroadcastFutures.remove(broadcastFuture);
                checkAllTransactionsBroadcasted();
            }

            @Override
            public void onFailure(Throwable t) {
                log.error("Channel close transaction failed to broadcast: " + tx.getHashAsString());
            }
        });
    } else
        log.info("Blockchain service is not connected, skipping channel close broadcast of transaction "
                + tx.getHashAsString());

    try {
        application.getWallet().receivePending(tx, new LinkedList<Transaction>());
    } catch (VerificationException e) {
        log.error("Channel close broadcast failed to commit to wallet.");
    }
}

From source file:org.opendaylight.toaster.impl.OpendaylightToaster.java

private void setToasterStatusUp(final Function<Boolean, Void> resultCallback) {

    WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
    tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Up));

    ListenableFuture<RpcResult<TransactionStatus>> commitFuture = tx.commit();

    Futures.addCallback(commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
        @Override// w ww . j av a 2 s. c  om
        public void onSuccess(RpcResult<TransactionStatus> result) {
            if (result.getResult() != TransactionStatus.COMMITED) {
                LOG.error("Failed to update toaster status: " + result.getErrors());
            }

            notifyCallback(result.getResult() == TransactionStatus.COMMITED);
        }

        @Override
        public void onFailure(Throwable t) {
            // We shouldn't get an OptimisticLockFailedException (or any ex) as no
            // other component should be updating the operational state.
            LOG.error("Failed to update toaster status", t);

            notifyCallback(false);
        }

        void notifyCallback(boolean result) {
            if (resultCallback != null) {
                resultCallback.apply(result);
            }
        }
    });
}

From source file:de.xaniox.heavyspleef.commands.CommandUpdate.java

@Command(name = "update", permission = Permissions.PERMISSION_UPDATE, usage = "/spleef update", descref = Messages.Help.Description.UPDATE)
public void onUpdateCommand(CommandContext context, final HeavySpleef heavySpleef) throws CommandException {
    final CommandSender sender = context.getSender() instanceof org.bukkit.entity.Player
            ? heavySpleef.getSpleefPlayer(context.getSender())
            : context.getSender();//from  w  ww . jav a 2 s  . c o  m

    DefaultConfig config = heavySpleef.getConfiguration(ConfigType.DEFAULT_CONFIG);
    UpdateSection section = config.getUpdateSection();

    //Don't continue if the user disabled updating checking or updating via command
    CommandValidate.isTrue(section.isUpdateChecking() && section.isUpdateCommandEnabled(),
            i18n.getString(Messages.Command.UPDATING_NOT_ENABLED));

    final Updater updater = heavySpleef.getUpdater();
    final Updater.CheckResult result = updater.getResult();

    CommandValidate.notNull(result, i18n.getString(Messages.Command.UPDATER_NOT_FINISHED_YET));
    CommandValidate.isTrue(result.isUpdateAvailable(), i18n.getVarString(Messages.Command.NO_UPDATE_AVAILABLE)
            .setVariable("this-version", heavySpleef.getPlugin().getDescription().getVersion()).toString());

    sender.sendMessage(i18n.getVarString(Messages.Command.STARTING_UPDATE)
            .setVariable("new-version", result.getVersion().toString()).toString());
    updater.update(sender, new FutureCallback<Void>() {

        @Override
        public void onSuccess(Void result) {
            File folder = updater.getUpdateFolder();

            sender.sendMessage(i18n.getVarString(Messages.Command.SUCCESSFULLY_PULLED_UPDATE)
                    .setVariable("folder", folder.getPath()).toString());
            sender.sendMessage(i18n.getString(Messages.Command.RESTART_SERVER_TO_UPDATE));

            if (sender instanceof Player) {
                heavySpleef.getLogger().log(Level.INFO,
                        "Successfully pulled the latest version of HeavySpleef into '" + folder.getPath()
                                + "'");
            }
        }

        @Override
        public void onFailure(Throwable t) {
            sender.sendMessage(i18n.getString(Messages.Command.ERROR_ON_UPDATING));
            heavySpleef.getLogger().log(Level.SEVERE,
                    "Could not update HeavySpleef to latest version v" + result.getVersion(), t);
        }
    });
}

From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApi.java

/**
 * Lists all deployments./*from   w ww . j av  a  2s  .com*/
 *
 * @param responseCallback
 * @throws IOException
 */
@Override
public void listAllAsync(final FutureCallback<ResourceList<Deployment>> responseCallback) throws IOException {
    ResourceList<Deployment> deploymentResourceList = new ResourceList<>();
    FutureCallback<ResourceList<Deployment>> callback = new FutureCallback<ResourceList<Deployment>>() {
        @Override
        public void onSuccess(@Nullable ResourceList<Deployment> result) {
            if (deploymentResourceList.getItems() == null) {
                deploymentResourceList.setItems(result.getItems());
            } else {
                deploymentResourceList.getItems().addAll(result.getItems());
            }
            if (result.getNextPageLink() != null && !result.getNextPageLink().isEmpty()) {
                try {
                    getObjectByPathAsync(result.getNextPageLink(), this,
                            new TypeReference<ResourceList<Deployment>>() {
                            });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                responseCallback.onSuccess(deploymentResourceList);
            }
        }

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

    getObjectByPathAsync(getBasePath(), callback, new TypeReference<ResourceList<Deployment>>() {
    });
}

From source file:de.cuseb.bilderbuch.images.ImageSearchService.java

public ImageResponse searchImages(final String query) {

    final ImageResponse response = new ImageResponse();
    final ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(searches.size()));

    for (final ImageSearch search : searches.values()) {

        if (!search.isEnabled()) {
            continue;
        }/* www. j a v a2s .c om*/

        ListenableFuture<List<Image>> searchResult = executor.submit(new Callable<List<Image>>() {
            @Override
            public List<Image> call() throws Exception {
                log.debug("starting enabled search " + search.getClass().getSimpleName());
                return search.searchImages(query);
            }
        });

        Futures.addCallback(searchResult, new FutureCallback<List<Image>>() {
            @Override
            public void onSuccess(List<Image> result) {
                log.debug(search.getClass().getSimpleName() + " result size: " + result.size());
                response.addImages(result);
            }

            @Override
            public void onFailure(Throwable t) {
                log.error(search.getClass().getSimpleName(), t);
            }
        });
    }

    try {
        executor.shutdown();
        executor.awaitTermination(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error("awaitTermination interrupted", e);
    }

    if (shuffle) {
        log.debug("shuffling result");
        response.shuffle();
    }

    return response;
}