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:org.solovyev.tasks.ListenersAwareFutureTask.java

private ListenersAwareFutureTask(@Nonnull ListenableFutureTask<T> futureTask) {
    this.futureTask = futureTask;
    Futures.addCallback(futureTask, new FutureCallback<T>() {
        @Override//w w w .  j a  va  2s.co m
        public void onSuccess(T result) {
            synchronized (listeners) {
                executed = true;
            }

            for (FutureCallback<T> listener : getListenersCopy()) {
                listener.onSuccess(result);
            }

            synchronized (listeners) {
                listeners.clear();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            synchronized (listeners) {
                executed = true;
            }

            for (FutureCallback<T> listener : getListenersCopy()) {
                listener.onFailure(t);
            }

            synchronized (listeners) {
                listeners.clear();
            }
        }
    });
}

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

@Override
public void checkNodeStatus(final String nodeAddress, final FutureCallback<Boolean> callback) {
    logger.info("Checking Marathon: {}", nodeAddress);

    try {// w  w w .j  av  a  2s .  c  o m
        String connectionString = createConnectionString(nodeAddress);
        mesosClient.checkMarathon(connectionString, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(@Nullable Boolean isReady) {
                try {
                    callback.onSuccess(isReady);
                } catch (Throwable t) {
                    logger.warn("Marathon call failed: ", t);
                    callback.onFailure(t);
                }
            }

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

From source file:blue.lapis.common.economy.Transaction.java

/**
 * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands
 * this Transaction to the EconomyAccount for final processing. This final processing may complete
 * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the
 * transaction.//from  w  w w .j av  a  2s  . com
 *
 * @param onResult A callback for when the transaction is complete
 */
public void commit(FutureCallback<Transaction> onResult) {
    validateState(Status.INCOMPLETE);
    status = Status.IN_TRANSIT;
    TransactionEvent event = new TransactionEventImpl(this);
    LapisCommonsPlugin.getGame().getEventManager().post(event);

    if (event.isCancelled()) {
        status = Status.CANCELLED;
        onResult.onFailure(new TransactionException("Transaction cancelled.", this));
        return;
    }
    status = Status.PROCESSING;

    this.callback = onResult;
    account.apply(this);
}

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

@Override
public void checkNodeStatus(final String nodeAddress, final FutureCallback<Boolean> callback) {
    logger.info("Checking Harbor: {}", nodeAddress);

    try {//from w  w w .  j a  v a2  s.  c  o  m
        String connectionString = createConnectionString(nodeAddress);
        harborClient.checkStatus(connectionString, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(@Nullable Boolean isReady) {
                try {
                    callback.onSuccess(isReady);
                } catch (Throwable t) {
                    logger.warn("Harbor node status check failed: ", t);
                    callback.onFailure(t);
                }
            }

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

From source file:org.eclipse.buildship.core.projectimport.ProjectPreviewJob.java

public ProjectPreviewJob(ProjectImportConfiguration configuration, List<ProgressListener> listeners,
        AsyncHandler initializer,
        final FutureCallback<Pair<OmniBuildEnvironment, OmniGradleBuild>> resultHandler) {
    super("Loading Gradle project preview");

    this.fixedAttributes = configuration.toFixedAttributes();
    this.initializer = Preconditions.checkNotNull(initializer);
    this.result = null;

    addJobChangeListener(new JobChangeAdapter() {

        @Override/* www .  j  a va  2 s. c  o m*/
        public void done(IJobChangeEvent event) {
            if (event.getResult().isOK()) {
                resultHandler.onSuccess(ProjectPreviewJob.this.result);
            } else {
                resultHandler.onFailure(event.getResult().getException());
            }
        }
    });
}

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

/**
 * This method calls into the Harbor API endpoint and determine its status
 * based on http status.//ww w . ja  v a 2s .  c  o m
 *
 * @param connectionString          connectionString of the Harbor Node
 * @param callback                  callback that is invoked on completion of the operation.
 * @throws IOException
 */
public void checkStatus(final String connectionString, final FutureCallback<Boolean> callback)
        throws IOException {

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

    org.apache.http.concurrent.FutureCallback<HttpResponse> futureCallback = new org.apache.http.concurrent.FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {
            callback.onSuccess(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
        }

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

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

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

From source file:io.soliton.protobuf.EnvelopeServerHandler.java

/**
 * Performs a single method invocation./*from ww  w . j  a v  a 2s.co  m*/
 *
 * @param method the method to invoke
 * @param payload the serialized parameter received from the client
 * @param requestId the unique identifier of the request
 * @param channel the channel to use for responding to the client
 * @param <I> the type of the method's parameter
 * @param <O> the return type of the method
 */
private <I extends Message, O extends Message> void invoke(ServerMethod<I, O> method, ByteString payload,
        long requestId, Channel channel) {
    FutureCallback<O> callback = new ServerMethodCallback<>(method, requestId, channel);
    try {
        I request = method.inputParser().parseFrom(payload);
        ListenableFuture<O> result = method.invoke(request);
        pendingRequests.put(requestId, result);
        Futures.addCallback(result, callback, responseCallbackExecutor);
    } catch (InvalidProtocolBufferException ipbe) {
        callback.onFailure(ipbe);
    }
}

From source file:com.vmware.photon.controller.clustermanager.rolloutplans.SlavesNodeRollout.java

private void provisionNode(final Service service, final NodeRolloutInput input, final int nodeIndex,
        final FutureCallback<String> responseFutureCallback) {

    FutureCallback<VmProvisionTaskService.State> callback = new FutureCallback<VmProvisionTaskService.State>() {
        @Override/*from ww  w  .j av a 2 s . com*/
        public void onSuccess(@Nullable VmProvisionTaskService.State result) {
            switch (result.taskState.stage) {
            case FINISHED:
                responseFutureCallback.onSuccess(result.vmIpAddress);
                break;
            case CANCELLED:
                responseFutureCallback.onFailure(new IllegalStateException(
                        String.format("VmProvisionTaskService was canceled. %s", result.documentSelfLink)));
                break;
            case FAILED:
                responseFutureCallback.onFailure(new IllegalStateException(
                        String.format("VmProvisionTaskService failed with error %s. %s",
                                result.taskState.failure.message, result.documentSelfLink)));
                break;
            }
        }

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

    NodeTemplate template = NodeTemplateFactory.createInstance(input.nodeType);
    String scriptDirectory = HostUtils.getScriptsDirectory(service);

    Map<String, String> nodeProperties = new HashMap<>(input.nodeProperties);
    nodeProperties.put(NodeTemplateUtils.NODE_INDEX_PROPERTY, Integer.toString(nodeIndex));
    nodeProperties.put(NodeTemplateUtils.HOST_ID_PROPERTY, UUID.randomUUID().toString());

    VmProvisionTaskService.State startState = new VmProvisionTaskService.State();
    startState.diskFlavorName = input.diskFlavorName;
    startState.imageId = input.imageId;
    startState.projectId = input.projectId;
    startState.vmFlavorName = input.vmFlavorName;
    startState.vmNetworkId = input.vmNetworkId;
    startState.vmTags = ClusterUtil.createClusterTags(input.clusterId, input.nodeType);
    startState.vmName = template.getVmName(nodeProperties);
    startState.userData = template.createUserDataTemplate(scriptDirectory, nodeProperties);
    startState.metaData = template.createMetaDataTemplate(scriptDirectory, nodeProperties);

    TaskUtils.startTaskAsync(service, VmProvisionTaskFactoryService.SELF_LINK, startState,
            (state) -> TaskUtils.finalTaskStages.contains(state.taskState.stage),
            VmProvisionTaskService.State.class, ClusterManagerConstants.DEFAULT_TASK_POLL_DELAY, callback);
}

From source file:com.vmware.photon.controller.clustermanager.rolloutplans.WorkersNodeRollout.java

private void provisionNode(final Service service, final NodeRolloutInput input, final int nodeIndex,
        final FutureCallback<String> responseFutureCallback) {

    FutureCallback<VmProvisionTaskService.State> callback = new FutureCallback<VmProvisionTaskService.State>() {
        @Override/*from   ww  w .j  av a 2  s  . c o  m*/
        public void onSuccess(@Nullable VmProvisionTaskService.State result) {
            switch (result.taskState.stage) {
            case FINISHED:
                responseFutureCallback.onSuccess(result.vmIpAddress);
                break;
            case CANCELLED:
                responseFutureCallback.onFailure(new IllegalStateException(
                        String.format("VmProvisionTaskService for clusterID %s was canceled. %s",
                                input.clusterId, result.documentSelfLink)));
                break;
            case FAILED:
                responseFutureCallback.onFailure(new IllegalStateException(
                        String.format("VmProvisionTaskService failed for clusterID %s with error %s. %s",
                                input.clusterId, result.taskState.failure.message, result.documentSelfLink)));
                break;
            }
        }

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

    NodeTemplate template = NodeTemplateFactory.createInstance(input.nodeType);
    String scriptDirectory = HostUtils.getScriptsDirectory(service);

    Map<String, String> nodeProperties = new HashMap<>(input.nodeProperties);
    nodeProperties.put(NodeTemplateUtils.NODE_INDEX_PROPERTY, Integer.toString(nodeIndex));
    nodeProperties.put(NodeTemplateUtils.HOST_ID_PROPERTY, UUID.randomUUID().toString());

    VmProvisionTaskService.State startState = new VmProvisionTaskService.State();
    startState.diskFlavorName = input.diskFlavorName;
    startState.imageId = input.imageId;
    startState.projectId = input.projectId;
    startState.vmFlavorName = input.vmFlavorName;
    startState.vmNetworkId = input.vmNetworkId;
    startState.vmTags = ClusterUtil.createClusterTags(input.clusterId, input.nodeType);
    startState.vmName = template.getVmName(nodeProperties);
    startState.userData = template.createUserDataTemplate(scriptDirectory, nodeProperties);
    startState.metaData = template.createMetaDataTemplate(scriptDirectory, nodeProperties);

    TaskUtils.startTaskAsync(service, VmProvisionTaskFactoryService.SELF_LINK, startState,
            (state) -> TaskUtils.finalTaskStages.contains(state.taskState.stage),
            VmProvisionTaskService.State.class, ClusterManagerConstants.DEFAULT_TASK_POLL_DELAY, callback);
}

From source file:com.vmware.photon.controller.nsxclient.apis.NsxClientApi.java

/**
 * Performs a DELETE HTTP request to NSX.
 *//*w  w  w .  ja v a2  s .c om*/
protected void deleteAsync(final String path, final int expectedResponseStatus,
        final FutureCallback<Void> responseCallback) throws IOException {
    restClient.sendAsync(RestClient.Method.DELETE, path, null,
            new org.apache.http.concurrent.FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse result) {
                    try {
                        restClient.check(result, expectedResponseStatus);
                    } catch (Throwable e) {
                        responseCallback.onFailure(e);
                    }

                    responseCallback.onSuccess(null);
                }

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

                @Override
                public void cancelled() {
                    responseCallback.onFailure(
                            new RuntimeException(String.format("deleteAsync %s was cancelled", path)));
                }
            });
}