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:c5db.replication.ReplicatorInstance.java

@FiberOnly
private List<ListenableFuture<Boolean>> reconcileAppendMessageWithLocalLog(AppendEntries appendMessage) {
    List<ListenableFuture<Boolean>> logOperationFutures = new ArrayList<>();

    // 6. if existing entries conflict with new entries, delete all
    // existing entries starting with first conflicting entry (sec 5.3)

    long nextIndex = log.getLastIndex() + 1;

    List<LogEntry> entriesFromMessage = appendMessage.getEntriesList();
    List<LogEntry> entriesToCommit = new ArrayList<>(entriesFromMessage.size());

    for (LogEntry entry : entriesFromMessage) {
        long entryIndex = entry.getIndex();

        if (entryIndex == nextIndex) {
            entriesToCommit.add(entry);/*from w w  w. ja v a  2  s  .c  o m*/
            nextIndex++;
            continue;
        }

        if (entryIndex > nextIndex) {
            // ok this entry is still beyond the LAST entry, so we have a problem:
            logger.warn(
                    "Received entry later in sequence than expected: expected {} but the next in the message is {}",
                    nextIndex, entryIndex);
            logOperationFutures.add(Futures.immediateFailedFuture(
                    new Exception("Unexpected log entry, or entry sequence gap in received entries")));
            return logOperationFutures;
        }

        // at this point entryIndex should be <= log.getLastIndex
        assert entryIndex < nextIndex;

        if (log.getLogTerm(entryIndex) != entry.getTerm()) {
            // This is generally expected to be fairly uncommon.
            // conflict:
            logger.debug(
                    "log conflict at idx {} my term: {} term from leader: {}, truncating log after this point",
                    entryIndex, log.getLogTerm(entryIndex), entry.getTerm());

            // delete this and all subsequent entries from the local log.
            logOperationFutures.add(log.truncateLog(entryIndex));

            entriesToCommit.add(entry);
            nextIndex = entryIndex + 1;
        }
    }

    // 7. Append any new entries not already in the log.
    logOperationFutures.add(log.logEntries(entriesToCommit));
    refreshQuorumConfigurationFromLog();
    return logOperationFutures;
}

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

@Override
public Future<RpcResult<CreateLogicalRouterOutput>> createLogicalRouter(final CreateLogicalRouterInput input) {

    final RpcResultBuilder<CreateLogicalRouterOutput> resultBuilder = RpcResultBuilder
            .<CreateLogicalRouterOutput>success();
    final CreateLogicalRouterOutputBuilder outputBuilder = new CreateLogicalRouterOutputBuilder();

    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)));
    }//  www  . java  2 s  . 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));

    LrAttributeBuilder lrAttr = new LrAttributeBuilder();
    lrAttr.setName(name);
    lrAttr.setLrUuid(new Uuid(uuid));
    fabricObj.buildLogicalRouter(newNodeId, lrAttr, input);

    LogicalRouterAugmentBuilder lrCtx = new LogicalRouterAugmentBuilder();
    lrCtx.setLrAttribute(lrAttr.build());

    nodeBuilder.addAugmentation(LogicalRouterAugment.class, lrCtx.build());

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

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

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

            outputBuilder.setLrUuid(new Uuid(uuid));
            outputBuilder.setName(input.getName());
            outputBuilder.setNodeId(newNodeId);
            fabricObj.notifyLogicRouterCreated(newNodeId, lr);
            return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build());
        }
    }, executor);

}

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

@Override
public Future<RpcResult<Void>> addLinkToFabric(AddLinkToFabricInput input) {

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

    FabricId fabricId = input.getFabricId();
    LinkRef link = input.getLinkRef();

    final InstanceIdentifier<DeviceLinks> path = Constants.DOM_FABRICS_PATH
            .child(Node.class, new NodeKey(fabricId)).augmentation(FabricNode.class)
            .child(FabricAttribute.class).child(DeviceLinks.class, new DeviceLinksKey(link));

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

    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();

    DeviceLinksBuilder linkBuilder = new DeviceLinksBuilder();
    linkBuilder.setKey(new DeviceLinksKey(link)).setLinkRef(link).build();

    trans.put(LogicalDatastoreType.OPERATIONAL, path, linkBuilder.build(), false);

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

    return Futures.transform(future,
            (AsyncFunction<Void, RpcResult<Void>>) submitResult -> Futures.immediateFuture(result));
}

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

/**
 * Update the organization&#39;s license assignments in a batch.
 * //from w w w .  ja  va2  s. c o  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<ApiResponse<List<LicenseUpdateStatus>>> postLicenseOrganizationAsync(
        ApiRequest<LicenseBatchAssignmentRequest> request,
        final AsyncApiCallback<ApiResponse<List<LicenseUpdateStatus>>> callback) {
    try {
        final SettableFuture<ApiResponse<List<LicenseUpdateStatus>>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<List<LicenseUpdateStatus>>() {
        }, new AsyncApiCallback<ApiResponse<List<LicenseUpdateStatus>>>() {
            @Override
            public void onCompleted(ApiResponse<List<LicenseUpdateStatus>> response) {
                notifySuccess(future, callback, response);
            }

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

From source file:com.restfb.DefaultFacebookClient.java

protected ListenableFuture<String> makeRequestAndProcessResponse(Requestor requestor) {
    ListenableFuture<Response> responseFuture = null;

    // Perform a GET or POST to the API endpoint
    try {/* w w  w.ja va 2s  .  c o m*/
        responseFuture = requestor.makeRequest();
    } catch (Throwable t) {
        return Futures.immediateFailedFuture(new FacebookNetworkException("Facebook request failed", t));
    }

    final SettableFuture<String> resultStringFuture = SettableFuture.create();
    Futures.addCallback(responseFuture, new FutureCallback<Response>() {
        @Override
        public void onSuccess(Response response) {
            // If we get any HTTP response code other than a 200 OK or 400 Bad Request
            // or 401 Not Authorized or 403 Forbidden or 404 Not Found or 500 Internal Server Error,
            // throw an exception.
            if (HTTP_OK != response.getStatusCode() && HTTP_BAD_REQUEST != response.getStatusCode()
                    && HTTP_UNAUTHORIZED != response.getStatusCode()
                    && HTTP_NOT_FOUND != response.getStatusCode()
                    && HTTP_INTERNAL_ERROR != response.getStatusCode()
                    && HTTP_FORBIDDEN != response.getStatusCode())
                throw new FacebookNetworkException("Facebook request failed", response.getStatusCode());

            String json = response.getBody();

            // If the response contained an error code, throw an exception.
            throwFacebookResponseStatusExceptionIfNecessary(json, response.getStatusCode());

            // If there was no response error information and this was a 500 or 401
            // error, something weird happened on Facebook's end. Bail.
            if (HTTP_INTERNAL_ERROR == response.getStatusCode()
                    || HTTP_UNAUTHORIZED == response.getStatusCode())
                throw new FacebookNetworkException("Facebook request failed", response.getStatusCode());

            resultStringFuture.set(json);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof FacebookException) {
                resultStringFuture.setException(t);
            } else {
                resultStringFuture.setException(new FacebookNetworkException("Facebook request failed", t));
            }
        }
    });

    return resultStringFuture;
}

From source file:diskCacheV111.srm.SrmHandler.java

/**
 * Returns a response for a token that cannot be mapped to a backend. The response depends
 * on whether the token has a valid backend id prefix (backend if offline) or not (token is invalid).
 *//*from   w ww.  j  av  a2 s. co  m*/
private ListenableFuture<TRequestSummary> provideRequestSummaryForTokenWithoutBackend(String token) {
    if (!hasPrefix(token)) {
        return Futures.immediateFailedFuture(new SRMInvalidRequestException("No such request token: " + token));
    }
    return Futures.immediateFailedFuture(
            new SRMInvalidRequestException("Backend for request " + token + " is currently unavailable."));
}

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

/**
 * Switch PureCloud license feature toggle value.
 * /*from  w w w  .  jav  a2 s  .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<LicenseOrgToggle> postLicenseToggleAsync(PostLicenseToggleRequest request,
        final AsyncApiCallback<LicenseOrgToggle> callback) {
    try {
        final SettableFuture<LicenseOrgToggle> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<LicenseOrgToggle>() {
        }, new AsyncApiCallback<ApiResponse<LicenseOrgToggle>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseOrgToggle> 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:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<CreateLogicalPortOutput>> createLogicalPort(CreateLogicalPortInput input) {
    final RpcResultBuilder<CreateLogicalPortOutput> resultBuilder = RpcResultBuilder
            .<CreateLogicalPortOutput>success();
    final CreateLogicalPortOutputBuilder outputBuilder = new CreateLogicalPortOutputBuilder();

    final FabricId fabricId = input.getFabricId();
    final String name = input.getName();
    final NodeId nodeId = input.getLogicalDevice();

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }//www .j a  v  a2  s  .c o  m

    final TpId tpid = new TpId(name == null ? UUID.randomUUID().toString() : name);

    TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
    tpBuilder.setTpId(tpid);
    tpBuilder.setKey(new TerminationPointKey(tpid));

    LportAttributeBuilder lpAttr = new LportAttributeBuilder();
    lpAttr.setName(input.getName());
    Attribute portAttr = input.getAttribute();
    if (portAttr != null) {
        lpAttr.setPortLayer(portAttr.getPortLayer());
        lpAttr.setFabricAcl(portAttr.getFabricAcl());
        lpAttr.setPortFunction(portAttr.getPortFunction());
    }

    fabricObj.buildLogicalPort(tpid, lpAttr, input);

    LogicalPortAugmentBuilder lpCtx = new LogicalPortAugmentBuilder();
    lpCtx.setLportAttribute(lpAttr.build());

    tpBuilder.addAugmentation(LogicalPortAugment.class, lpCtx.build());

    InstanceIdentifier<TerminationPoint> tpIId = MdSalUtils.createLogicPortIId(fabricId, nodeId, tpid);
    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    trans.put(LogicalDatastoreType.OPERATIONAL, tpIId, tpBuilder.build());

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

        @Override
        public ListenableFuture<RpcResult<CreateLogicalPortOutput>> apply(Void submitResult) throws Exception {
            outputBuilder.setTpId(tpid);
            outputBuilder.setName(name);
            return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build());
        }
    }, executor);

}

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

/**
 * Switch PureCloud license feature toggle value.
 * /*from   w w w . java 2  s .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<LicenseOrgToggle>> postLicenseToggleAsync(ApiRequest<Void> request,
        final AsyncApiCallback<ApiResponse<LicenseOrgToggle>> callback) {
    try {
        final SettableFuture<ApiResponse<LicenseOrgToggle>> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request, new TypeReference<LicenseOrgToggle>() {
        }, new AsyncApiCallback<ApiResponse<LicenseOrgToggle>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseOrgToggle> response) {
                notifySuccess(future, callback, response);
            }

            @Override
            public void onFailed(Throwable exception) {
                if (exception instanceof ApiException) {
                    @SuppressWarnings("unchecked")
                    ApiResponse<LicenseOrgToggle> response = (ApiResponse<LicenseOrgToggle>) (ApiResponse<?>) exception;
                    notifySuccess(future, callback, response);
                }
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    @SuppressWarnings("unchecked")
                    ApiResponse<LicenseOrgToggle> response = (ApiResponse<LicenseOrgToggle>) (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.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<Void>> addAcl(AddAclInput input) {
    String aclName = input.getAclName();
    FabricId fabricId = input.getFabricId();
    NodeId ldev = input.getLogicalDevice();
    TpId tpId = input.getLogicalPort();/*from   ww w.j  a  va2 s. c o  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<FabricAcl> aclIId = fabricObj.addAcl(ldev, tpId, aclName);

    if (aclIId == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException("Can not add acl, maybe the target is not exists !"));
    }

    FabricAclBuilder aclBuilder = new FabricAclBuilder();
    aclBuilder.setFabricAclName(aclName);
    aclBuilder.setKey(new FabricAclKey(aclName));

    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    trans.merge(LogicalDatastoreType.OPERATIONAL, aclIId, aclBuilder.build(), false);

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

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyAclUpdated(aclIId, false);
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
    }, executor);
}