Example usage for com.google.common.util.concurrent Futures addCallback

List of usage examples for com.google.common.util.concurrent Futures addCallback

Introduction

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

Prototype

public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) 

Source Link

Document

Registers separate success and failure callbacks to be run when the Future 's computation is java.util.concurrent.Future#isDone() complete or, if the computation is already complete, immediately.

Usage

From source file:io.crate.action.sql.TransportSQLBulkAction.java

@Override
void executePlan(Executor executor, Analysis analysis, Plan plan,
        final ActionListener<SQLBulkResponse> listener, final SQLBulkRequest request, final long startTime) {
    if (!analysis.expectsAffectedRows()) {
        listener.onFailure(new UnsupportedOperationException(
                "Bulk operations for statements that return result sets is not supported"));
        return;/*from   w  w w .j  a  v a  2s.com*/
    }

    ListenableFuture<List<TaskResult>> future = Futures.allAsList(executor.executeBulk(plan));
    Futures.addCallback(future, new FutureCallback<List<TaskResult>>() {
        @Override
        public void onSuccess(@Nullable List<TaskResult> result) {
            listener.onResponse(createResponse(result, startTime));
        }

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

From source file:br.com.ufu.impl.SdnfirewallImpl.java

private void initializeDataTree(DataBroker db) {
    LOG.info("Preparing to initialize the rules registry");
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<RuleRegistry> iid = InstanceIdentifier.create(RuleRegistry.class);
    RuleRegistry greetingRegistry = new RuleRegistryBuilder().build();
    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, greetingRegistry);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<>("Failed to create rules registry", LOG));
}

From source file:org.retrostore.android.RetrostoreActivity.java

private void refreshApps() {
    setRefreshingStatus(true);//from  w  w w  . ja v a 2 s  .  c  om
    // FIXME: I don't see variable names for the API.
    Futures.addCallback(mFetcher.getAppsAsync(), new FutureCallback<List<App>>() {
        @Override
        public void onSuccess(List<App> result) {
            onAppsReceived(result);
            setRefreshingStatus(false);
        }

        @Override
        public void onFailure(Throwable t) {
            showToast("Something went wrong during the request: " + t.getMessage());
            setRefreshingStatus(false);
        }
    });
}

From source file:org.opendaylight.nemo.user.vnspacemanager.structurestyle.deleteintent.DeleteFlow.java

private void DeleteFlowInstance(UserId userId, FlowId flowId) {
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    UserKey userKey = new UserKey(userId);
    FlowKey flowKey = new FlowKey(flowId);

    InstanceIdentifier<Flow> flowid = InstanceIdentifier.builder(Users.class).child(User.class, userKey)
            .child(Objects.class).child(Flow.class, flowKey).build();
    t.delete(LogicalDatastoreType.CONFIGURATION, flowid);
    CheckedFuture<Void, TransactionCommitFailedException> f = t.submit();
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override/*  w w  w .j  ava 2 s.c om*/
        public void onFailure(Throwable t) {
            LOG.error("Could not write endpoint base container", t);
        }

        @Override
        public void onSuccess(Void result) {
        }
    });
}

From source file:org.opendaylight.nemo.user.vnspacemanager.structurestyle.deleteintent.DeleteNode.java

private void DeleteNodeInstance(UserId userId, NodeId nodeId) {
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    UserKey userKey = new UserKey(userId);
    NodeKey nodeKey = new NodeKey(nodeId);

    InstanceIdentifier<Node> nodeid = InstanceIdentifier.builder(Users.class).child(User.class, userKey)
            .child(Objects.class).child(Node.class, nodeKey).build();
    t.delete(LogicalDatastoreType.CONFIGURATION, nodeid);
    CheckedFuture<Void, TransactionCommitFailedException> f = t.submit();
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override/*from  w w  w .  ja va  2  s.c o  m*/
        public void onFailure(Throwable t) {
            LOG.error("Could not write endpoint base container", t);
        }

        @Override
        public void onSuccess(Void result) {
        }
    });
}

From source file:org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl.java

@Override
public void run() {
    while (true) {
        forgetSuccessfulTransactions();//from   ww w.j a  v  a  2s.c  om

        List<TransactionCommand> commands = null;
        try {
            commands = extractCommands();
        } catch (InterruptedException e) {
            LOG.warn("Extracting commands was interrupted.", e);
            continue;
        }

        ReadWriteTransaction transactionInFlight = null;
        try {
            for (TransactionCommand command : commands) {
                final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
                transactionInFlight = transaction;
                recordPendingTransaction(command, transaction);
                command.execute(transaction);
                Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
                    @Override
                    public void onSuccess(final Void result) {
                        successfulTransactionQueue.offer(transaction);
                    }

                    @Override
                    public void onFailure(final Throwable throwable) {
                        // NOOP - handled by failure of transaction chain
                    }
                });
            }
        } catch (IllegalStateException e) {
            if (transactionInFlight != null) {
                // TODO: This method should distinguish exceptions on which the command should be
                // retried from exceptions on which the command should NOT be retried.
                // Then it should retry only the commands which should be retried, otherwise
                // this method will retry commands which will never be successful forever.
                failedTransactionQueue.offer(transactionInFlight);
            }
            LOG.warn("Failed to process an update notification from OVS.", e);
        }
    }
}

From source file:com.google.cloud.pubsub.PollingSubscriberConnection.java

private void pullMessages(final Duration backoff) {
    ListenableFuture<PullResponse> pullResult = stub
            .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)
            .pull(PullRequest.newBuilder().setSubscription(subscription).setMaxMessages(DEFAULT_MAX_MESSAGES)
                    .setReturnImmediately(true).build());

    Futures.addCallback(pullResult, new FutureCallback<PullResponse>() {
        @Override/*  w ww.  j a v  a  2 s .  c o  m*/
        public void onSuccess(PullResponse pullResponse) {
            processReceivedMessages(pullResponse.getReceivedMessagesList());
            if (pullResponse.getReceivedMessagesCount() == 0) {
                // No messages in response, possibly caught up in backlog, we backoff to avoid 
                // slamming the server.
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            pullMessages(INITIAL_BACKOFF);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (!(cause instanceof StatusRuntimeException)
                    || isRetryable(((StatusRuntimeException) cause).getStatus())) {
                logger.error("Failed to pull messages (recoverable): " + cause.getMessage(), cause);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            notifyFailed(cause);
        }
    });
}

From source file:io.v.x.jni.test.fortune.FortuneServerImpl.java

@Override
public ListenableFuture<Integer> streamingGet(final VContext context, ServerCall call,
        final ServerStream<String, Boolean> stream) {
    final SettableFuture<Integer> future = SettableFuture.create();
    final AtomicInteger numSent = new AtomicInteger(0);
    Futures.addCallback(InputChannels.withCallback(stream, new InputChannelCallback<Boolean>() {
        @Override/*from   www.  j  av a 2s  . com*/
        public ListenableFuture<Void> onNext(Boolean result) {
            if (lastAddedFortune == null) {
                return Futures.immediateFailedFuture(new NoFortunesException(context));
            }
            return Futures.transform(stream.send(lastAddedFortune), new Function<Void, Void>() {
                @Override
                public Void apply(Void input) {
                    numSent.incrementAndGet();
                    return null;
                }
            });
        }
    }), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            future.set(numSent.get());
        }

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

From source file:eu.point.registry.impl.LinkRegistryUtils.java

/**
 * The method which deletes from the registry a specific entry.
 *
 * @param key The key of the entry to be deleted.
 */// w w w.  j  a va  2 s .c  om
public void deleteFromLinkRegistry(String key) {
    LOG.debug("Removing from Link registry key {}.", key);
    WriteTransaction transaction = db.newReadWriteTransaction();
    InstanceIdentifier<LinkRegistryEntry> iid = toInstanceIdentifier(key);

    transaction.delete(LogicalDatastoreType.OPERATIONAL, iid);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<Void>("Failed to delete from Link registry", LOG));
}

From source file:xyz.cloudbans.bukkit.command.TempBanCommand.java

@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
    // /tempban <player> <duration> <reason>
    if (!sender.hasPermission("cloudbans.ban.tempban")) {
        sender.sendMessage(ChatColor.RED + "You don't have enough permissions for that.");
        return true;
    }/*from   w ww .j av a  2 s  .  c om*/

    if (args.length < 2) {
        sender.sendMessage(ChatColor.RED + "Your missing arguments for this command.");
        return false;
    }

    if (sender instanceof BlockCommandSender) {
        sender.sendMessage(ChatColor.RED
                + "For security reasons this command can only executed by a player or the console!");
        return true;
    }

    BanRequestBuilder builder = new BanRequestBuilder();
    builder.setServer(config.getServerUuid());

    if (args.length > 2) {
        String[] reason = Arrays.copyOfRange(args, 2, args.length);
        String finalReason = Joiner.on(" ").join(reason);
        builder.setDescription(finalReason);
    }

    if (sender instanceof Player) {
        builder.setIssuer(((Player) sender).getUniqueId());
    }

    try {
        builder.setValidUntil(TimeParser.addToNow(args[1]));
    } catch (NumberFormatException exception) {
        sender.sendMessage(ChatColor.RED + "The given time is invalid.");
    }

    BanRequest request = builder.build();
    CommandUtils.parseTarget(request, args[0]);

    Future<BanResponse> future = client.createBan(request);
    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future, executor),
            new FutureCallback<BanResponse>() {
                @Override
                public void onSuccess(BanResponse result) {
                    switch (result.getBan().getDelayState()) {
                    case EXECUTED:
                        sender.sendMessage(ChatColor.GREEN + "Ban executed");
                        break;
                    case QUEUED:
                        sender.sendMessage(ChatColor.GREEN + "Ban will be executed soon.");
                        break;
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    sender.sendMessage(ChatColor.RED + "Ban was not executed successfully.");
                    LOGGER.log(Level.SEVERE, "An error occurred while executing ban request.", t);
                }
            });
    return true;
}