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

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

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V, X extends Exception> CheckedFuture<V, X> immediateCheckedFuture(@Nullable V value) 

Source Link

Document

Returns a CheckedFuture which has its value 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 w w  .ja v a2  s.  co 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.ConcurrentDOMDataBroker.java

@Override
protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
        Collection<DOMStoreThreePhaseCommitCohort> cohorts) {

    Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
    Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
    LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());

    if (cohorts.isEmpty()) {
        return Futures.immediateCheckedFuture(null);
    }//from   www.  ja  v a2  s.c o  m

    final AsyncNotifyingSettableFuture clientSubmitFuture = new AsyncNotifyingSettableFuture(
            clientFutureCallbackExecutor);

    doCanCommit(clientSubmitFuture, transaction, cohorts);

    return MappingCheckedFuture.create(clientSubmitFuture,
            TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
}

From source file:org.opendaylight.controller.clustering.it.provider.impl.SingletonGetConstantService.java

@Nonnull
@Override//from www.  j  a  v a 2 s .  c o  m
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull DOMRpcIdentifier rpc,
        @Nullable NormalizedNode<?, ?> input) {
    LOG.debug("get-singleton-constant invoked, current value: {}", constant);

    final LeafNode<Object> value = ImmutableLeafNodeBuilder.create()
            .withNodeIdentifier(new NodeIdentifier(CONSTANT)).withValue(constant).build();

    final ContainerNode result = ImmutableContainerNodeBuilder.create()
            .withNodeIdentifier(new NodeIdentifier(OUTPUT)).withChild(value).build();

    return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(result));
}

From source file:org.opendaylight.netconf.topology.singleton.impl.NetconfTopologyContext.java

@Override
public ListenableFuture<Void> closeServiceInstance() {

    if (!finalClose) {
        // in case that master changes role to slave, new NodeDeviceManager must be created and listener registered
        netconfNodeManager = createNodeDeviceManager();
    }/*from  w  w w  .j  av a2s.c o m*/
    if (masterActorRef != null) {
        netconfTopologyDeviceSetup.getActorSystem().stop(masterActorRef);
        masterActorRef = null;
    }
    if (remoteDeviceConnector != null) {
        remoteDeviceConnector.stopRemoteDeviceConnection();
    }

    return Futures.immediateCheckedFuture(null);
}

From source file:io.airlift.discovery.client.HttpDiscoveryAnnouncementClient.java

@Override
public ListenableFuture<Void> unannounce() {
    URI uri = discoveryServiceURI.get();
    if (uri == null) {
        return Futures.immediateCheckedFuture(null);
    }//  w ww .  java 2s  . c  o  m

    Request request = prepareDelete().setUri(URI.create(uri + "/v1/announcement/" + nodeInfo.getNodeId()))
            .setHeader("User-Agent", nodeInfo.getNodeId()).build();
    return httpClient.executeAsync(request, new DiscoveryResponseHandler<Void>("Unannouncement", uri));
}

From source file:org.opendaylight.yangtools.yang.parser.repo.SharedSchemaContextFactory.java

private CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(
        final Collection<SourceIdentifier> requiredSources,
        final Cache<Collection<SourceIdentifier>, SchemaContext> cache,
        final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources) {
    // Make sources unique
    final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);

    final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
    if (existing != null) {
        LOG.debug("Returning cached context {}", existing);
        return Futures.immediateCheckedFuture(existing);
    }//from w  w  w  .  jav  a 2 s.  co m

    // Request all sources be loaded
    ListenableFuture<List<ASTSchemaSource>> sf = Futures
            .allAsList(Collections2.transform(uniqueSourceIdentifiers, this::requestSource));

    // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
    // Also remove duplicates if present
    // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
    sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));

    // Assemble sources into a schema context
    final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);

    // Populate cache when successful
    Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
        @Override
        public void onSuccess(final SchemaContext result) {
            cache.put(uniqueSourceIdentifiers, result);
        }

        @Override
        public void onFailure(@Nonnull final Throwable t) {
            LOG.debug("Failed to assemble sources", t);
        }
    });

    return Futures.makeChecked(cf, MAPPER);
}

From source file:io.airlift.discovery.client.testing.InMemoryDiscoveryClient.java

@Override
public CheckedFuture<ServiceDescriptors, DiscoveryException> getServices(String type, String pool) {
    Preconditions.checkNotNull(type, "type is null");
    Preconditions.checkNotNull(pool, "pool is null");

    ImmutableList.Builder<ServiceDescriptor> builder = ImmutableList.builder();
    for (ServiceDescriptor serviceDescriptor : this.announcements.get()) {
        if (serviceDescriptor.getType().equals(type) && serviceDescriptor.getPool().equals(pool)) {
            builder.add(serviceDescriptor);
        }/*from  w w  w.j  a  va 2 s.c o m*/
    }
    for (ServiceDescriptor serviceDescriptor : this.discovered.values()) {
        if (serviceDescriptor.getType().equals(type) && serviceDescriptor.getPool().equals(pool)) {
            builder.add(serviceDescriptor);
        }
    }
    return Futures.immediateCheckedFuture(
            new ServiceDescriptors(type, pool, builder.build(), maxAge, UUID.randomUUID().toString()));
}

From source file:org.apache.twill.internal.AbstractTwillService.java

/**
 * Handles message by simply logging it. Child class should override this method for custom handling of message.
 *
 * @see org.apache.twill.internal.state.MessageCallback
 */// w w w . ja va  2s.  c o m
@Override
public ListenableFuture<String> onReceived(String messageId, Message message) {
    LOG.info("Message received: {}", message);
    return Futures.immediateCheckedFuture(messageId);
}

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

/**
 * Returns an observable from a character source.
 *///  w  w  w .  j  av  a  2  s. c  o m
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.onos.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 = storageAdapters.get(representation)
                .restore(sourceIdentifier, file);
        return Futures.immediateCheckedFuture(representation.cast(restored));
    }//www. j  ava2  s.c o  m

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