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

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

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(ListenableFuture<V> future,
        Function<? super Exception, X> mapper) 

Source Link

Document

Creates a CheckedFuture out of a normal ListenableFuture and a Function that maps from Exception instances into the appropriate checked type.

Usage

From source file:org.opendaylight.netconf.sal.connect.netconf.sal.tx.WriteCandidateTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override/*  w w w. j av a 2 s  .c om*/
                public Void apply(final RpcResult<TransactionStatus> input) {
                    Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
                            "Submit failed with errors: %s", input.getErrors());
                    return null;
                }
            });

    return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
        @Override
        public TransactionCommitFailedException apply(final Exception input) {
            return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
                    input);
        }
    });
}

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);
    }/*ww w  .  j a  v  a  2 s.c o  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:org.opendaylight.controller.sal.connect.netconf.sal.tx.WriteCandidateTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override//ww w  .  j  a  v a  2 s .  c  o m
                public Void apply(final RpcResult<TransactionStatus> input) {
                    return null;
                }
            });

    return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
        @Override
        public TransactionCommitFailedException apply(final Exception input) {
            return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
                    input);
        }
    });
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.util.MonitoredUDFExecutor.java

public Object monitorExec(final Tuple input) throws IOException {
    CheckedFuture<Object, Exception> f = Futures.makeChecked(
            // the Future whose exceptions we want to catch
            exec.submit(new Callable<Object>() {
                @Override/*w  ww .  j  av  a2 s  .  co  m*/
                public Object call() throws Exception {
                    return closure.apply(input);
                }
            }),
            // How to map those exceptions; we simply rethrow them.
            // Theoretically we could do some handling of
            // CancellationException, ExecutionException  and InterruptedException here
            // and do something special for UDF IOExceptions as opposed to thread exceptions.
            new Function<Exception, Exception>() {
                @Override
                public Exception apply(Exception e) {
                    return e;
                }
            });

    Object result = defaultValue;

    // The outer try "should never happen" (tm).
    try {
        try {
            result = f.get(duration, timeUnit);
        } catch (TimeoutException e) {
            timeoutHandler.invoke(null, evalFunc, e);
        } catch (Exception e) {
            errorHandler.invoke(null, evalFunc, e);
        } finally {
            f.cancel(true);
        }
    } catch (IllegalArgumentException e) {
        throw new IOException(e);
    } catch (IllegalAccessException e) {
        throw new IOException(e);
    } catch (InvocationTargetException e) {
        throw new IOException(e);
    }
    return result;
}

From source file:org.opendaylight.sxp.controller.core.DatastoreAccess.java

/**
 * @param path                 InstanceIdentifier path specifying data
 * @param data                 Data that will be used in operation
 * @param logicalDatastoreType Type of datastore where operation will be held
 * @param <T>                  Any type extending DataObject
 * @return CheckedFuture callback of operation
 *///from  w w  w  .j  a  v  a2 s  .  com
public synchronized <T extends DataObject> CheckedFuture<Void, TransactionCommitFailedException> put(
        InstanceIdentifier<T> path, T data, LogicalDatastoreType logicalDatastoreType) {
    if (!checkParams(path, logicalDatastoreType)) {
        return Futures.makeChecked(Futures.immediateCancelledFuture(), input -> ACCESS_CLOSED_ON_RW);
    }
    Preconditions.checkNotNull(data);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Put {} {}", logicalDatastoreType, path.getTargetType());
    }
    WriteTransaction transaction = bindingTransactionChain.newWriteOnlyTransaction();
    transaction.put(logicalDatastoreType, path, data);
    return transaction.submit();
}

From source file:org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.java

@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
        final SourceIdentifier sourceIdentifier) {
    final String moduleName = sourceIdentifier.getName();

    // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
    final String formattedRevision = sourceIdentifier.getRevision()
            .equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision();
    final Optional<String> revision = Optional.fromNullable(formattedRevision);
    final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);

    LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);

    final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
            rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
                    getSchemaRequest),/* w  w  w  . j  a  v  a2 s . c o m*/
            new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));

    final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed,
            MAPPER);

    return checked;
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.legacy.sharded.adapter.ShardedDOMDataBrokerDelegatingReadWriteTransaction.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkState(root != null,/* w w  w . j  av a 2 s  .co m*/
            "A modify operation (put, merge or delete) must be performed prior to a read operation");
    final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();
    final Queue<Modification> currentHistory = Lists.newLinkedList(modificationHistoryMap.get(store));
    Futures.addCallback(initialReadMap.get(store), new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            final DataTreeModification mod = snapshotMap.get(store).newModification();
            if (result.isPresent()) {
                mod.write(path, result.get());
            }
            applyModificationHistoryToSnapshot(mod, currentHistory);
            readResult.set(mod.readNode(path));
        }

        @Override
        public void onFailure(final Throwable t) {
            readResult.setException(t);
        }
    });

    return Futures.makeChecked(readResult, ReadFailedException.MAPPER);
}

From source file:org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.java

@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
        final SourceIdentifier sourceIdentifier) {
    final String moduleName = sourceIdentifier.getName();

    // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
    final String formattedRevision = sourceIdentifier.getRevision()
            .equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision();
    final Optional<String> revision = Optional.fromNullable(formattedRevision);
    final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);

    logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);

    final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
            rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
                    getSchemaRequest),//  w  w w.  jav a  2s.c  o  m
            new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));

    final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed,
            MAPPER);

    // / FIXME remove this get, it is only present to wait until source is retrieved
    // (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly)
    // TODO retest this
    try {
        logger.trace("{}: Blocking for {}", id, sourceIdentifier);
        checked.checkedGet();
    } catch (final SchemaSourceException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }

    return checked;
}

From source file:org.opendaylight.sxp.controller.core.DatastoreAccess.java

/**
 * @param path                 InstanceIdentifier path specifying data
 * @param logicalDatastoreType Type of datastore where operation will be held
 * @param <T>                  Any type extending DataObject
 * @return CheckedFuture callback of operation
 *//*from w w  w .j  a v a 2 s.co m*/
public synchronized <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read(
        InstanceIdentifier<T> path, LogicalDatastoreType logicalDatastoreType) {
    if (!checkParams(path, logicalDatastoreType)) {
        return Futures.makeChecked(Futures.immediateCancelledFuture(), input -> ACCESS_CLOSED_ON_R);
    }
    try (ReadOnlyTransaction transaction = bindingTransactionChain.newReadOnlyTransaction()) {
        return transaction.read(logicalDatastoreType, path);
    }
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.legacy.sharded.adapter.ShardedDOMDataBrokerDelegatingReadWriteTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    checkState(root != null,/*from   www .j  ava 2  s.c o m*/
            "A modify operation (put, merge or delete) must be performed prior to an exists operation");
    return Futures.makeChecked(
            Futures.transform(read(store, path),
                    (Function<Optional<NormalizedNode<?, ?>>, Boolean>) Optional::isPresent),
            ReadFailedException.MAPPER);
}