Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

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

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();//  w ww  .  j  a  v  a  2  s .co  m
    System.out.println("Connecting to node");
    final NetworkParameters params = MainNetParams.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    peerGroup.addAddress(new PeerAddress(params, InetAddress.getLocalHost()));
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = Sha256Hash.wrap("ffd26b8e5212b442d9cd0241a53c4fd1381bb24937844eb31b839b31c23dd057");
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stop();
}

From source file:com.matthewmitchell.nubitsj.examples.FetchTransactions.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/*from w ww  .  j a  v  a  2 s  .co  m*/
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.startAsync();
    peerGroup.awaitRunning();
    peerGroup.addAddress(new PeerAddress(InetAddress.getLocalHost(), params.getPort()));
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = new Sha256Hash(args[0]);
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stopAsync();
    peerGroup.awaitTerminated();
}

From source file:com.skry.ingestion.FetchTransactions.java

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();//from  w w  w  .  j a  v  a 2  s. com
    System.out.println("Connecting to node");
    final NetworkParameters params = TestNet3Params.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    BlockChain chain = new BlockChain(params, blockStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.start();
    //        peerGroup.addAddress(new PeerAddress(InetAddress.getLocalHost(), params.getPort()));
    peerGroup.addAddress(new PeerAddress(InetAddress.getByAddress("192.168.1.121", "8333".getBytes())));

    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = Sha256Hash.wrap(args[0]);
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stop();
}

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

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();/*from ww w.  ja va2 s .co  m*/
    System.out.println("Connecting to node");
    final NetworkParameters params = MainNetParams.get();

    BlockStore blockStore = new MemoryBlockStore(params);
    ValidHashStore validHashStore = new ValidHashStore(new File("."));
    BlockChain chain = new BlockChain(params, blockStore, validHashStore);
    PeerGroup peerGroup = new PeerGroup(params, chain);
    peerGroup.startAsync();
    peerGroup.awaitRunning();
    peerGroup.addAddress(new PeerAddress(InetAddress.getLocalHost(), params.getPort()));
    peerGroup.waitForPeers(1).get();
    Peer peer = peerGroup.getConnectedPeers().get(0);

    Sha256Hash txHash = new Sha256Hash(args[0]);
    ListenableFuture<Transaction> future = peer.getPeerMempoolTransaction(txHash);
    System.out.println("Waiting for node to send us the requested transaction: " + txHash);
    Transaction tx = future.get();
    System.out.println(tx);

    System.out.println("Waiting for node to send us the dependencies ...");
    List<Transaction> deps = peer.downloadDependencies(tx).get();
    for (Transaction dep : deps) {
        System.out.println("Got dependency " + dep.getHashAsString());
    }

    System.out.println("Done.");
    peerGroup.stopAsync();
    peerGroup.awaitTerminated();
}

From source file:com.example.retrofit.CustomCallAdapter.java

public static void main(String... args) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://httpbin.org")
            .addCallAdapterFactory(new ListenableFutureCallAdapterFactory()).build();

    HttpBinService service = retrofit.create(HttpBinService.class);
    final ListenableFuture<Ip> ip = service.getIp();
    ip.addListener(new Runnable() {
        @Override//from   w  w w  . jav a 2  s .com
        public void run() {
            try {
                System.out.println("IP: " + ip.get().origin);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }, Executors.newSingleThreadExecutor());
}

From source file:retrofit.CustomCallAdapter.java

public static void main(String... args) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://httpbin.org")
            .addCallAdapterFactory(new ListenableFutureCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create()).build();

    HttpBinService service = retrofit.create(HttpBinService.class);
    final ListenableFuture<Ip> ip = service.getIp();
    ip.addListener(new Runnable() {
        @Override//w ww  .  ja va2s.  com
        public void run() {
            try {
                System.out.println("IP: " + ip.get().origin);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }, Executors.newSingleThreadExecutor());
}

From source file:com.vsct.strowgr.monitoring.gui.cassandra.CassandraClient.java

public static void main(String[] args) throws ExecutionException, InterruptedException {

    String node = System.getenv("cassandra.node");
    String keyspace = System.getenv("cassandra.keyspace");
    String entrypoint = System.getenv("entrypoint");
    String date = System.getenv("date");
    String since = System.getenv("since");
    showPayload = Boolean.valueOf(System.getenv("showPayload"));

    Date sinceDate = null;/*from  w  w  w  .j  ava2s .co  m*/
    if (since != null && since.contains("s"))
        sinceDate = Date.from(LocalDateTime.now().minusSeconds(Long.valueOf(since.replace("s", "")))
                .atZone(ZoneId.systemDefault()).toInstant());
    if (since != null && since.contains("m"))
        sinceDate = Date.from(LocalDateTime.now().minusMinutes(Long.valueOf(since.replace("m", "")))
                .atZone(ZoneId.systemDefault()).toInstant());
    if (since != null && since.contains("h"))
        sinceDate = Date.from(LocalDateTime.now().minusHours(Long.valueOf(since.replace("h", "")))
                .atZone(ZoneId.systemDefault()).toInstant());

    if (node == null | keyspace == null | entrypoint == null | date == null | since == null
            | showPayload == null | sinceDate == null) {
        System.out.println("You must provide these environment variables :");
        System.out.println("\t- cassandra.node");
        System.out.println("\t- cassandra.keyspace");
        System.out.println("\t- entrypoint (ex. PAO/REL1)");
        System.out.println("\t- date (ex. 2016-04-28)");
        System.out.println("\t- since (ex. 10s|25m|2h)");
        System.out.println("\t- showPayload (true or false)");
        return;
    }

    System.out.println("Initiating connection with Cassandra on " + node);

    Cluster cluster = Cluster.builder().addContactPoint(node)
            .withQueryOptions(new QueryOptions().setFetchSize(500)).build();

    Session session = cluster.connect(keyspace);

    String query;
    if (showPayload) {
        query = "select event_timestamp,event_name,correlation_id,payload from entrypoint_by_day where id='"
                + entrypoint + "' and date='" + date + "' and event_timestamp > " + sinceDate.getTime() + ";";
    } else {
        query = "select event_timestamp,event_name,correlation_id from entrypoint_by_day where id='"
                + entrypoint + "' and date='" + date + "' and event_timestamp > " + sinceDate.getTime() + ";";
    }

    System.out.println("Cassandra query=" + query + "\n");

    Statement statement = new SimpleStatement(query);

    ResultSetFuture resultSetFuture = session.executeAsync(statement);
    ListenableFuture<Multimap<Key, Value>> futur = Futures.transform(resultSetFuture, iterate(result));

    futur.get().keySet().forEach(k -> {
        System.out.print(k.correlationId + " END");
        result.get(k).forEach(v -> {
            if (showPayload) {
                System.out.print(" <- " + v.name + "(" + v.timestamp + ")|" + v.payload + "|");
            } else {
                System.out.print(" <- " + v.name + "(" + v.timestamp + ")");
            }
        });
        System.out.println(" <- BEGIN");
    });

    System.out.println("\nClosing Cassandra connection");
    session.close();
    cluster.close();
}

From source file:de.dfki.kiara.example.CalcTest2.java

public static void main(String[] args) throws Exception {
    try (Context context = Kiara.createContext();
            Connection connection = context.openConnection("http://localhost:8080/service")) {

        MethodBinding<Calc> binder = new MethodBinding<>(Calc.class).bind("calc.add", "add")
                .bind("calc.add", "add1").bind("calc.add", "add_serializer")
                .bind("calc.add", "add_deserializer");

        Calc calc = connection.getServiceInterface(binder);
        RemoteInterface ri = (RemoteInterface) calc;
        ConnectionBase conn = ri.getConnection();
        Message msg = calc.add_serializer(10, 12);
        System.out.println("Message data: " + new String(msg.getMessageData().array()));

        msg = calc.add_serializer(2, 30);
        System.out.println("Message data: " + new String(msg.getMessageData().array()));

        int a = 3;
        int b = 4;
        int c = 10;
        ListenableFuture<Integer> temp = calc.add(Futures.<Integer>immediateFuture(a),
                Futures.<Integer>immediateFuture(b));
        int result = calc.add(temp, Futures.<Integer>immediateFuture(c)).get();

        System.out.println("Performed remote call: " + a + "+" + b + "+" + c + " = " + result);

        temp = calc.add1(Futures.<Integer>immediateFuture(a), b);
        System.out.println("Performed remote call: " + a + "+" + b + " = " + temp.get());

        String res = "{\"jsonrpc\":\"2.0\", \"result\": 22}";
        Message responseMsg = msg.getProtocol().createMessageFromData(ByteBuffer.wrap(res.getBytes("UTF-8")));
        result = calc.add_deserializer(responseMsg);
        System.out.println("Result of deserialization of: " + res + " -> " + result);

    } finally {//from  ww  w . ja  v a  2  s.c  om
        Kiara.shutdownGracefully();
    }
}

From source file:com.google.devtools.build.lib.remote.util.Utils.java

/**
 * Returns the result of a {@link ListenableFuture} if successful, or throws any checked {@link
 * Exception} directly if it's an {@link IOException} or else wraps it in an {@link IOException}.
 */// ww w. java  2s  . co m
public static <T> T getFromFuture(ListenableFuture<T> f) throws IOException, InterruptedException {
    try {
        return f.get();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        }
        throw new IOException(e.getCause());
    }
}

From source file:com.spotify.folsom.KetamaRunner.java

private static void checkStatus(final ListenableFuture<?> future, final Set<MemcacheStatus> expected)
        throws Throwable {
    try {//from  w w  w  . ja  v  a2s  . co m
        final Object v = future.get();
        if (v == null && expected.contains(MemcacheStatus.KEY_NOT_FOUND)) {
            // ok
        } else if (v != null && expected.contains(MemcacheStatus.OK)) {
            // ok
        } else {
            throw new IllegalStateException();
        }
    } catch (final ExecutionException e) {
        throw e.getCause();
    }
}