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

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

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V, X extends Exception> CheckedFuture<V, X> immediateFailedCheckedFuture(X exception) 

Source Link

Document

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

Usage

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.ShardedDOMDataWriteTransaction.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    Preconditions.checkState(!closed, "Transaction %s is already closed", identifier);

    final Set<DOMStoreWriteTransaction> txns = ImmutableSet.copyOf(idToTransaction.values());
    final List<DOMStoreThreePhaseCommitCohort> cohorts = new ArrayList<>(txns.size());
    for (DOMStoreWriteTransaction tx : txns) {
        cohorts.add(tx.ready());//from   w ww.  j  av  a2s. c o m
    }

    try {
        return Futures.immediateCheckedFuture(new CommitCoordinationTask(this, cohorts, null).call());
    } catch (TransactionCommitFailedException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }
}

From source file:org.opendaylight.controller.cluster.databroker.actors.dds.RemoteProxyTransaction.java

private <T> CheckedFuture<T, ReadFailedException> sendReadRequest(
        final AbstractReadTransactionRequest<?> request, final Consumer<Response<?, ?>> completer,
        final ListenableFuture<T> future) {
    // Check if a previous operation failed. If it has, do not bother sending anything and report a failure
    final Exception local = operationFailure;
    if (local != null) {
        return Futures
                .immediateFailedCheckedFuture(new ReadFailedException("Previous operation failed", local));
    }/*w  w  w .  j a  v a2  s. c om*/

    // Make sure we send any modifications before issuing a read
    ensureFlushedBuider();
    client().sendRequest(nextSequence(), request, completer);
    return MappingCheckedFuture.create(future, ReadFailedException.MAPPER);
}

From source file:org.opendaylight.yangtools.yang.model.repo.util.AbstractSchemaRepository.java

@Override
public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(
        @Nonnull final SourceIdentifier id, @Nonnull final Class<T> representation) {
    final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;

    synchronized (this) {
        final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs = sources
                .get(id);//from w ww  .j a  v a  2 s.co m
        if (srcs == null) {
            return Futures.immediateFailedCheckedFuture(
                    new MissingSchemaSourceException("No providers registered for source" + id, id));
        }

        sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
    }

    // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
    Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);

    final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
    if (!regs.hasNext()) {
        return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
                "No providers for source " + id + " representation " + representation + " available", id));
    }

    CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
    // Add callback to notify cache listeners about encountered schema
    Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
        @Override
        public void onSuccess(final T result) {
            for (final SchemaListenerRegistration listener : listeners) {
                listener.getInstance().schemaSourceEncountered(result);
            }
        }

        @Override
        public void onFailure(@Nonnull final Throwable t) {
            LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
        }
    });

    return fetchSourceFuture;
}

From source file:org.opendaylight.controller.blueprint.ext.ActionProviderBean.java

private void registerFallback(final Class<RpcService> interfaceClass) {
    final Collection<SchemaPath> paths = RpcUtil.decomposeRpcService(interfaceClass,
            schemaService.getGlobalContext(), RpcRoutingStrategy::isContextBasedRouted);
    if (paths.isEmpty()) {
        LOG.warn("{}: interface {} has no actions defined", ACTION_PROVIDER, interfaceClass);
        return;//ww w.  ja  v a2s.  com
    }

    final Set<DOMRpcIdentifier> rpcs = ImmutableSet
            .copyOf(Collections2.transform(paths, DOMRpcIdentifier::create));
    reg = rpcProviderService.registerRpcImplementation((rpc, input) -> {
        return Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException(
                "Action %s has no instance matching %s", rpc, input));
    }, rpcs);
    LOG.debug("Registered provider for {}", interfaceName);
}

From source file:org.opendaylight.sfc.provider.validators.ServiceFunctionPathCohort.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*w  w  w . j av a  2s  . c om*/
public CheckedFuture<PostCanCommitStep, DataValidationFailedException> canCommit(Object txId,
        DOMDataTreeCandidate candidate, SchemaContext ctx) {

    LOG.debug("canCommit:called! txId={}, candidate={}, context={} ", txId, candidate, ctx);

    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    NormalizedNode nn = candidateRoot.getDataAfter().orNull();
    if (nn == null) {
        LOG.debug("canCommit:no sfp after the change");
        return ValidationConstants.SUCCESS_CAN_COMMIT_FUTURE;
    }

    LOG.debug("canCommit:updating codec contexts");
    moduleContext.addModuleInfos(infos);
    bindingContext = BindingRuntimeContext.create(moduleContext, ctx);
    codecRegistry.onBindingRuntimeContextUpdated(bindingContext);

    LOG.debug("canCommit:Mapping service ready");

    LOG.debug("canCommit:before deserializing:  {}", nn);
    // (nn is an immutableMapNode). Contains an unmodifiable collection
    // reference of all this thing
    // https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL:Design:Normalized_DOM_Model
    Collection collection = (Collection<MapEntryNode>) nn.getValue();
    LOG.debug("canCommit:collection containing the sfs:  {}", collection);
    Iterator<MapEntryNode> menIter = collection.iterator();
    while (menIter.hasNext()) {
        MapEntryNode meNode = menIter.next();
        LOG.debug("canCommit:sfp to process: {}", meNode);
        NormalizedNode sfpAsNormalizedNode = meNode;
        LOG.debug("canCommit:the first SF (as nn):  {}", sfpAsNormalizedNode);
        DataObject dobj = codecRegistry
                .fromNormalizedNode(ValidationConstants.SFP_PATH_YII, sfpAsNormalizedNode).getValue();
        LOG.debug("canCommit:registerValidationCohorts:the first SFP (as dataobject):  {}", dobj);
        ServiceFunctionPath sfp = (ServiceFunctionPath) dobj;
        LOG.debug("canCommit:registerValidationCohorts:the implemented interface: {}",
                dobj.getImplementedInterface());
        LOG.debug("canCommit:the first SF (as binding representation):  {}", sfp);
        try {
            if (!sfpv.validateServiceFunctionPath(sfp)) {
                return ValidationConstants.FAILED_CAN_COMMIT_SFP_FUTURE;
            }
        } catch (DataValidationFailedException dvfe) {
            return Futures.immediateFailedCheckedFuture(dvfe);
        }
    }
    return ValidationConstants.SUCCESS_CAN_COMMIT_FUTURE;
}

From source file:org.apache.s4.comm.staging.BlockingThreadPoolExecutorService.java

@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
    try {//w ww .  ja v  a 2  s  .  co  m
        queueingPermits.acquire();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return Futures.immediateFailedCheckedFuture(e);
    }
    ListenableFuture<T> future = super.submit(new CallableWithPermitRelease<T>(task));
    return future;
}

From source file:com.blackducksoftware.bdio.io.BdioReader.java

/**
 * Returns an observable from a character source.
 *//*www . j ava 2 s . c  om*/
public static Observable<Node> open(final LinkedDataContext context, final CharSource source) {
    checkNotNull(context);
    checkNotNull(source);
    // Use CheckedFuture as a wrapper for either a BdioReader or an IOException
    return Observable.create(new SyncOnSubscribe<CheckedFuture<BdioReader, IOException>, Node>() {
        @Override
        protected CheckedFuture<BdioReader, IOException> generateState() {
            try {
                return Futures.immediateCheckedFuture(new BdioReader(context, source.openBufferedStream()));
            } catch (IOException e) {
                return Futures.immediateFailedCheckedFuture(e);
            }
        }

        @Override
        protected CheckedFuture<BdioReader, IOException> next(CheckedFuture<BdioReader, IOException> s,
                Observer<? super Node> t) {
            // Iterate over the nodes in the file as we see them
            try {
                Node node = s.checkedGet().read();
                if (node != null) {
                    t.onNext(node);
                } else {
                    t.onCompleted();
                }
            } catch (IOException e) {
                t.onError(e);
            }
            return s;
        }

        @Override
        protected void onUnsubscribe(CheckedFuture<BdioReader, IOException> s) {
            try {
                s.checkedGet().close();
            } catch (IOException e) {
                return;
            }
        }
    });
}

From source file:org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache.java

@Override
public synchronized CheckedFuture<? extends T, SchemaSourceException> getSource(
        final SourceIdentifier sourceIdentifier) {
    final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
    if (file.exists() && file.canRead()) {
        LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
        final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation)
                .restore(sourceIdentifier, file);
        return Futures.immediateCheckedFuture(representation.cast(restored));
    }//from  w ww  .j av a  2s.  c  om

    LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
    return Futures.immediateFailedCheckedFuture(
            new MissingSchemaSourceException("Source not found", sourceIdentifier));
}

From source file:org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl.java

private CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> fillFromDatastore(
        final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<FlowCapableNode> path) {
    // Create new read-only transaction
    final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();

    // Bail out early if transaction is null
    if (transaction == null) {
        return Futures.immediateFailedCheckedFuture(new ReadFailedException("Read transaction is null"));
    }/*from   w w  w.j a  v a2  s. c o  m*/

    // Prepare read operation from datastore for path
    final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> future = transaction
            .read(logicalDatastoreType, path);

    // Bail out early if future is null
    if (future == null) {
        return Futures
                .immediateFailedCheckedFuture(new ReadFailedException("Future from read transaction is null"));
    }

    Futures.addCallback(future, new FutureCallback<Optional<FlowCapableNode>>() {
        @Override
        public void onSuccess(Optional<FlowCapableNode> result) {
            result.asSet().stream().filter(Objects::nonNull)
                    .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
                    .flatMap(flowCapableNode -> flowCapableNode.getTable().stream()).filter(Objects::nonNull)
                    .filter(table -> Objects.nonNull(table.getFlow()))
                    .flatMap(table -> table.getFlow().stream()).filter(Objects::nonNull)
                    .filter(flow -> Objects.nonNull(flow.getId())).forEach(flowConsumer);

            // After we are done with reading from datastore, close the transaction
            transaction.close();
        }

        @Override
        public void onFailure(Throwable t) {
            // Even when read operation failed, close the transaction
            transaction.close();
        }
    });

    return future;
}

From source file:org.apache.s4.comm.staging.BlockingThreadPoolExecutorService.java

@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
    try {/*  w w  w  .  jav  a2  s .  c  o m*/
        queueingPermits.acquire();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return Futures.immediateFailedCheckedFuture(e);
    }
    ListenableFuture<T> future = super.submit(new RunnableWithPermitRelease(task), result);
    return future;
}