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:org.opendaylight.dsbenchmark.txchain.TxchainBaWrite.java

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

    BindingTransactionChain chain = bindingDataBroker.createTransactionChain(this);
    WriteTransaction tx = chain.newWriteOnlyTransaction();
    LogicalDatastoreType dsType = getDataStoreType();

    for (OuterList element : this.list) {
        InstanceIdentifier<OuterList> iid = InstanceIdentifier.create(TestExec.class).child(OuterList.class,
                element.getKey());/*w  ww  . j  a  v  a 2  s  .  c  om*/

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

        writeCnt++;

        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.opendaylight.tl1.impl.MDSal.java

public static List<String> getAllDevices() {

    InstanceIdentifier<DeviceRegistry> identifier = InstanceIdentifier.create(DeviceRegistry.class);
    ReadOnlyTransaction transaction = dbroker.newReadOnlyTransaction();

    ReadOnlyTransaction readTx = dbroker.newReadOnlyTransaction();
    ListenableFuture<Optional<DeviceRegistry>> dataFuture = readTx.read(LogicalDatastoreType.OPERATIONAL,
            identifier);/* w w  w.  j  a va  2 s  . c o m*/
    Futures.addCallback(dataFuture, new FutureCallback<Optional<DeviceRegistry>>() {
        @Override
        public void onSuccess(final Optional<DeviceRegistry> result) {
            if (result.isPresent()) {
                // data are present in data store.
                allDevices = ExtractIps(result.get().getDeviceRegistryEntry());
                //doSomething(result.get());
            } else {
                // data are not present in data store.
                allDevices = null;
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            // Error during read
        }

    });

    return allDevices;
}

From source file:com.metamx.druid.indexing.coordinator.ThreadPoolTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    final TaskToolbox toolbox = toolboxFactory.build(task);
    final ListenableFuture<TaskStatus> statusFuture = exec
            .submit(new ExecutorServiceTaskRunnerCallable(task, toolbox));

    final TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task, statusFuture);
    runningItems.add(taskRunnerWorkItem);
    Futures.addCallback(statusFuture, new FutureCallback<TaskStatus>() {
        @Override/*from  w  ww.j  a  va2 s .  com*/
        public void onSuccess(TaskStatus result) {
            runningItems.remove(taskRunnerWorkItem);
        }

        @Override
        public void onFailure(Throwable t) {
            runningItems.remove(taskRunnerWorkItem);
        }
    });

    return statusFuture;
}

From source file:org.anhonesteffort.chnlbrkr.chnlzr.IdleChnlzrController.java

public boolean registerAndSwap(ServerHandler connection, String chnlzrId) {
    if (!queue.containsKey(chnlzrId)) {
        Futures.addCallback(factory.create(connection, chnlzrId), new ChnlzrConnectionCallback(chnlzrId));
        log.debug(chnlzrId + " registered");
        return true;
    } else {/*from w  ww  . j a  va 2 s .co m*/
        return false;
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private static void uploadBlob(List<TestCase> tests, String blobAccessToken) {
    String urlBlob = "https://daylight.blob.core.windows.net/attachments";

    for (TestCase test : tests) {
        String blobName = test.getFileName();
        String body = test.getLog();

        URI requestUrl = null;// ww  w .  j av  a2 s . c  o m

        try {
            requestUrl = new URI(urlBlob + "/" + blobName + "?" + blobAccessToken);
        } catch (URISyntaxException e) {
        }

        test.setFileName(blobName);

        HttpPut request = new HttpPut(requestUrl);
        request.addHeader("x-ms-blob-type", "BlockBlob");

        try {
            request.setEntity(new StringEntity(body, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
        }

        final SettableFuture<Void> externalFuture = SettableFuture.create();

        ListenableFuture<HttpURLConnection> internalFuture = execute(request);

        Futures.addCallback(internalFuture, new FutureCallback<HttpURLConnection>() {
            @Override
            public void onFailure(Throwable throwable) {
                externalFuture.setException(throwable);
            }

            @Override
            public void onSuccess(HttpURLConnection connection) {
                try {
                    connection.getInputStream();
                    externalFuture.set(null);
                } catch (Throwable throwable) {
                    externalFuture.setException(throwable);
                }
            }
        });

        try {
            externalFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.orangerhymelabs.helenus.cassandra.table.ViewService.java

public void readAll(String database, String table, FutureCallback<List<View>> callback) {
    Futures.addCallback(readAll(database, table), callback);
}

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

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

    BindingTransactionChain chain = bindingDataBroker.createTransactionChain(this);
    WriteTransaction tx = chain.newWriteOnlyTransaction();

    for (long l = 0; l < outerListElem; l++) {
        InstanceIdentifier<OuterList> iid = InstanceIdentifier.create(TestExec.class).child(OuterList.class,
                new OuterListKey((int) l));
        tx.delete(LogicalDatastoreType.CONFIGURATION, iid);

        writeCnt++;//from w ww. j  av  a  2s.  c om

        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();
            writeCnt = 0;
        }
    }

    // Submit the outstanding transaction even if it's empty and wait for it to finish
    // We need to empty the chain before closing it
    try {
        if (writeCnt > 0) {
            txSubmitted++;
        }
        tx.submit().checkedGet();
    } catch (TransactionCommitFailedException e) {
        LOG.error("Transaction failed", e);
    }
    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.TezTestServiceCommunicator.java

public void submitWork(SubmitWorkRequestProto request, String host, int port,
        final ExecuteRequestCallback<SubmitWorkResponseProto> callback) {
    ListenableFuture<SubmitWorkResponseProto> future = executor
            .submit(new SubmitWorkCallable(request, host, port));
    Futures.addCallback(future, new FutureCallback<SubmitWorkResponseProto>() {
        @Override/*from  w w w.  j a  v  a  2 s  .c o  m*/
        public void onSuccess(SubmitWorkResponseProto result) {
            callback.setResponse(result);
        }

        @Override
        public void onFailure(Throwable t) {
            callback.indicateError(t);
        }
    });

}

From source file:org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.didm.vendor.extreme.rev150211.ExtremeModule.java

protected static InstanceIdentifier<DeviceTypeInfo> registerDeviceTypeInfo(DataBroker dataBroker) {
    LOG.debug("registerDeviceTypeInfo -> " + dataBroker);

    InstanceIdentifier<DeviceTypeInfo> path = createKeyedDeviceTypeInfoPath(DEVICE_TYPE);

    WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
    writeTx.merge(LogicalDatastoreType.CONFIGURATION, path, DEVICE_TYPE_INFO, true);

    CheckedFuture<Void, TransactionCommitFailedException> future = writeTx.submit();
    Futures.addCallback(future, new FutureCallback<Void>() {
        public void onSuccess(Void result) {
            LOG.info("registerDeviceTypeInfo onSuccess");
        }/*ww  w .j  a va  2  s.  c o  m*/

        public void onFailure(Throwable t) {
            LOG.error("registerDeviceTypeInfo onFailure -> " + t);
        }
    });

    return path;
}

From source file:org.opendaylight.controller.clustering.it.provider.PeopleProvider.java

@Override
public Future<RpcResult<Void>> addPerson(AddPersonInput input) {
    log.info("RPC addPerson : adding person [{}]", input);

    PersonBuilder builder = new PersonBuilder(input);
    final Person person = builder.build();
    final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();

    // Each entry will be identifiable by a unique key, we have to create that identifier
    final InstanceIdentifier.InstanceIdentifierBuilder<Person> personIdBuilder = InstanceIdentifier
            .<People>builder(People.class).child(Person.class, person.getKey());
    final InstanceIdentifier personId = personIdBuilder.build();
    // Place entry in data store tree
    WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
    tx.put(LogicalDatastoreType.CONFIGURATION, personId, person, true);

    Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
        @Override/*from   w  w w. ja  va2 s.  c o m*/
        public void onSuccess(final Void result) {
            log.info("RPC addPerson : person added successfully [{}]", person);
            rpcRegistration.registerPath(PersonContext.class, personId);
            log.info("RPC addPerson : routed rpc registered for instance ID [{}]", personId);
            futureResult.set(RpcResultBuilder.<Void>success().build());
        }

        @Override
        public void onFailure(final Throwable t) {
            log.error(String.format("RPC addPerson : person addition failed [%s]", person), t);
            futureResult.set(RpcResultBuilder.<Void>failed()
                    .withError(RpcError.ErrorType.APPLICATION, t.getMessage()).build());
        }
    });
    return futureResult;
}