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:xyz.cloudbans.bukkit.command.BanCommand.java

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

    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 > 1) {
        String[] reason = Arrays.copyOfRange(args, 1, args.length);
        String finalReason = Joiner.on(" ").join(reason);
        builder.setDescription(finalReason);
    }

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

    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;
}

From source file:org.opendaylight.dsbenchmark.txchain.TxchainDomWrite.java

@Override
public void executeList() {
    int txSubmitted = 0;
    int writeCnt = 0;

    DOMTransactionChain chain = domDataBroker.createTransactionChain(this);
    LogicalDatastoreType dsType = getDataStoreType();
    DOMDataWriteTransaction tx = chain.newWriteOnlyTransaction();

    YangInstanceIdentifier pid = YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME)
            .build();//w w  w  .  j  a  v a 2s . c o  m
    for (MapEntryNode element : this.list) {
        YangInstanceIdentifier yid = pid.node(
                new NodeIdentifierWithPredicates(OuterList.QNAME, element.getIdentifier().getKeyValues()));

        if (oper == StartTestInput.Operation.PUT) {
            tx.put(dsType, yid, element);
        } else {
            tx.merge(dsType, yid, element);
        }

        writeCnt++;

        // Start performing the operation; submit the transaction at every n-th operation
        if (writeCnt == writesPerTx) {
            txSubmitted++;
            Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
                @Override
                public void onSuccess(final Void result) {
                    txOk++;
                }

                @Override
                public void onFailure(final Throwable t) {
                    LOG.error("Transaction failed, {}", t);
                    txError++;
                }
            });
            tx = chain.newWriteOnlyTransaction();
            dsType = getDataStoreType();
            writeCnt = 0;
        }
    }

    // *** Clean up and close the transaction chain ***
    // Submit the outstanding transaction even if it's empty and wait for it to finish
    // We need to empty the transaction chain before closing it

    try {
        txSubmitted++;
        tx.submit().checkedGet();
        txOk++;
    } catch (TransactionCommitFailedException e) {
        LOG.error("Transaction failed", e);
        txError++;
    }
    try {
        chain.close();
    } catch (IllegalStateException e) {
        LOG.error("Transaction close failed,", e);
    }
    LOG.info("Transactions: submitted {}, completed {}", txSubmitted, (txOk + txError));
}

From source file:org.apache.tez.dag.app.dag.RootInputInitializerRunner.java

public void runInputInitializers(List<RootInputLeafOutputDescriptor<InputDescriptor>> inputs) {
    for (RootInputLeafOutputDescriptor<InputDescriptor> input : inputs) {
        ListenableFuture<List<Event>> future = executor
                .submit(new InputInitializerCallable(input, vertexID, dagName, vertexName, dagUgi, numTasks));
        Futures.addCallback(future, createInputInitializerCallback(input.getEntityName()));
    }//w  w  w.  j a v a  2s  .c om
}

From source file:io.crate.executor.transport.task.DistributedMergeTask.java

@Override
public void start() {
    logger.trace("start");
    int i = 0;/* w w w  . ja  v  a  2 s .  co  m*/
    final NodeMergeRequest request = new NodeMergeRequest(mergeNode);
    final CountDownLatch countDownLatch;

    // if we have an upstream result, we need to register failure handlers here, in order to
    // handle bootstrapping failures on the data providing side
    if (upstreamResult == null) {
        countDownLatch = new CountDownLatch(0);
    } else {
        countDownLatch = new CountDownLatch(upstreamResult.size());
        logger.trace("upstreamResult.size: " + upstreamResult.size());
        // consume the upstream result
        for (final ListenableFuture<TaskResult> upstreamFuture : upstreamResult) {
            Futures.addCallback(upstreamFuture, new FutureCallback<TaskResult>() {
                @Override
                public void onSuccess(@Nullable TaskResult result) {
                    assert result != null;
                    logger.trace("successful collect Future size: " + result.rows().length);
                    countDownLatch.countDown();
                }

                @Override
                public void onFailure(@Nonnull Throwable t) {
                    if (t instanceof RemoteTransportException) {
                        t = t.getCause();
                    }
                    for (ListenableFuture<QueryResult> result : results) {
                        ((SettableFuture<QueryResult>) result).setException(t);
                    }
                    countDownLatch.countDown();
                    logger.error("remote collect request failed", t);
                }
            });
        }
    }

    for (final String node : mergeNode.executionNodes()) {
        logger.trace("prepare executionNode: {} of {}", node, mergeNode.executionNodes().size());
        final int resultIdx = i;
        transportMergeNodeAction.startMerge(node, request, new ActionListener<NodeMergeResponse>() {

            @Override
            public void onResponse(NodeMergeResponse nodeMergeResponse) {
                logger.trace("startMerge.onResponse: {} of {}", node, mergeNode.executionNodes().size());
                ((SettableFuture<QueryResult>) results.get(resultIdx))
                        .set(new QueryResult(nodeMergeResponse.rows()));
            }

            @Override
            public void onFailure(Throwable e) {
                logger.trace("startMerge.onFailure: {} of {}", node, mergeNode.executionNodes().size());
                if (e instanceof RemoteTransportException) {
                    e = e.getCause();
                }
                if (e instanceof UnknownUpstreamFailure) {
                    // prioritize the upstreams original exception over the UnknownUpstreamFailure
                    try {
                        countDownLatch.await(1, TimeUnit.SECONDS);
                    } catch (InterruptedException e1) {
                        logger.error("Interrupted waiting for upstream exception", e1);
                    }
                }
                SettableFuture<QueryResult> result = (SettableFuture<QueryResult>) results.get(resultIdx);
                result.setException(e);
                logger.error("Failure getting NodeMergeResponse: ", e);
            }
        });

        i++;
    }
}

From source file:org.apache.flink.batch.connectors.cassandra.CassandraOutputFormat.java

@Override
public void writeRecord(OUT record) throws IOException {
    if (exception != null) {
        throw new IOException("write record failed", exception);
    }/*from w  w  w  .ja  va 2  s.c  o m*/

    Object[] fields = new Object[record.getArity()];
    for (int i = 0; i < record.getArity(); i++) {
        fields[i] = record.getField(i);
    }
    ResultSetFuture result = session.executeAsync(prepared.bind(fields));
    Futures.addCallback(result, callback);
}

From source file:gobblin.compliance.validation.ComplianceValidationJob.java

public void run() throws IOException {
    Preconditions.checkNotNull(this.finder, "Dataset finder class is not set");
    List<Dataset> datasets = this.finder.findDatasets();
    this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size()));
    for (final Dataset dataset : datasets) {
        ListenableFuture<Void> future = this.service.submit(new Callable<Void>() {
            @Override/* w ww .  ja  v a  2s .co m*/
            public Void call() throws Exception {
                if (dataset instanceof ValidatableDataset) {
                    ((ValidatableDataset) dataset).validate();
                } else {
                    log.warn("Not an instance of " + ValidatableDataset.class + " Dataset won't be validated "
                            + dataset.datasetURN());
                }
                return null;
            }
        });
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void result) {
                ComplianceValidationJob.this.finishCleanSignal.get().countDown();
                log.info("Successfully validated: " + dataset.datasetURN());
            }

            @Override
            public void onFailure(Throwable t) {
                ComplianceValidationJob.this.finishCleanSignal.get().countDown();
                log.warn("Exception caught when validating " + dataset.datasetURN() + ".", t);
                ComplianceValidationJob.this.throwables.add(t);
                ComplianceValidationJob.this.eventSubmitter.submit(
                        ComplianceEvents.Validation.FAILED_EVENT_NAME,
                        ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY,
                                ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY,
                                dataset.datasetURN()));
            }
        });
    }
}

From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMTransactionChainAdapter.java

@Override
public void close() {
    if (finished) {
        // already closed, do nothing
        return;//ww  w. j  a v  a2  s. c om
    }

    checkReadTxClosed();
    checkWriteTxClosed();
    Futures.addCallback(writeTxSubmitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable final Void result) {
            txChainListener.onTransactionChainSuccessful(ShardedDOMTransactionChainAdapter.this);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            // We don't have to do nothing here,
            // tx should take car of it
        }
    });

    cachedDataTreeService.closeProducers();
    finished = true;
}

From source file:org.opendaylight.ocpplugin.impl.OcpPluginProviderImpl.java

private void startRadioHeadConnections() {
    final List<ListenableFuture<Boolean>> starterChain = new ArrayList<>(radioHeadConnectionProviders.size());
    for (final RadioHeadConnectionProvider radioHeadConnectionPrv : radioHeadConnectionProviders) {
        radioHeadConnectionPrv.setRadioHeadConnectionHandler(connectionManager);
        final ListenableFuture<Boolean> isOnlineFuture = radioHeadConnectionPrv.startup();
        starterChain.add(isOnlineFuture);
    }/*from  w  w w.ja va  2 s.  co  m*/

    final ListenableFuture<List<Boolean>> srvStarted = Futures.allAsList(starterChain);
    Futures.addCallback(srvStarted, new FutureCallback<List<Boolean>>() {
        @Override
        public void onSuccess(final List<Boolean> result) {
            LOG.info("All radioHeadConnectionProviders are up and running ({}).", result.size());
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.warn("Some radioHeadConnectionProviders failed to start.", t);
        }
    });
}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

public static void watchDeleted(final ZKClient zkClient, final String path,
        final SettableFuture<String> completion) {

    Futures.addCallback(zkClient.exists(path, new Watcher() {
        @Override//from   w  w w . j  a  v a  2 s  .c om
        public void process(WatchedEvent event) {
            if (!completion.isDone()) {
                if (event.getType() == Event.EventType.NodeDeleted) {
                    completion.set(path);
                } else {
                    watchDeleted(zkClient, path, completion);
                }
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            if (result == null) {
                completion.set(path);
            }
        }

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

From source file:com.reigon.spotifydownloader.SpotifyProcessor.java

public void process(String url) throws UnsupportedEncodingException {

    //Decodeamos y encodeamos los nombres de usuario
    String user = URLEncoder.encode(URLDecoder.decode(getUser(url), "UTF-8"), "UTF-8");
    String idP = getIdPlayList(url);

    System.out.println("Usuario: " + user + " - ID PlayList: " + idP);
    textui.printText("Usuario: " + user + " - ID PlayList: " + idP);

    // Create an API instance. The default instance connects to https://api.spotify.com/.
    api = Api.builder().clientId(clientId).clientSecret(clientSecret).redirectURI("https://www.spotify.com/es/")
            .build();/*  w ww .  j ava2s  .  c  om*/
    final ClientCredentialsGrantRequest request = api.clientCredentialsGrant().build();

    /* Use the request object to make the request, either asynchronously (getAsync) or synchronously (get) */
    final SettableFuture<ClientCredentials> responseFuture = request.getAsync();

    /* Add callbacks to handle success and failure */
    Futures.addCallback(responseFuture, new FutureCallback<ClientCredentials>() {
        @Override
        public void onSuccess(ClientCredentials clientCredentials) {

            /* Set access token on the Api object so that it's used going forward */
            api.setAccessToken(clientCredentials.getAccessToken());
            textui.printText("Procediendo a analizar la playList...");
            //Sacamos el numero de tracks que tiene la playlist
            final PlaylistRequest infoPlayListRequest = api.getPlaylist(user, idP).build();

            try {
                final Playlist playlist = infoPlayListRequest.get();
                numTracks = playlist.getTracks().getTotal();
                System.out.println("Num Tracks PlayList: " + numTracks);
                textui.printText("Num Tracks PlayList: " + numTracks);
                //Sacamos las canciones pasando el offset y el limite
                for (int i = 0; i <= numTracks - 1; i += 30) {
                    cargarCanciones(i, 30, user, idP, textui);
                }
            } catch (Exception e) {
                System.out.println("Something went wrong!" + e.getMessage());
                textui.printText("Something went wrong!" + e.getMessage());
            }

        }

        @Override
        public void onFailure(Throwable throwable) {
            /* An error occurred while getting the access token. This is probably caused by the client id or
            * client secret is invalid. */
        }
    });

}