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.metamx.rdiclient.example.FileInputMain.java

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.err.println(String.format("Usage: %s file1 file2 ...", FileInputMain.class.getCanonicalName()));
        System.exit(1);/*w ww . j  a v a2 s  .c om*/
    }

    // Start up RdiClient.
    final RdiClientConfig rdiConfig = RdiClientConfig.fromProperties(Props.fromFilename("conf/rdi.properties"));
    final RdiClient<byte[]> rdiClient = RdiClients.usingPassthroughSerializer(rdiConfig);
    rdiClient.start();

    // Track how many messages are sent and how many successes and failures are received.
    final AtomicLong sends = new AtomicLong(0);
    final AtomicLong acks = new AtomicLong(0);
    final AtomicLong fails = new AtomicLong(0);

    // Send data from files (in args) through RdiClient.
    for (final String arg : args) {
        final File file = new File(arg);
        try (final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line;
            while ((line = in.readLine()) != null) {
                // Asynchronously send a message.
                final ListenableFuture<RdiResponse> send = rdiClient.send(line.getBytes(Charsets.UTF_8));
                sends.incrementAndGet();

                // When the message is acknowledged (or fails), increment the appropriate counter.
                Futures.addCallback(send, new FutureCallback<RdiResponse>() {
                    @Override
                    public void onSuccess(RdiResponse result) {
                        acks.incrementAndGet();
                    }

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

    // Done sending messages.
    rdiClient.flush();

    // Wait for all messages to be sent.
    while (sends.get() != acks.get() + fails.get()) {
        Thread.sleep(100);
    }

    // Close the client.
    rdiClient.close();

    // Log and exit.
    log.info("Sent %,d messages with %,d acks and %,d fails.", sends.get(), acks.get(), fails.get());
}

From source file:com.amazonaws.services.kinesis.producer.sample.MetricsAwareSampleProducer.java

public static void main(String[] args) throws InterruptedException, ExecutionException {
    final long totalRecordsToPut = 50000;
    final int dataSize = 64;
    final long outstandingLimit = 5000;

    final AtomicLong sequenceNumber = new AtomicLong(0);
    final AtomicLong completed = new AtomicLong(0);
    final String timetstamp = Long.toString(System.currentTimeMillis());

    KinesisProducerConfiguration config = new KinesisProducerConfiguration().setRecordMaxBufferedTime(3000)
            .setMaxConnections(1).setRequestTimeout(60000).setRegion(SampleProducer.REGION);

    final KinesisProducer kinesisProducer = new KinesisProducer(config);

    // Result handler
    final FutureCallback<UserRecordResult> callback = new FutureCallback<UserRecordResult>() {
        @Override// ww  w.ja v  a2 s.  co m
        public void onFailure(Throwable t) {
            if (t instanceof UserRecordFailedException) {
                Attempt last = Iterables.getLast(((UserRecordFailedException) t).getResult().getAttempts());
                log.error(String.format("Record failed to put - %s : %s", last.getErrorCode(),
                        last.getErrorMessage()));
            }
            log.error("Exception during put", t);
            System.exit(1);
        }

        @Override
        public void onSuccess(UserRecordResult result) {
            completed.getAndIncrement();
        }
    };

    // Progress updates
    Thread progress = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long put = sequenceNumber.get();
                double putPercent = 100.0 * put / totalRecordsToPut;
                long done = completed.get();
                double donePercent = 100.0 * done / totalRecordsToPut;
                log.info(String.format("Put %d of %d so far (%.2f %%), %d have completed (%.2f %%)", put,
                        totalRecordsToPut, putPercent, done, donePercent));

                if (done == totalRecordsToPut) {
                    break;
                }

                // Numerous metrics are available from the KPL locally, as
                // well as uploaded to CloudWatch. See the metrics
                // documentation for details.
                //
                // KinesisProducer provides methods to retrieve metrics for
                // the current instance, with a customizable time window.
                // This allows us to get sliding window statistics in real
                // time for the current host.
                //
                // Here we're going to look at the number of user records
                // put over a 5 seconds sliding window.
                try {
                    for (Metric m : kinesisProducer.getMetrics("UserRecordsPut", 5)) {
                        // Metrics are emitted at different granularities, here
                        // we only look at the stream level metric, which has a
                        // single dimension of stream name.
                        if (m.getDimensions().size() == 1 && m.getSampleCount() > 0) {
                            log.info(String.format(
                                    "(Sliding 5 seconds) Avg put rate: %.2f per sec, success rate: %.2f, failure rate: %.2f, total attemped: %d",
                                    m.getSum() / 5, m.getSum() / m.getSampleCount() * 100,
                                    (m.getSampleCount() - m.getSum()) / m.getSampleCount() * 100,
                                    (long) m.getSampleCount()));
                        }
                    }
                } catch (Exception e) {
                    log.error("Unexpected error getting metrics", e);
                    System.exit(1);
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
        }
    });
    progress.start();

    // Put records
    while (true) {
        // We're going to put as fast as we can until we've reached the max
        // number of records outstanding.
        if (sequenceNumber.get() < totalRecordsToPut) {
            if (kinesisProducer.getOutstandingRecordsCount() < outstandingLimit) {
                ByteBuffer data = Utils.generateData(sequenceNumber.incrementAndGet(), dataSize);
                ListenableFuture<UserRecordResult> f = kinesisProducer.addUserRecord(SampleProducer.STREAM_NAME,
                        timetstamp, data);
                Futures.addCallback(f, callback);
            } else {
                Thread.sleep(1);
            }
        } else {
            break;
        }
    }

    // Wait for remaining records to finish
    while (kinesisProducer.getOutstandingRecordsCount() > 0) {
        kinesisProducer.flush();
        Thread.sleep(100);
    }

    progress.join();

    for (Metric m : kinesisProducer.getMetrics("UserRecordsPerKinesisRecord")) {
        if (m.getDimensions().containsKey("ShardId")) {
            log.info(String.format(
                    "%.2f user records were aggregated into each Kinesis record on average for shard %s, for a total of %d Kinesis records.",
                    m.getMean(), m.getDimensions().get("ShardId"), (long) m.getSampleCount()));
        }
    }

    kinesisProducer.destroy();
    log.info("Finished.");
}

From source file:com.google.NithPoints.examples.PrintPeers.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/*from   w w  w.  j  ava  2 s  .  c o  m*/
    System.out.println("=== DNS ===");
    printDNS();
    System.out.println("=== Version/chain heights ===");

    ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
    for (InetSocketAddress peer : dnsPeers)
        addrs.add(peer.getAddress());
    System.out.println("Scanning " + addrs.size() + " peers:");

    final NetworkParameters params = NetworkParameters.prodNet();
    final Object lock = new Object();
    final long[] bestHeight = new long[1];

    List<ListenableFuture<TCPNetworkConnection>> futures = Lists.newArrayList();
    for (final InetAddress addr : addrs) {
        final ListenableFuture<TCPNetworkConnection> future = TCPNetworkConnection.connectTo(params,
                new InetSocketAddress(addr, params.port), 1000 /* timeout */);
        futures.add(future);
        // Once the connection has completed version handshaking ...
        Futures.addCallback(future, new FutureCallback<TCPNetworkConnection>() {
            public void onSuccess(TCPNetworkConnection conn) {
                // Check the chain height it claims to have.
                VersionMessage ver = conn.getVersionMessage();
                long nodeHeight = ver.bestHeight;
                synchronized (lock) {
                    long diff = bestHeight[0] - nodeHeight;
                    if (diff > 0) {
                        System.out.println("Node is behind by " + diff + " blocks: " + addr);
                    } else if (diff == 0) {
                        System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
                        bestHeight[0] = nodeHeight;
                    } else if (diff < 0) {
                        System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
                        bestHeight[0] = nodeHeight;
                    }
                }
                conn.close();
            }

            public void onFailure(Throwable throwable) {
                System.out.println("Failed to talk to " + addr + ": " + throwable.getMessage());
            }
        });
    }
    // Wait for every tried connection to finish.
    Futures.successfulAsList(futures).get();
}

From source file:com.google.logicoin.examples.PrintPeers.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/* w w  w  .  j a v  a  2  s .  c om*/
    System.out.println("=== DNS ===");
    printDNS();
    System.out.println("=== Version/chain heights ===");

    ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
    for (InetSocketAddress peer : dnsPeers)
        addrs.add(peer.getAddress());
    System.out.println("Scanning " + addrs.size() + " peers:");

    final NetworkParameters params = MainNetParams.get();
    final Object lock = new Object();
    final long[] bestHeight = new long[1];

    List<ListenableFuture<TCPNetworkConnection>> futures = Lists.newArrayList();
    for (final InetAddress addr : addrs) {
        final ListenableFuture<TCPNetworkConnection> future = TCPNetworkConnection.connectTo(params,
                new InetSocketAddress(addr, params.getPort()), 1000 /* timeout */, null);
        futures.add(future);
        // Once the connection has completed version handshaking ...
        Futures.addCallback(future, new FutureCallback<TCPNetworkConnection>() {
            public void onSuccess(TCPNetworkConnection conn) {
                // Check the chain height it claims to have.
                VersionMessage ver = conn.getVersionMessage();
                long nodeHeight = ver.bestHeight;
                synchronized (lock) {
                    long diff = bestHeight[0] - nodeHeight;
                    if (diff > 0) {
                        System.out.println("Node is behind by " + diff + " blocks: " + addr);
                    } else if (diff == 0) {
                        System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
                        bestHeight[0] = nodeHeight;
                    } else if (diff < 0) {
                        System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
                        bestHeight[0] = nodeHeight;
                    }
                }
                conn.close();
            }

            public void onFailure(Throwable throwable) {
                System.out.println("Failed to talk to " + addr + ": " + throwable.getMessage());
            }
        });
    }
    // Wait for every tried connection to finish.
    Futures.successfulAsList(futures).get();
}

From source file:org.bitcoinj.examples.StakingService.java

public static void main(String[] args) throws Exception {

    // This line makes the log output more compact and easily read, especially when using the JDK log adapter.
    BriefLogFormatter.init();/* w  w  w . j a  v a  2 s . c o  m*/

    // Figure out which network we should connect to. Each one gets its own set of files.
    final NetworkParameters params;
    String filePrefix;
    params = MainNetParams.get();
    filePrefix = "forwarding-service";

    kit = new WalletAppKit(params, new File("."), filePrefix);
    //TODO Remove
    kit.connectToLocalHost();

    // Download the block chain and wait until it's done.
    kit.startAsync();
    kit.awaitRunning();

    // We want to know when we receive money.
    kit.wallet().addEventListener(new AbstractWalletEventListener() {
        @Override
        public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this).
            //
            // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
            Coin value = tx.getValueSentToMe(w);
            System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
            System.out.println("Transaction will be forwarded after it confirms.");
            // Wait until it's made it into the block chain (may run immediately if it's already there).
            //
            // For this dummy app of course, we could just forward the unconfirmed transaction. If it were
            // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
            // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
            // case of waiting for a block.
            Futures.addCallback(tx.getConfidence().getDepthFuture(1),
                    new FutureCallback<TransactionConfidence>() {
                        @Override
                        public void onSuccess(TransactionConfidence result) {
                            System.out.println("got it, printing private keys for importprivkey");
                            List<ECKey> issuedReceiveKeys = kit.wallet().getIssuedReceiveKeys();
                            for (ECKey code : issuedReceiveKeys) {
                                System.out.println(
                                        "private keys:" + code.getPrivateKeyEncoded(params).toString());
                            }
                            //stakeCoins(params, kit.peerGroup(),kit.wallet(),kit.store(),kit.chain());
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            // This kind of future can't fail, just rethrow in case something weird happens.
                            throw new RuntimeException(t);
                        }
                    });
        }
    });

    Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params);
    System.out.println("Send coins to: " + sendToAddress);
    List<ECKey> issuedReceiveKeys = kit.wallet().getIssuedReceiveKeys();
    for (ECKey code : issuedReceiveKeys) {
        System.out.println("private keys:" + code.getPrivateKeyEncoded(params).toString());
    }

    System.out.println("staking..");
    List<TransactionOutput> calculateAllSpendCandidates = kit.wallet().calculateAllSpendCandidates();
    for (TransactionOutput coin : calculateAllSpendCandidates) {
        System.out.println("coins:" + coin.getValue());
    }
    stakeCoins(params, kit.peerGroup(), kit.wallet(), kit.store(), kit.chain());
}

From source file:org.bitcoinj.examples.SendRequest.java

public static void main(String[] args) throws Exception {

    // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details.
    NetworkParameters params = TestNet3Params.get();
    WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example");
    kit.startAsync();//from   w  w w.j a  v  a2s. com
    kit.awaitRunning();

    // How much coins do we want to send?
    // The Coin class represents a monetary Bitcoin value.
    // We use the parseCoin function to simply get a Coin instance from a simple String.
    Coin value = Coin.parseCoin("0.09");

    // To which address you want to send the coins?
    // The Address class represents a Bitcoin address.
    Address to = Address.fromBase58(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw");
    System.out.println("Send money to: " + to.toString());

    // There are different ways to create and publish a SendRequest. This is probably the easiest one.
    // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html
    // 
    // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend.
    // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins.
    // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance.
    try {
        Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value);
        System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString());
        // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. 
    } catch (InsufficientMoneyException e) {
        System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue()
                + " satoshis are missing (including fees)");
        System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

        // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance.
        // Here we wait until the we have enough balance and display a notice.
        // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://github.com/google/guava/wiki/ListenableFutureExplained
        ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
        FutureCallback<Coin> callback = new FutureCallback<Coin>() {
            @Override
            public void onSuccess(Coin balance) {
                System.out.println("coins arrived and the wallet now has enough balance");
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("something went wrong");
            }
        };
        Futures.addCallback(balanceFuture, callback);
    }

    // shutting down 
    //kit.stopAsync();
    //kit.awaitTerminated();
}

From source file:org.guldenj.examples.SendRequest.java

public static void main(String[] args) throws Exception {

    // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details.
    NetworkParameters params = TestNet3Params.get();
    WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example");
    kit.startAsync();/*  w  w w .jav  a  2s.c o m*/
    kit.awaitRunning();

    System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

    // How much coins do we want to send?
    // The Coin class represents a monetary Bitcoin value.
    // We use the parseCoin function to simply get a Coin instance from a simple String.
    Coin value = Coin.parseCoin("0.09");

    // To which address you want to send the coins?
    // The Address class represents a Bitcoin address.
    Address to = Address.fromBase58(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw");

    // There are different ways to create and publish a SendRequest. This is probably the easiest one.
    // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://guldenj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html
    // 
    // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend.
    // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins.
    // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance.
    try {
        Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value);
        System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString());
        // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. 
    } catch (InsufficientMoneyException e) {
        System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue()
                + " satoshis are missing (including fees)");
        System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

        // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance.
        // Here we wait until the we have enough balance and display a notice.
        // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://github.com/google/guava/wiki/ListenableFutureExplained
        ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
        FutureCallback<Coin> callback = new FutureCallback<Coin>() {
            @Override
            public void onSuccess(Coin balance) {
                System.out.println("coins arrived and the wallet now has enough balance");
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("something went wrong");
            }
        };
        Futures.addCallback(balanceFuture, callback);
    }

    // shutting down 
    //kit.stopAsync();
    //kit.awaitTerminated();
}

From source file:org.litecoinj.examples.SendRequest.java

public static void main(String[] args) throws Exception {

    // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details.
    NetworkParameters params = TestNet3Params.get();
    WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example");
    kit.startAsync();/*from  ww w . ja  v a 2 s  . co  m*/
    kit.awaitRunning();

    System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

    // How much coins do we want to send?
    // The Coin class represents a monetary Bitcoin value.
    // We use the parseCoin function to simply get a Coin instance from a simple String.
    Coin value = Coin.parseCoin("0.09");

    // To which address you want to send the coins?
    // The Address class represents a Bitcoin address.
    Address to = Address.fromBase58(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw");

    // There are different ways to create and publish a SendRequest. This is probably the easiest one.
    // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html
    // 
    // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend.
    // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins.
    // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance.
    try {
        Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value);
        System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString());
        // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. 
    } catch (InsufficientMoneyException e) {
        System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue()
                + " satoshis are missing (including fees)");
        System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

        // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance.
        // Here we wait until the we have enough balance and display a notice.
        // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://github.com/google/guava/wiki/ListenableFutureExplained
        ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
        FutureCallback<Coin> callback = new FutureCallback<Coin>() {
            @Override
            public void onSuccess(Coin balance) {
                System.out.println("coins arrived and the wallet now has enough balance");
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("something went wrong");
            }
        };
        Futures.addCallback(balanceFuture, callback);
    }

    // shutting down 
    //kit.stopAsync();
    //kit.awaitTerminated();
}

From source file:io.xpydev.paycoinj.examples.ForwardingService.java

public static void main(String[] args) throws Exception {
    // This line makes the log output more compact and easily read, especially when using the JDK log adapter.
    BriefLogFormatter.initVerbose();/*from   ww  w . j  ava  2  s.c om*/
    //        if (args.length < 1) {
    //            System.err.println("Usage: address-to-send-back-to [regtest|testnet]");
    //            return;
    //        }

    // Figure out which network we should connect to. Each one gets its own set of files.
    NetworkParameters params = MainNetParams.get();
    String filePrefix = "forwarding-service";

    // Parse the address given as the first parameter.
    forwardingAddress = new Address(params, "PS43Jt2x3LXCkou2hZPaKjGwb1TQmAaihg");

    // Start up a basic app using a class that automates some boilerplate.
    kit = new WalletAppKit(params, new File("."), filePrefix);

    // Download the block chain and wait until it's done.
    kit.startAsync();
    kit.setBlockingStartup(false);
    kit.awaitRunning();
    //        kit.peerGroup().addPeerDiscovery(new SeedPeers(params), true);
    kit.peerGroup().setFastCatchupTimeSecs(1417219190L);

    // We want to know when we receive money.
    kit.wallet().addEventListener(new AbstractWalletEventListener() {
        @Override
        public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
            // Runs in the dedicated "user thread" (see peercoinj docs for more info on this).
            //
            // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
            Coin value = tx.getValueSentToMe(w);
            System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
            System.out.println("Transaction will be forwarded after it confirms.");
            // Wait until it's made it into the block chain (may run immediately if it's already there).
            //
            // For this dummy app of course, we could just forward the unconfirmed transaction. If it were
            // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
            // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
            // case of waiting for a block.
            Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<Transaction>() {
                @Override
                public void onSuccess(Transaction result) {
                    // "result" here is the same as "tx" above, but we use it anyway for clarity.
                    forwardCoins(result);
                }

                @Override
                public void onFailure(Throwable t) {
                    // This kind of future can't fail, just rethrow in case something weird happens.
                    throw new RuntimeException(t);
                }
            });
        }
    });

    Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params);
    System.out.println("Send coins to: " + sendToAddress);
    System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit.");

    try {
        Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException ignored) {
    }
}

From source file:com.google.litecoin.examples.PrintPeers.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/*from  w  w w.  j a va2 s.c o  m*/
    System.out.println("=== IRC ===");
    printIRC();
    System.out.println("=== DNS ===");
    printDNS();
    System.out.println("=== Version/chain heights ===");

    ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
    for (InetSocketAddress peer : dnsPeers)
        addrs.add(peer.getAddress());
    for (InetSocketAddress peer : ircPeers)
        addrs.add(peer.getAddress());
    System.out.println("Scanning " + addrs.size() + " peers:");

    final NetworkParameters params = NetworkParameters.prodNet();
    final Object lock = new Object();
    final long[] bestHeight = new long[1];

    List<ListenableFuture<TCPNetworkConnection>> futures = Lists.newArrayList();
    for (final InetAddress addr : addrs) {
        final ListenableFuture<TCPNetworkConnection> future = TCPNetworkConnection.connectTo(params,
                new InetSocketAddress(addr, params.port), 1000 /* timeout */);
        futures.add(future);
        // Once the connection has completed version handshaking ...
        Futures.addCallback(future, new FutureCallback<TCPNetworkConnection>() {
            public void onSuccess(TCPNetworkConnection conn) {
                // Check the chain height it claims to have.
                VersionMessage ver = conn.getVersionMessage();
                long nodeHeight = ver.bestHeight;
                synchronized (lock) {
                    long diff = bestHeight[0] - nodeHeight;
                    if (diff > 0) {
                        System.out.println("Node is behind by " + diff + " blocks: " + addr);
                    } else if (diff == 0) {
                        System.out.println("Node " + addr + " has " + nodeHeight + " blocks");
                        bestHeight[0] = nodeHeight;
                    } else if (diff < 0) {
                        System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr);
                        bestHeight[0] = nodeHeight;
                    }
                }
                conn.close();
            }

            public void onFailure(Throwable throwable) {
                System.out.println("Failed to talk to " + addr + ": " + throwable.getMessage());
            }
        });
    }
    // Wait for every tried connection to finish.
    Futures.successfulAsList(futures).get();
}