Example usage for com.google.common.util.concurrent FutureCallback onFailure

List of usage examples for com.google.common.util.concurrent FutureCallback onFailure

Introduction

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

Prototype

void onFailure(Throwable t);

Source Link

Document

Invoked when a Future computation fails or is canceled.

Usage

From source file:com.vmware.photon.controller.clustermanager.clients.MesosClient.java

/**
 * This method calls into the Mesos API endpoint to retrieve the master leader ip addresses.
 *
 * @param connectionString          connectionString of the master Node in the Cluster
 * @param callback                  callback that is invoked on completion of the operation.
 * @throws IOException//from   ww  w.  ja  v  a 2 s .co m
 */
public void getMasterLeader(final String connectionString, final FutureCallback<String> callback)
        throws IOException {

    final RestClient restClient = new RestClient(connectionString, this.httpClient);

    org.apache.http.concurrent.FutureCallback futureCallback = new org.apache.http.concurrent.FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {

            final String leaderStringPrefix = "master@";
            MasterState response;
            try {
                restClient.checkResponse(result, HttpStatus.SC_OK);
                response = objectMapper.readValue(result.getEntity().getContent(),
                        new TypeReference<MasterState>() {
                        });
            } catch (Throwable e) {
                callback.onFailure(e);
                return;
            }

            if (StringUtils.isNotBlank(response.getLeader())
                    && response.getLeader().startsWith(leaderStringPrefix)) {
                callback.onSuccess(response.getLeader().replace(leaderStringPrefix, "http://"));
            } else {
                callback.onFailure(new RuntimeException("failed to get leader address."));
            }
        }

        @Override
        public void failed(Exception ex) {
            callback.onFailure(ex);
        }

        @Override
        public void cancelled() {
            callback.onFailure(new RuntimeException("getMasterLeader was cancelled"));
        }
    };

    restClient.performAsync(RestClient.Method.GET, MASTER_STATE_PATH, null, futureCallback);
}

From source file:com.vmware.photon.controller.clustermanager.statuschecks.MesosStatusChecker.java

private void checkSlaves(final String connectionString, final List<String> slaveAddresses,
        final FutureCallback<Boolean> callback) {
    logger.info("Checking Mesos: {}", connectionString);

    try {//  w  w w .  j ava2s  .  com
        mesosClient.getNodeAddressesAsync(connectionString, new FutureCallback<Set<String>>() {
            @Override
            public void onSuccess(@Nullable Set<String> nodes) {
                try {
                    for (String nodeAddress : slaveAddresses) {
                        if (!nodes.contains(nodeAddress)) {
                            logger.info("Node not registered with Mesos Master: {}", nodeAddress);
                            callback.onSuccess(false);
                            return;
                        }
                    }
                    callback.onSuccess(true);
                } catch (Throwable t) {
                    logger.warn("Failed to process Mesos nodes: ", t);
                    callback.onFailure(t);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                logger.warn("Mesos call failed: ", t);
                callback.onSuccess(false);
            }
        });
    } catch (Exception e) {
        logger.warn("Mesos call failed: ", e);
        callback.onSuccess(false);
    }
}

From source file:ch.icclab.netfloc.impl.NetflocServiceImpl.java

private void commitWriteTransaction(final ReadWriteTransaction wt, final FutureCallback<Void> cb,
        final int totalTries, final int tries) {
    Futures.addCallback(wt.submit(), new FutureCallback<Void>() {
        public void onSuccess(Void result) {
            logger.info("Transaction success after {} tries for {}", totalTries - tries + 1, wt);
            cb.onSuccess(result);//from ww  w  .j  a v  a 2s .  co  m
        }

        public void onFailure(Throwable t) {
            if (t instanceof OptimisticLockFailedException) {
                if ((tries - 1) > 0) {
                    logger.warn("Transaction retry {} for {}", totalTries - tries + 1, wt);
                    commitWriteTransaction(wt, cb, totalTries, tries - 1);
                } else {
                    logger.error("Transaction out of retries: ", wt);
                    cb.onFailure(t);
                }
            } else {
                if (t instanceof DataValidationFailedException) {
                    logger.error("Transaction validation failed {}", t.getMessage());
                } else {
                    logger.error("Transaction failed {}", t.getMessage());
                }
                cb.onFailure(t);
            }
        }
    });
}

From source file:org.thingsboard.server.service.telemetry.DefaultTelemetrySubscriptionService.java

private void addMainCallback(ListenableFuture<List<Void>> saveFuture, final FutureCallback<Void> callback) {
    Futures.addCallback(saveFuture, new FutureCallback<List<Void>>() {
        @Override/*from ww w  . j  a va  2s .  c om*/
        public void onSuccess(@Nullable List<Void> result) {
            callback.onSuccess(null);
        }

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

From source file:org.thingsboard.server.service.telemetry.DefaultTelemetryWebSocketService.java

private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId,
        final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
    return new FutureCallback<ValidationResult>() {
        @Override/*from  w ww .j ava2  s  .co m*/
        public void onSuccess(@Nullable ValidationResult result) {
            Futures.addCallback(attributesService.findAll(tenantId, entityId, scope), callback);
        }

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

From source file:org.thingsboard.server.service.telemetry.DefaultTelemetryWebSocketService.java

private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId,
        final EntityId entityId, final String scope, final List<String> keys,
        final FutureCallback<List<AttributeKvEntry>> callback) {
    return new FutureCallback<ValidationResult>() {
        @Override/*from   w w w  . ja v  a 2  s.  c o m*/
        public void onSuccess(@Nullable ValidationResult result) {
            Futures.addCallback(attributesService.find(tenantId, entityId, scope, keys), callback);
        }

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

From source file:com.vmware.photon.controller.deployer.xenon.util.MiscUtils.java

private static void getVmNetworks(Service service, ApiClient client, String vmId, Integer taskPollDelay,
        FutureCallback<List<String>> callback) throws IOException {
    client.getVmApi().getNetworksAsync(vmId, new FutureCallback<Task>() {
        @Override//  ww w.  j  a va  2s  . co  m
        public void onSuccess(@Nullable Task task) {
            try {
                ApiUtils.pollTaskAsync(task, client, service, taskPollDelay, new FutureCallback<Task>() {
                    @Override
                    public void onSuccess(@Nullable Task task) {
                        try {
                            VmNetworks vmNetworks = VmApi.parseVmNetworksFromTask(task);

                            checkState(vmNetworks.getNetworkConnections() != null);
                            List<String> result = new ArrayList<>();
                            // Get only the non-docker ips. For docker Ips, network is null
                            Set<NetworkConnection> connections = vmNetworks.getNetworkConnections();
                            for (NetworkConnection networkConnection : connections) {
                                if (!Strings.isNullOrEmpty(networkConnection.getNetwork())
                                        && !Strings.isNullOrEmpty(networkConnection.getIpAddress())) {
                                    result.add(networkConnection.getIpAddress());
                                }
                            }
                            ServiceUtils.logInfo(service, "Found " + result.size() + " vm ips");
                            checkState(result.size() > 0);
                            callback.onSuccess(result);
                            return;
                        } catch (Throwable t) {
                            callback.onFailure(t);
                        }
                    }

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

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

From source file:io.github.trulyfree.easyaspi.ssh.ssh.SSHHandler.java

/**
 *
 * @param callback//from w ww.  j a va  2s . c  o  m
 * @param command
 * @param profile
 * @return
 */
public Future<Void> executeCommand(@NonNull final FutureCallback<ChannelWrapper> callback,
        @NonNull final String command, @NonNull final Profile profile) {
    return module.getExecutorService().submit(new Callable<Void>() {
        public Void call() {
            try {
                Session session = profile.getSession(SSHHandler.this);
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();
                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                channel.setCommand(command);
                channel.connect();
                callback.onSuccess(new ChannelWrapper(channel));
                channel.disconnect();
                session.disconnect();
            } catch (Throwable e) {
                e.printStackTrace();
                callback.onFailure(e);
            }
            return null;
        }
    });
}

From source file:io.github.trulyfree.easyaspi.ssh.ssh.SSHHandler.java

/**
 *
 * @param callback//from www  .  j av a  2s  .c  om
 * @param name
 * @return
 * @throws IOException
 */
public Future<String> getPublicKey(final @Nullable FutureCallback<String> callback, final @NonNull String name)
        throws IOException {
    return module.getActivity().getExecutorService().submit(new Callable<String>() {
        @Override
        public String call() {
            String pubkey;
            try {
                KeyPair keyPair = KeyPair.load(jsch, getKeyFile(name).getAbsolutePath());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                keyPair.writePublicKey(baos, null);
                pubkey = baos.toString("UTF-8");
                if (callback != null) {
                    callback.onSuccess(pubkey);
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                pubkey = null;
                if (callback != null) {
                    callback.onFailure(throwable);
                }
            }
            return pubkey;
        }
    });
}

From source file:org.jenkinsci.plugins.workflow.cps.BodyInvoker.java

/**
 * Evaluates the body./* w w w .j  av  a2s  . c o m*/
 *
 * If the body is a synchronous closure, this method evaluates the closure synchronously.
 * Otherwise, the body is asynchronous and the method schedules another thread to evaluate the body.
 *
 * In either case, the result of the evaluation is passed to {@link #bodyCallback}.
 *
 * @param currentThread
 *      The thread whose context the new thread will inherit.
 * @param callback
 *      If non-null, this gets called back in addition to {@link #bodyCallback}
 */
/*package*/ void start(CpsThread currentThread, FlowHead head, @Nullable FutureCallback callback) {
    FutureCallback c = bodyCallback;

    if (callback != null)
        c = new TeeFutureCallback(callback, c);

    StepStartNode sn = addBodyStartFlowNode(head);

    try {
        // TODO: handle arguments to closure
        Object x = body.getBody(currentThread).call();

        c.onSuccess(x); // body has completed synchronously
    } catch (CpsCallableInvocation e) {
        // execute this closure asynchronously
        // TODO: does it make sense that the new thread shares the same head?
        // this problem is captured as https://trello.com/c/v6Pbwqxj/70-allowing-steps-to-build-flownodes
        CpsThread t = currentThread.group.addThread(createContinuable(e, c, sn), head,
                ContextVariableSet.from(currentThread.getContextVariables(), contextOverrides));
        t.resume(new Outcome(null, null)); // get the new thread going
    } catch (Throwable t) {
        // body has completed synchronously and abnormally
        c.onFailure(t);
    }
}