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: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);/*from   w  ww  .  j  a  v a 2  s  .  co  m*/
    }

    // 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: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();/*  ww  w  . j av  a2 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:com.google.NithPoints.examples.PrintPeers.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/*from ww w .  j a v  a 2  s.co  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  ww.j a  va2s .  co 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 = 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: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 w w w  .ja v a 2  s .  c o m*/
    //        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 ww w .java  2 s .co  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();
}

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();/*w w  w.ja v a2 s .  c o  m*/
    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();//from   w w  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://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   w  ww.  jav  a  2  s. 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://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.neoscoinj.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.init();//from ww w  . j av a2s.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;
    String filePrefix;
    if (args.length > 1 && args[1].equals("testnet")) {
        params = TestNet3Params.get();
        filePrefix = "forwarding-service-testnet";
    } else if (args.length > 1 && args[1].equals("regtest")) {
        params = RegTestParams.get();
        filePrefix = "forwarding-service-regtest";
    } else {
        params = MainNetParams.get();
        filePrefix = "forwarding-service";
    }
    // Parse the address given as the first parameter.
    forwardingAddress = new Address(params, args[0]);

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

    if (params == RegTestParams.get()) {
        // Regression test mode is designed for testing and development only, so there's no public network for it.
        // If you pick this mode, you're expected to be running a local "neoscoind -regtest" instance.
        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 neoscoinj 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) {
                            forwardCoins(tx);
                        }

                        @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) {
    }
}