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.apache.pulsar.io.cassandra.CassandraAbstractSink.java

@Override
public void write(Record<byte[]> record) {
    KeyValue<K, V> keyValue = extractKeyValue(record);
    BoundStatement bound = statement.bind(keyValue.getKey(), keyValue.getValue());
    ResultSetFuture future = session.executeAsync(bound);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        @Override//  w  ww .  j  a v a  2  s .  c  o  m
        public void onSuccess(ResultSet result) {
            record.ack();
        }

        @Override
        public void onFailure(Throwable t) {
            record.fail();
        }
    });
}

From source file:org.opendaylight.ocpplugin.impl.services.SalDeviceMgmtServiceImpl.java

@Override
public Future<RpcResult<HealthCheckOutput>> healthCheck(final HealthCheckInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.HealthCheckOutput>> future = healthCheck
            .handleServiceCall(input);/*ww w .  ja va 2s  . c om*/
    final SettableFuture<RpcResult<HealthCheckOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.HealthCheckOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.HealthCheckOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.HealthCheckOutput output = result
                            .getResult();
                    HealthCheckOutputBuilder builder = new HealthCheckOutputBuilder();
                    builder.setResult(output.getResult());
                    RpcResultBuilder<HealthCheckOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

                @Override
                public void onFailure(final Throwable t) {
                    RpcResultBuilder<HealthCheckOutput> rpcResultBuilder = RpcResultBuilder.failed();
                    finalFuture.set(rpcResultBuilder.build());
                }
            });

    return finalFuture;
}

From source file:org.opendaylight.controller.remote.rpc.RpcBroker.java

private void executeRpc(final ExecuteRpc msg) {
    LOG.debug("Executing rpc {}", msg.getRpc());
    final NormalizedNode<?, ?> input = RemoteRpcInput.from(msg.getInputNormalizedNode());
    final SchemaPath schemaPath = SchemaPath.create(true, msg.getRpc());
    final ActorRef sender = getSender();
    final ActorRef self = self();

    try {//from  w  ww  .  j  ava2 s .  c  o  m
        final CheckedFuture<DOMRpcResult, DOMRpcException> future = rpcService.invokeRpc(schemaPath, input);

        Futures.addCallback(future, new FutureCallback<DOMRpcResult>() {
            @Override
            public void onSuccess(final DOMRpcResult result) {
                if (result.getErrors() != null && (!result.getErrors().isEmpty())) {
                    final String message = String.format("Execution of RPC %s failed", msg.getRpc());
                    Collection<RpcError> errors = result.getErrors();
                    if (errors == null || errors.size() == 0) {
                        errors = Arrays.asList(RpcResultBuilder.newError(ErrorType.RPC, null, message));
                    }

                    sender.tell(new akka.actor.Status.Failure(new RpcErrorsException(message, errors)), self);
                } else {
                    final Node serializedResultNode;
                    if (result.getResult() == null) {
                        serializedResultNode = null;
                    } else {
                        serializedResultNode = NormalizedNodeSerializer.serialize(result.getResult());
                    }

                    LOG.debug("Sending response for execute rpc : {}", msg.getRpc());

                    sender.tell(new RpcResponse(serializedResultNode), self);
                }
            }

            @Override
            public void onFailure(final Throwable t) {
                LOG.error(
                        "executeRpc for {} failed with root cause: {}. For exception details, enable Debug logging.",
                        msg.getRpc(), Throwables.getRootCause(t));
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Detailed exception for execute RPC failure :{}", t);
                }
                sender.tell(new akka.actor.Status.Failure(t), self);
            }
        });
    } catch (final Exception e) {
        sender.tell(new akka.actor.Status.Failure(e), sender);
    }
}

From source file:org.guldenj.testing.MockTransactionBroadcaster.java

@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
    // Use a lock just to catch lock ordering inversions e.g. wallet->broadcaster.
    lock.lock();//from  w  w  w  . j av a2 s.c o  m
    try {
        SettableFuture<Transaction> result = SettableFuture.create();
        broadcasts.put(new TxFuturePair(tx, result));
        Futures.addCallback(result, new FutureCallback<Transaction>() {
            @Override
            public void onSuccess(Transaction result) {
                try {
                    wallet.receivePending(result, null);
                } catch (VerificationException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onFailure(Throwable t) {
            }
        });
        return TransactionBroadcast.createMockBroadcast(tx, result);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        lock.unlock();
    }
}

From source file:com.continuuity.weave.internal.zookeeper.FailureRetryZKClient.java

@Override
public OperationFuture<String> create(final String path, final byte[] data, final CreateMode createMode,
        final boolean createParent) {
    final SettableOperationFuture<String> result = SettableOperationFuture.create(path,
            Threads.SAME_THREAD_EXECUTOR);
    Futures.addCallback(super.create(path, data, createMode, createParent),
            new OperationFutureCallback<String>(OperationType.CREATE, System.currentTimeMillis(), path, result,
                    new Supplier<OperationFuture<String>>() {
                        @Override
                        public OperationFuture<String> get() {
                            return FailureRetryZKClient.super.create(path, data, createMode, createParent);
                        }//from ww  w.  ja  v a 2s  . c o m
                    }));
    return result;
}

From source file:dao.ClientCassandra.java

public static void saveEndConnection(Connection_Cassandra msg) {
    PreparedStatement ps = session.prepare(closeConnection);
    BatchStatement batch = new BatchStatement();

    batch.add(ps.bind(msg.getConnection_id(), msg.getDb_id(), msg.getDb_user_name(),
            msg.getEnd_limit_timestamp().getTime()));

    Futures.addCallback(session.executeAsync(batch), callback());

}

From source file:odl.example.impl.ApplicationRegistryUtils.java

public void initializeDataTree() {
    LOG.info("Preparing to initialize the application registry");
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<ApplicationRegistry> iid = InstanceIdentifier.create(ApplicationRegistry.class);
    ApplicationRegistry greetingRegistry = new ApplicationRegistryBuilder().build();
    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, greetingRegistry);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<>("Failed to create application registry", LOG));
}

From source file:org.hawkular.metrics.api.undertow.MetricsHandlers.java

public void setup(RoutingHandler commonHandler) {

    commonHandler.add(Methods.POST, "/{tenantId}/gauges", new AsyncHttpHandler() {

        public void handleRequestAsync(HttpServerExchange exchange) throws Exception {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = mapper.readValue(Channels.newInputStream(exchange.getRequestChannel()),
                    Map.class);
            Map<String, Deque<String>> queryParams = exchange.getQueryParameters();

            String tenantId = queryParams.get("tenantId").getFirst();
            String name = body.get("name").toString();
            Integer dataRetention = Integer.parseInt(body.get("dataRetention").toString());

            Gauge metric = new Gauge(tenantId, new MetricId(name), null, dataRetention);
            ListenableFuture<Void> future = metricsService.createMetric(metric);
            Futures.addCallback(future, new FutureCallback<Void>() {
                @Override/*ww  w  .  j  av a 2 s.c  o  m*/
                public void onSuccess(Void result) {
                    exchange.setResponseCode(200);
                }

                @Override
                public void onFailure(Throwable t) {
                    exchange.setResponseCode(501);
                }
            });
        }
    });

    commonHandler.add(Methods.POST, "/{tenantId}/gauges/data", new AsyncHttpHandler() {
        public void handleRequestAsync(HttpServerExchange exchange) throws Exception {
            List<Gauge> metrics = mapper.readValue(Channels.newInputStream(exchange.getRequestChannel()),
                    new TypeReference<List<GaugeData>>() {
                    });
            Map<String, Deque<String>> queryParams = exchange.getQueryParameters();
            String tenantId = queryParams.get("tenantId").getFirst();

            if (metrics == null || metrics.size() == 0) {
                exchange.setResponseCode(200);
                return;
            }

            for (Gauge metric : metrics) {
                metric.setTenantId(tenantId);
            }

            ListenableFuture<Void> future = metricsService.addGaugeData(metrics);
            Futures.addCallback(future, new FutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                    exchange.setResponseCode(200);
                }

                @Override
                public void onFailure(Throwable t) {
                    exchange.setResponseCode(501);
                }
            });
        }
    });
}

From source file:com.example.office.ui.fragments.ContactsFragment.java

@Override
protected void initList() {
    try {//from ww  w .  j  a  va2 s.com
        // Should have checked for persisted data but we don't do caching for Contacts.

        NetworkState nState = NetworkUtils.getNetworkState(getActivity());
        if (nState.getWifiConnectedState()
                || nState.getDataState() == NetworkUtils.NETWORK_UTILS_CONNECTION_STATE_CONNECTED) {

            Futures.addCallback(Me.getContacts().fetchAsync(), new FutureCallback<Void>() {
                @Override
                public void onFailure(Throwable t) {
                    onError(t);
                    isInitializing = false;
                }

                @Override
                public void onSuccess(Void result) {
                    onDone(new ArrayList<IContact>(Me.getContacts()));
                    isInitializing = false;
                }
            });

        } else {
            Toast.makeText(getActivity(), R.string.data_connection_no_data_connection, Toast.LENGTH_LONG)
                    .show();
        }
    } catch (Exception e) {
        Logger.logApplicationException(e, getClass().getSimpleName() + "initList(): Error.");
    }
}

From source file:org.opendaylight.openflowplugin.impl.statistics.services.compatibility.AbstractCompatibleStatService.java

@Override
public ListenableFuture<RpcResult<O>> handleAndNotify(final I input,
        final NotificationPublishService notificationPublishService) {
    // prepare emulated xid
    final long emulatedXid = compatibilityXidSeed.incrementAndGet();
    final TransactionId emulatedTxId = new TransactionId(BigInteger.valueOf(emulatedXid));

    // do real processing
    final ListenableFuture<RpcResult<List<MultipartReply>>> rpcResultListenableFuture = handleServiceCall(
            input);// w w w. j  a  v a  2 s .  co  m

    // hook notification publishing
    Futures.addCallback(rpcResultListenableFuture, new FutureCallback<RpcResult<List<MultipartReply>>>() {
        @Override
        public void onSuccess(@Nullable RpcResult<List<MultipartReply>> result) {
            if (result != null && result.isSuccessful()) {
                // transform rpc result (raw multipart) to notification
                final N flowNotification = transformToNotification(result.getResult(), emulatedTxId);
                notificationPublishService.offerNotification(flowNotification);
            } else {
                LOG.debug("compatibility callback failed - NOT emitting notification: {}",
                        input.getClass().getSimpleName());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.debug("compatibility callback crashed - NOT emitting notification: {}",
                    input.getClass().getSimpleName(), t);
        }
    });

    return RpcResultBuilder.<O>success(buildTxCapableResult(emulatedTxId)).buildFuture();
}