Example usage for com.google.common.util.concurrent SettableFuture create

List of usage examples for com.google.common.util.concurrent SettableFuture create

Introduction

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

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:org.opendaylight.ocpplugin.impl.services.SalConfigMgmtServiceImpl.java

@Override
public Future<RpcResult<ModifyParamOutput>> modifyParam(final ModifyParamInput input) {
    ListenableFuture<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyParamOutput>> future = modifyParam
            .handleServiceCall(input);// w  ww  .j  av a2 s  . c  om
    final SettableFuture<RpcResult<ModifyParamOutput>> finalFuture = SettableFuture.create();
    Futures.addCallback(future,
            new FutureCallback<RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyParamOutput>>() {
                @Override
                public void onSuccess(
                        final RpcResult<org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyParamOutput> result) {
                    org.opendaylight.yang.gen.v1.urn.opendaylight.ocp.protocol.rev150811.ModifyParamOutput output = result
                            .getResult();
                    ModifyParamOutputBuilder builder = new ModifyParamOutputBuilder();
                    builder.setObjId(output.getObjId());
                    builder.setParam(output.getParam());
                    builder.setGlobResult(output.getGlobResult());
                    RpcResultBuilder<ModifyParamOutput> rpcResultBuilder = RpcResultBuilder.success(builder);
                    finalFuture.set(rpcResultBuilder.build());
                }

                @Override
                public void onFailure(final Throwable t) {
                    RpcResultBuilder<ModifyParamOutput> rpcResultBuilder = RpcResultBuilder.failed();
                    finalFuture.set(rpcResultBuilder.build());
                }
            });

    return finalFuture;
}

From source file:io.v.baku.toolkit.blessings.ActivityBlessingsSeeker.java

@Override
@Synchronized("mSeekLock")
public ListenableFuture<Blessings> refreshBlessings() {
    if (isAwaitingBlessings()) {
        return mCurrentSeek;
    }/*from  w  ww .  jav a 2s . c  om*/

    Blessings mgrBlessings;
    try {
        mgrBlessings = BlessingsManager.getBlessings(mActivity.getApplicationContext());
    } catch (final VException e) {
        log.warn("Could not get blessings from shared preferences", e);
        mgrBlessings = null;
    }

    final ListenableFuture<Blessings> nextBlessings;

    if (mgrBlessings == null) {
        nextBlessings = mCurrentSeek = SettableFuture.create();
        seekBlessings();
    } else {
        nextBlessings = Futures.immediateFuture(mgrBlessings);
    }
    mPub.onNext(nextBlessings);

    return nextBlessings;
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.JsonRpcEndpoint.java

/**
 *
 * Send a concrete {@link RpcMessage} to the RPC endpoint.
 *
 * @param message The concrete {@link RpcMessage} to send
 * @return SettableFuture<Object> The caller can use the returned
 * object to wait for the response (currently no timeout)
 * @throws Throwable The concrete message couldn't be serialized and sent
 *///from   ww  w  .ja  v  a  2s  . c  o m
public SettableFuture<Object> sendRequest(RpcMessage message) throws Throwable {
    if (messageMap.get(message.getName()) == null) {
        return null;
    }
    message.setId(UUID.randomUUID().toString());

    String s = objectMapper.writeValueAsString(message);
    logger.trace("invoke: {}", s);

    SettableFuture<Object> sf = SettableFuture.create();
    methodContext.put(message.getId(), new CallContext(message.getName(), sf));

    nettyChannel.writeAndFlush(s);

    return sf;
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint.java

public <T> T getClient(final Object context, Class<T> klazz) {

    return Reflection.newProxy(klazz, new InvocationHandler() {
        @Override/*from  w  w  w.  j a v a  2  s  .c  om*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
                if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
                    return false;
                }
                requestCallbacks.put(context, (OvsdbRPC.Callback) args[0]);
                return true;
            }

            JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
            request.setMethod(method.getName());

            if (args != null && args.length != 0) {
                List<Object> params = null;

                if (args.length == 1) {
                    if (args[0] instanceof Params) {
                        params = ((Params) args[0]).params();
                    } else if (args[0] instanceof List) {
                        params = (List<Object>) args[0];
                    }

                    if (params == null) {
                        throw new UnsupportedArgumentException("do not understand this argument yet");
                    }
                    request.setParams(params);
                }
            }

            String requestString = objectMapper.writeValueAsString(request);
            logger.trace("getClient Request : {}", requestString);

            SettableFuture<Object> sf = SettableFuture.create();
            methodContext.put(request.getId(), new CallContext(request, method, sf));

            nettyChannel.writeAndFlush(requestString);

            return sf;
        }
    });
}

From source file:com.google.logicoin.core.TCPNetworkConnection.java

/**
 * Returns a future for a TCPNetworkConnection that is connected and version negotiated to the given remote address.
 * Behind the scenes this method sets up a thread pool and a Netty pipeline that uses it. The equivalent Netty code
 * is quite complex so use this method if you aren't writing a complex app. The future completes once version
 * handshaking is done, use .get() on the response to wait for it.
 *
 * @param params The network parameters to use (production or testnet)
 * @param address IP address and port to use
 * @param connectTimeoutMsec How long to wait before giving up and setting the future to failure.
 * @param peer If not null, this peer will be added to the pipeline.
 *///from w w  w. j a va  2s  .  c  om
public static ListenableFuture<TCPNetworkConnection> connectTo(NetworkParameters params,
        InetSocketAddress address, int connectTimeoutMsec, @Nullable Peer peer) {
    synchronized (TCPNetworkConnection.class) {
        if (channelFactory == null) {
            ExecutorService bossExecutor = Executors.newCachedThreadPool();
            ExecutorService workerExecutor = Executors.newCachedThreadPool();
            channelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor);
        }
    }
    // Run the connection in the thread pool and wait for it to complete.
    ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
    ChannelPipeline pipeline = Channels.pipeline();
    final TCPNetworkConnection conn = new TCPNetworkConnection(params, new VersionMessage(params, 0));
    conn.handshakeFuture = SettableFuture.create();
    conn.setRemoteAddress(address);
    pipeline.addLast("codec", conn.getHandler());
    if (peer != null)
        pipeline.addLast("peer", peer.getHandler());
    clientBootstrap.setPipeline(pipeline);
    clientBootstrap.setOption("connectTimeoutMillis", connectTimeoutMsec);
    ChannelFuture socketFuture = clientBootstrap.connect(address);
    // Once the socket is either connected on the TCP level, or failed ...
    socketFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            // Check if it failed ...
            if (channelFuture.isDone() && !channelFuture.isSuccess()) {
                // And complete the returned future with an exception.
                conn.handshakeFuture.setException(channelFuture.getCause());
            }
            // Otherwise the handshakeFuture will be marked as completed once we did ver/verack exchange.
        }
    });
    return conn.handshakeFuture;
}

From source file:com.microsoft.office365.SharepointClient.java

/**
 * Execute request json with digest./* www.  j a v  a 2 s .  c  om*/
 * 
 * @param url
 *            the url
 * @param method
 *            the method
 * @param headers
 *            the headers
 * @param payload
 *            the payload
 * @return OfficeFuture<JSONObject>
 */
protected ListenableFuture<JSONObject> executeRequestJsonWithDigest(final String url, final String method,
        final Map<String, String> headers, final byte[] payload) {

    final SettableFuture<JSONObject> result = SettableFuture.create();
    ListenableFuture<String> digestFuture = getFormDigest();

    Futures.addCallback(digestFuture, new FutureCallback<String>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(String digest) {
            Map<String, String> finalHeaders = new HashMap<String, String>();

            if (headers != null) {
                for (String key : headers.keySet()) {
                    finalHeaders.put(key, headers.get(key));
                }
            }

            finalHeaders.put("Content-Type", "application/json;odata=verbose");
            finalHeaders.put("X-RequestDigest", digest);

            ListenableFuture<JSONObject> request = executeRequestJson(url, method, finalHeaders, payload);

            Futures.addCallback(request, new FutureCallback<JSONObject>() {
                @Override
                public void onFailure(Throwable t) {
                    result.setException(t);
                }

                @Override
                public void onSuccess(JSONObject json) {
                    result.set(json);
                }
            });
        }
    });
    return result;
}

From source file:edu.umich.si.inteco.minuku.dao.ImageDataRecordDAO.java

@Override
public Future<List<ImageDataRecord>> getLast(int N) throws DAOException {
    final SettableFuture<List<ImageDataRecord>> settableFuture = SettableFuture.create();
    final Date today = new Date();

    final List<ImageDataRecord> lastNRecords = Collections.synchronizedList(new ArrayList<ImageDataRecord>());

    getLastNValues(N, myUserEmail, today, lastNRecords, settableFuture);

    return settableFuture;
}

From source file:com.android.ddmlib.PropertyFetcher.java

/**
 * Make a possibly asynchronous request for a system property value.
 *
 * @param name the property name to retrieve
 * @return a {@link Future} that can be used to retrieve the prop value
 *///from   w  ww.  j ava 2s .c  o  m
@NonNull
public synchronized Future<String> getProperty(@NonNull String name) {
    SettableFuture<String> result;
    if (mCacheState.equals(CacheState.FETCHING)) {
        result = addPendingRequest(name);
    } else if (mDevice.isOnline() && mCacheState.equals(CacheState.UNPOPULATED) || !isRoProp(name)) {
        // cache is empty, or this is a volatile prop that requires a query
        result = addPendingRequest(name);
        mCacheState = CacheState.FETCHING;
        initiatePropertiesQuery();
    } else {
        result = SettableFuture.create();
        // cache is populated and this is a ro prop
        result.set(mProperties.get(name));
    }
    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTable.java

/**
 * Executes a query to retrieve all the table rows
 *
 * @throws com.microsoft.windowsazure.mobileservices.MobileServiceException
 *//*from w w w.j av  a  2 s .  co  m*/
public ListenableFuture<MobileServiceList<E>> execute() throws MobileServiceException {
    final SettableFuture<MobileServiceList<E>> future = SettableFuture.create();
    ListenableFuture<JsonElement> internalFuture = mInternalTable.execute();
    Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable exc) {
            future.setException(exc);
        }

        @Override
        public void onSuccess(JsonElement result) {
            try {
                if (result.isJsonObject()) {
                    JsonObject jsonObject = result.getAsJsonObject();

                    int count = jsonObject.get("count").getAsInt();
                    JsonElement elements = jsonObject.get("results");

                    List<E> list = parseResults(elements);
                    future.set(new MobileServiceList<E>(list, count));
                } else {
                    List<E> list = parseResults(result);
                    future.set(new MobileServiceList<E>(list, -1));
                }
            } catch (Exception e) {
                future.setException(e);
            }
        }
    });

    return future;
}

From source file:io.crate.executor.transport.task.elasticsearch.QueryThenFetchPageableTaskResult.java

private ListenableFuture<PageableTaskResult> fetchWithNewQTF(final PageInfo pageInfo) {
    final SettableFuture<PageableTaskResult> future = SettableFuture.create();
    QueryThenFetchNode oldNode = ctx.searchNode();
    Futures.addCallback(operation.execute(oldNode, ctx.outputs(), Optional.of(pageInfo)),
            new FutureCallback<QueryThenFetchOperation.QueryThenFetchContext>() {
                @Override/*  www  .  j a  va2 s.  com*/
                public void onSuccess(@Nullable final QueryThenFetchOperation.QueryThenFetchContext newCtx) {
                    Futures.addCallback(newCtx.createSearchResponse(),
                            new FutureCallback<InternalSearchResponse>() {
                                @Override
                                public void onSuccess(@Nullable InternalSearchResponse searchResponse) {
                                    ObjectArray<Object[]> pageSource = newCtx
                                            .toPage(searchResponse.hits().hits(), extractors);
                                    newCtx.cleanAfterFirstPage();
                                    future.set(new QueryThenFetchPageableTaskResult(operation, newCtx,
                                            extractors, pageInfo, pageSource, 0L));
                                    closeSafe(); // close old searchcontexts and stuff
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    closeSafe();
                                    future.setException(t);
                                }
                            });
                }

                @Override
                public void onFailure(Throwable t) {
                    closeSafe();
                    future.setException(t);
                }
            });
    return future;
}