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

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

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) 

Source Link

Document

Creates a ListenableFuture which has its value set immediately upon construction.

Usage

From source file:org.jclouds.rest.internal.AsyncRestClientProxy.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private ListenableFuture<?> createListenableFuture(Method method, Object[] args) throws ExecutionException {
    method = annotationProcessor.getDelegateOrNull(method);
    logger.trace("Converting %s.%s", declaring.getSimpleName(), method.getName());
    Function<Exception, ?> exceptionParser = annotationProcessor
            .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(method);
    // in case there is an exception creating the request, we should at least
    // pass in args
    if (exceptionParser instanceof InvocationContext) {
        ((InvocationContext) exceptionParser).setContext((HttpRequest) null);
    }/*from  w  ww  .j a  va  2s  .  c  om*/
    ListenableFuture<?> result;
    try {
        GeneratedHttpRequest<T> request = annotationProcessor.createRequest(method, args);
        if (exceptionParser instanceof InvocationContext) {
            ((InvocationContext) exceptionParser).setContext(request);
        }
        logger.trace("Converted %s.%s to %s", declaring.getSimpleName(), method.getName(),
                request.getRequestLine());

        Function<HttpResponse, ?> transformer = annotationProcessor.createResponseParser(method, request);
        logger.trace("Response from %s.%s is parsed by %s", declaring.getSimpleName(), method.getName(),
                transformer.getClass().getSimpleName());

        logger.debug("Invoking %s.%s", declaring.getSimpleName(), method.getName());
        result = commandFactory.create(request, transformer).execute();

    } catch (RuntimeException e) {
        AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class);
        if (aex != null)
            e = aex;
        if (exceptionParser != null) {
            try {
                return Futures.immediateFuture(exceptionParser.apply(e));
            } catch (Exception ex) {
                return Futures.immediateFailedFuture(ex);
            }
        }
        return Futures.immediateFailedFuture(e);
    }

    if (exceptionParser != null) {
        logger.trace("Exceptions from %s.%s are parsed by %s", declaring.getSimpleName(), method.getName(),
                exceptionParser.getClass().getSimpleName());
        result = new ExceptionParsingListenableFuture(result, exceptionParser);
    }
    return result;
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeProcessMiningSPI.java

@Override
public Future<IProcessCycle> addProcessCycle(String docType, IProcessCycle cycle, SecurityToken token) {
    // check linking person parameter
    /*/*ww w  .j a  v  a 2 s .c o  m*/
     * if (token == null || token.getViewerId() == null || token.getViewerId().isEmpty()) { throw
     * new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
     * "viewer ID from security token is required"); }
     */

    // convert to map
    final Map<String, Object> cycleMap = new HashMap<String, Object>();
    ProcessCycleDTO dto = new ProcessCycleDTO(cycleMap);
    dto.setData(cycle);

    // create query
    final WebsockQuery query = new WebsockQuery(EQueryType.PROCEDURE_CALL);
    query.setPayload(ShindigNativeQueries.ADD_PROCESS_CYCLE_QUERY);

    // set parameters for method
    query.setParameter(ShindigNativeQueries.PROCESS_CYCLE_DOC_TYPE, docType);
    query.setParameter(ShindigNativeQueries.PROCESS_CYCLE_OBJECT, cycleMap);

    // execute
    final IQueryCallback result = this.fQueryHandler.sendQuery(query);

    SingleResult sResult = null;

    try {
        sResult = (SingleResult) result.get();
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failed to execute query", e);
    }

    @SuppressWarnings("unchecked")
    final Map<String, Object> map = (Map<String, Object>) sResult.getResults();
    dto = new ProcessCycleDTO(map);

    return Futures.immediateFuture((IProcessCycle) dto);
}

From source file:com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService.java

@Override
public Future<Void> putAll(Map<?, ?> values, Expiration expires) {
    memcacheService.putAll(values, expires);
    return Futures.immediateFuture(null);
}

From source file:org.opendaylight.discovery.providers.identification.IdentificationProvider.java

@Override
public Future<RpcResult<DiscoverNetworkElementOutput>> discoverNetworkElement(
        final DiscoverNetworkElementInput input) {
    log.debug("RPC: discoverNetworkElement : RECEIVED : {}, {}, {}", input.getRequestId(),
            input.getNetworkElementIp(), input.getNetworkElementType());
    /*//from  w  ww  . j  av  a2  s .co  m
     * It no request ID was specified with the notification then generate a
     * request ID
     */
    String txnId = input.getRequestId();
    if (txnId == null || txnId.isEmpty()) {
        txnId = UUID.randomUUID().toString();
    }

    final DiscoverNetworkElementOutputBuilder result = new DiscoverNetworkElementOutputBuilder();
    result.setRequestId(txnId);
    result.setResult(true);
    final NewNetworkElementBuilder notification = new NewNetworkElementBuilder();
    notification.setRequestId(txnId);
    notification.setNodeId(null); // node-id is not available when the NE is
                                  // discovered initially
    notification.setNetworkElementIp(input.getNetworkElementIp());
    notification.setNetworkElementType(input.getNetworkElementType());
    notification.setUsername(input.getUsername());
    notification.setPassword(input.getPassword());
    log.debug("EVENT : NewNetworkElement : PUBLISH : {}, {}, {}", notification.getRequestId(),
            notification.getNetworkElementIp(), notification.getNetworkElementType());
    notificationProviderService.publish(notification.build());

    return Futures
            .immediateFuture(RpcResultBuilder.<DiscoverNetworkElementOutput>success(result.build()).build());
}

From source file:org.apache.gobblin.writer.SequentialBasedBatchAccumulator.java

/**
 * Add a data to internal deque data structure
 *///w  w w . j  a v  a 2  s.c o m
public final Future<RecordMetadata> enqueue(D record, WriteCallback callback) throws InterruptedException {
    final ReentrantLock lock = this.dqLock;
    lock.lock();
    try {
        BytesBoundedBatch last = dq.peekLast();
        if (last != null) {
            Future<RecordMetadata> future = null;
            try {
                future = last.tryAppend(record, callback, this.largeMessagePolicy);
            } catch (RecordTooLargeException e) {
                // Ok if the record was too large for the current batch
            }
            if (future != null) {
                return future;
            }
        }

        // Create a new batch because previous one has no space
        BytesBoundedBatch batch = new BytesBoundedBatch(this.memSizeLimit, this.expireInMilliSecond);
        LOG.debug("Batch " + batch.getId() + " is generated");
        Future<RecordMetadata> future = null;
        try {
            future = batch.tryAppend(record, callback, this.largeMessagePolicy);
        } catch (RecordTooLargeException e) {
            // If a new batch also wasn't able to accomodate the new message
            throw new RuntimeException("Failed due to a message that was too large", e);
        }

        // The future might be null, since the largeMessagePolicy might be set to DROP
        if (future == null) {
            assert largeMessagePolicy.equals(LargeMessagePolicy.DROP);
            LOG.error("Batch " + batch.getId() + " is silently marked as complete, dropping a huge record: "
                    + record);
            future = Futures.immediateFuture(new RecordMetadata(0));
            callback.onSuccess(WriteResponse.EMPTY);
            return future;
        }

        // if queue is full, we should not add more
        while (dq.size() >= this.capacity) {
            LOG.debug("Accumulator size {} is greater than capacity {}, waiting", dq.size(), this.capacity);
            this.notFull.await();
        }
        dq.addLast(batch);
        incomplete.add(batch);
        this.notEmpty.signal();
        return future;

    } finally {
        lock.unlock();
    }
}

From source file:org.apache.qpid.server.txn.AsyncAutoCommitTransaction.java

public void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction) {
    Transaction txn = null;//from  w  ww  .java2s  . c  o  m
    try {
        for (MessageInstance entry : queueEntries) {
            MessageEnqueueRecord record = entry.getEnqueueRecord();

            if (record != null) {
                _logger.debug("Dequeue of message number {} from transaction log. Queue : {}",
                        record.getMessageNumber(), record.getQueueId());

                if (txn == null) {
                    txn = _messageStore.newTransaction();
                }

                txn.dequeueMessage(record);
            }

        }
        ListenableFuture<Void> future;
        if (txn != null) {
            future = txn.commitTranAsync((Void) null);
            txn = null;
        } else {
            future = Futures.immediateFuture(null);
        }
        addFuture(future, postTransactionAction);
        postTransactionAction = null;
    } finally {
        rollbackIfNecessary(postTransactionAction, txn);
    }

}

From source file:org.opendaylight.lispflowmapping.southbound.LispSouthboundRPC.java

@Override
public Future<RpcResult<GetStatsOutput>> getStats() {
    LOG.trace("getStats called!!");

    RpcResultBuilder<GetStatsOutput> rpcResultBuilder;

    LispSouthboundStats stats = lispSbPlugin.getStats();

    if (stats == null) {
        rpcResultBuilder = RpcResultBuilder.<GetStatsOutput>failed().withError(RpcError.ErrorType.APPLICATION,
                "data-missing", "No stats found");
    } else {/*from  w  w  w  .  j a  va  2s .c om*/
        rpcResultBuilder = RpcResultBuilder.success(createGetStatsOutput(stats));
    }
    return Futures.immediateFuture(rpcResultBuilder.build());
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeAlbumSPI.java

private Future<RestfulCollection<Album>> convertList(IQueryCallback result) {
    ListResult lResult = null;/*from   w ww  . j a v a2s.c o  m*/

    try {
        lResult = (ListResult) result.get();

        // TODO: proper not found exception
        if (lResult == null) {
            return null;
        }
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not retrieve results",
                e);
    }

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> mapList = (List<Map<String, Object>>) lResult.getResults();

    final List<Album> albums = new LinkedList<Album>();

    for (final Map<String, Object> aMap : mapList) {
        albums.add(new AlbumDTO(aMap));
    }

    final RestfulCollection<Album> rColl = new RestfulCollection<Album>(albums);
    rColl.setStartIndex(lResult.getFirst());
    rColl.setTotalResults(lResult.getTotal());
    rColl.setItemsPerPage(lResult.getMax());
    return Futures.immediateFuture((rColl));
}

From source file:org.opendaylight.vpnservice.fibmanager.FibRpcServiceImpl.java

/**
 * to remove FIB/LFIB/TST routes from specified dpn
 *
 *//*from  w ww . j a v a  2  s .  co  m*/
public Future<RpcResult<Void>> removeFibEntry(RemoveFibEntryInput input) {

    BigInteger dpnId = input.getSourceDpid();
    String vpnName = input.getVpnName();
    long vpnId = getVpnId(broker, vpnName);
    long serviceId = input.getServiceId();
    String ipAddress = input.getIpAddress();

    LOG.info("Delete custom FIB entry - {} on dpn {} for VPN {} ", ipAddress, dpnId, vpnName);

    removeLocalFibEntry(dpnId, vpnId, ipAddress);
    //removeLFibTableEntry(dpnId, serviceId);
    //removeTunnelTableEntry(dpnId, serviceId);
    removeFromVpnDpnAssociation(vpnId, dpnId, ipAddress, vpnName);

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

From source file:com.facebook.buck.artifact_cache.SQLiteArtifactCache.java

@Override
public ListenableFuture<CacheResult> fetchAsync(@Nullable BuildTarget target, RuleKey ruleKey,
        LazyPath output) {
    return Futures.immediateFuture(fetch(ruleKey, output));
}