Example usage for com.google.common.util.concurrent Futures immediateFailedFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) 

Source Link

Document

Returns a ListenableFuture which has an exception set immediately upon construction.

Usage

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get licenses for specified user./*  w  w  w . j  a  va2s.c om*/
 * 
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<ApiResponse<LicenseUser>> getLicenseUserAsync(ApiRequest<Void> request,
        final AsyncApiCallback<ApiResponse<LicenseUser>> callback) {
    try {
        final SettableFuture<ApiResponse<LicenseUser>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<LicenseUser>() {
        }, new AsyncApiCallback<ApiResponse<LicenseUser>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseUser> response) {
                notifySuccess(future, callback, response);
            }

            @Override
            public void onFailed(Throwable exception) {
                if (exception instanceof ApiException) {
                    @SuppressWarnings("unchecked")
                    ApiResponse<LicenseUser> response = (ApiResponse<LicenseUser>) (ApiResponse<?>) exception;
                    notifySuccess(future, callback, response);
                }
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    @SuppressWarnings("unchecked")
                    ApiResponse<LicenseUser> response = (ApiResponse<LicenseUser>) (ApiResponse<?>) (new ApiException(
                            exception));
                    notifySuccess(future, callback, response);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:org.opendaylight.faas.fabric.general.FabricManagementAPIProvider.java

@Override
public Future<RpcResult<Void>> rmNodeFromFabric(RmNodeFromFabricInput input) {
    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    FabricId fabricId = input.getFabricId();
    final NodeRef device = input.getNodeRef();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }/*from  w w w. ja  v  a2 s .c  o  m*/

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    // del fabric attribute
    InstanceIdentifier<DeviceNodes> devicepath = Constants.DOM_FABRICS_PATH
            .child(Node.class, new NodeKey(fabricId)).augmentation(FabricNode.class)
            .child(FabricAttribute.class).child(DeviceNodes.class, new DeviceNodesKey(device));

    trans.delete(LogicalDatastoreType.OPERATIONAL, devicepath);

    // del node attribute
    @SuppressWarnings("unchecked")
    InstanceIdentifier<Node> noderef = (InstanceIdentifier<Node>) device.getValue();
    NodeId deviceid = noderef.firstKeyOf(Node.class).getNodeId();
    TopologyId topoid = noderef.firstKeyOf(Topology.class).getTopologyId();
    InstanceIdentifier<SupportingNode> suplNodeIid = MdSalUtils.createFNodeIId(input.getFabricId())
            .child(SupportingNode.class, new SupportingNodeKey(deviceid, topoid));

    trans.delete(LogicalDatastoreType.OPERATIONAL, suplNodeIid);

    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @SuppressWarnings("unchecked")
        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyDeviceRemoved((InstanceIdentifier<Node>) device.getValue());
            return Futures.immediateFuture(result);
        }
    });
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get a page of users and their licenses
 * Retrieve a page of users in an organization along with the licenses they possess.
 * @param request the request object//from   w  w w. j  a  v  a 2 s.  c  om
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<UserLicensesEntityListing> getLicenseUsersAsync(GetLicenseUsersRequest request,
        final AsyncApiCallback<UserLicensesEntityListing> callback) {
    try {
        final SettableFuture<UserLicensesEntityListing> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<UserLicensesEntityListing>() {
        }, new AsyncApiCallback<ApiResponse<UserLicensesEntityListing>>() {
            @Override
            public void onCompleted(ApiResponse<UserLicensesEntityListing> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:com.android.tools.idea.avdmanager.AvdManagerConnection.java

/**
 * Handle the {@link AccelerationErrorCode} found when attempting to start an AVD.
 * @param project/*from w w w .j a  va2 s .  co  m*/
 * @param error
 * @return a future with a device that was launched delayed, or null if startAvd should proceed to start the AVD.
 */
@Nullable
private ListenableFuture<IDevice> handleAccelerationError(@Nullable final Project project,
        @NotNull final AvdInfo info, @NotNull AccelerationErrorCode error) {
    switch (error) {
    case ALREADY_INSTALLED:
        return null;
    case TOOLS_UPDATE_REQUIRED:
    case PLATFORM_TOOLS_UPDATE_ADVISED:
    case SYSTEM_IMAGE_UPDATE_ADVISED:
        // Do not block emulator from running if we need updates (run with degradated performance):
        return null;
    case NO_EMULATOR_INSTALLED:
        // report this error below
        break;
    default:
        Abi abi = Abi.getEnum(info.getAbiType());
        boolean isAvdIntel = abi == Abi.X86 || abi == Abi.X86_64;
        if (!isAvdIntel) {
            // Do not block Arm and Mips emulators from running without an accelerator:
            return null;
        }
        // report all other errors
        break;
    }
    String accelerator = SystemInfo.isLinux ? "KVM" : "Intel HAXM";
    int result = Messages.showOkCancelDialog(project,
            String.format("%1$s is required to run this AVD.\n%2$s\n\n%3$s\n", accelerator, error.getProblem(),
                    error.getSolutionMessage()),
            error.getSolution().getDescription(), AllIcons.General.WarningDialog);
    if (result != Messages.OK || error.getSolution() == AccelerationErrorSolution.SolutionCode.NONE) {
        return Futures.immediateFailedFuture(new RuntimeException("Could not start AVD"));
    }
    final SettableFuture<ListenableFuture<IDevice>> future = SettableFuture.create();
    Runnable retry = () -> future.set(startAvd(project, info));
    Runnable cancel = () -> future.setException(new RuntimeException("Retry after fixing problem by hand"));
    Runnable action = AccelerationErrorSolution.getActionForFix(error, project, retry, cancel);
    ApplicationManager.getApplication().invokeLater(action);
    return Futures.dereference(future);
}

From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<CreateLogicalSwitchOutput>> createLogicalSwitch(final CreateLogicalSwitchInput input) {
    final RpcResultBuilder<CreateLogicalSwitchOutput> resultBuilder = RpcResultBuilder
            .<CreateLogicalSwitchOutput>success();
    final CreateLogicalSwitchOutputBuilder outputBuilder = new CreateLogicalSwitchOutputBuilder();

    FabricId fabricId = input.getFabricId();
    String name = input.getName();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }/*from   www . j ava  2s.  co  m*/

    final String uuid = UUID.randomUUID().toString();
    final NodeId newNodeId = new NodeId(name == null ? uuid : name);
    final InstanceIdentifier<Node> newRouterIId = MdSalUtils.createNodeIId(fabricId.getValue(), newNodeId);

    NodeBuilder nodeBuilder = new NodeBuilder();
    nodeBuilder.setKey(new NodeKey(newNodeId));
    nodeBuilder.setNodeId(newNodeId);

    nodeBuilder.setSupportingNode(createDefaultSuplNode(fabricId));

    LswAttributeBuilder lswAttr = new LswAttributeBuilder();
    lswAttr.setName(input.getName());
    lswAttr.setLswUuid(new Uuid(uuid));
    fabricObj.buildLogicalSwitch(newNodeId, lswAttr, input);

    LogicalSwitchAugmentBuilder lswCtx = new LogicalSwitchAugmentBuilder();
    lswCtx.setLswAttribute(lswAttr.build());

    nodeBuilder.addAugmentation(LogicalSwitchAugment.class, lswCtx.build());

    final Node lsw = nodeBuilder.build();
    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    trans.put(LogicalDatastoreType.OPERATIONAL, newRouterIId, lsw);

    return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<CreateLogicalSwitchOutput>>() {

        @Override
        public ListenableFuture<RpcResult<CreateLogicalSwitchOutput>> apply(Void submitResult)
                throws Exception {

            outputBuilder.setLswUuid(new Uuid(uuid));
            outputBuilder.setName(input.getName());
            outputBuilder.setNodeId(newNodeId);
            fabricObj.notifyLogicSwitchCreated(newNodeId, lsw);
            return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build());
        }
    }, executor);
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get a page of users and their licenses
 * Retrieve a page of users in an organization along with the licenses they possess.
 * @param request the request object/*from w w  w  .j  a va 2  s . com*/
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<ApiResponse<UserLicensesEntityListing>> getLicenseUsersAsync(ApiRequest<Void> request,
        final AsyncApiCallback<ApiResponse<UserLicensesEntityListing>> callback) {
    try {
        final SettableFuture<ApiResponse<UserLicensesEntityListing>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<UserLicensesEntityListing>() {
        }, new AsyncApiCallback<ApiResponse<UserLicensesEntityListing>>() {
            @Override
            public void onCompleted(ApiResponse<UserLicensesEntityListing> response) {
                notifySuccess(future, callback, response);
            }

            @Override
            public void onFailed(Throwable exception) {
                if (exception instanceof ApiException) {
                    @SuppressWarnings("unchecked")
                    ApiResponse<UserLicensesEntityListing> response = (ApiResponse<UserLicensesEntityListing>) (ApiResponse<?>) exception;
                    notifySuccess(future, callback, response);
                }
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    @SuppressWarnings("unchecked")
                    ApiResponse<UserLicensesEntityListing> response = (ApiResponse<UserLicensesEntityListing>) (ApiResponse<?>) (new ApiException(
                            exception));
                    notifySuccess(future, callback, response);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:org.opendaylight.faas.fabric.general.FabricManagementAPIProvider.java

@Override
public Future<RpcResult<Void>> addNodeToFabric(AddNodeToFabricInput input) {

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    final FabricId fabricId = input.getFabricId();
    final NodeRef device = input.getNodeRef();
    final DeviceRole role = input.getRole();

    final InstanceIdentifier<DeviceNodes> path = Constants.DOM_FABRICS_PATH
            .child(Node.class, new NodeKey(fabricId)).augmentation(FabricNode.class)
            .child(FabricAttribute.class).child(DeviceNodes.class, new DeviceNodesKey(device));

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }//from  ww w  .  java 2 s  .c  o  m

    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    // set fabric attribute
    DeviceNodesBuilder dnodeBuilder = new DeviceNodesBuilder();
    dnodeBuilder.setKey(new DeviceNodesKey(device)).setDeviceRef(device).build();
    fabricObj.addNodeToFabric(dnodeBuilder, input);
    trans.put(LogicalDatastoreType.OPERATIONAL, path, dnodeBuilder.build(), true);

    // set node attribute
    @SuppressWarnings("unchecked")
    InstanceIdentifier<Node> noderef = (InstanceIdentifier<Node>) device.getValue();
    NodeId deviceid = noderef.firstKeyOf(Node.class).getNodeId();
    TopologyId topoid = noderef.firstKeyOf(Topology.class).getTopologyId();
    final InstanceIdentifier<SupportingNode> suplNodeIid = MdSalUtils.createFNodeIId(input.getFabricId())
            .child(SupportingNode.class, new SupportingNodeKey(deviceid, topoid));
    SupportingNodeBuilder suplNodeBuilder = new SupportingNodeBuilder();
    suplNodeBuilder.setNodeRef(deviceid);
    suplNodeBuilder.setTopologyRef(topoid);
    suplNodeBuilder.setKey(new SupportingNodeKey(deviceid, topoid));
    trans.put(LogicalDatastoreType.OPERATIONAL, suplNodeIid, suplNodeBuilder.build(), true);

    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @SuppressWarnings("unchecked")
        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyDeviceAdded((InstanceIdentifier<Node>) device.getValue(), role);
            return Futures.immediateFuture(result);
        }
    });
}

From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<Void>> rmLogicalRouter(RmLogicalRouterInput input) {
    FabricId fabricId = input.getFabricId();
    NodeId nodeid = input.getNodeId();/*from  w w  w  . j a v a 2  s  .co  m*/

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }

    final InstanceIdentifier<Node> routerIId = MdSalUtils.createNodeIId(fabricId.getValue(), nodeid);

    ReadOnlyTransaction trans = dataBroker.newReadOnlyTransaction();

    CheckedFuture<Optional<Node>, ReadFailedException> readFuture = trans.read(LogicalDatastoreType.OPERATIONAL,
            routerIId);

    return Futures.transform(readFuture, new AsyncFunction<Optional<Node>, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Optional<Node> optional) throws Exception {

            if (optional.isPresent()) {
                Node lr = optional.get();
                fabricObj.notifyLogicRouterRemoved(lr);

                WriteTransaction wt = dataBroker.newWriteOnlyTransaction();
                wt.delete(LogicalDatastoreType.OPERATIONAL, routerIId);
                MdSalUtils.wrapperSubmit(wt, executor);
            }

            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
    }, executor);
}

From source file:org.apache.qpid.server.exchange.AbstractExchange.java

@SuppressWarnings("unused")
@StateTransition(currentState = State.ACTIVE, desiredState = State.DELETED)
private ListenableFuture<Void> doDelete() {
    try {/*w  ww. j a  va  2 s.  c om*/
        deleteWithChecks();
        preSetAlternateExchange();
        setState(State.DELETED);
        return Futures.immediateFuture(null);
    } catch (ExchangeIsAlternateException | RequiredExchangeException e) {
        // let management know about constraint violations
        // in order to report error back to caller
        return Futures.immediateFailedFuture(e);
    }
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Update the organization&#39;s license assignments in a batch.
 * //  w  w w .  ja v  a2 s .co m
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<List<LicenseUpdateStatus>> postLicenseOrganizationAsync(PostLicenseOrganizationRequest request,
        final AsyncApiCallback<List<LicenseUpdateStatus>> callback) {
    try {
        final SettableFuture<List<LicenseUpdateStatus>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<List<LicenseUpdateStatus>>() {
        }, new AsyncApiCallback<ApiResponse<List<LicenseUpdateStatus>>>() {
            @Override
            public void onCompleted(ApiResponse<List<LicenseUpdateStatus>> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}