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:es.udc.pfc.gameroom.AbstractRoom.java

@Override
public ListenableFuture<Void> configureRoom() {
    final SettableFuture<Void> future = SettableFuture.create();
    final Map<String, List<String>> fields = Maps.newHashMap();
    final List<String> no = ImmutableList.of("0");
    final List<String> si = ImmutableList.of("1");

    fields.put("muc#roomconfig_persistentroom", no);
    fields.put("muc#roomconfig_publicroom", no);
    fields.put("muc#roomconfig_membersonly", si);
    fields.put("muc#roomconfig_changesubject", no);

    final IQ config = new IQ(IQ.Type.set);
    config.setFrom(component.getJID());/* w  w w . j a v a2  s  .c  om*/
    config.setTo(roomJID);
    final XMLElement data = config.addExtension("x", XMPPNamespaces.DATA);
    data.setAttribute("type", "submit");

    for (final Map.Entry<String, List<String>> field : fields.entrySet()) {
        final XMLElement f = data.addChild("field");
        f.setAttribute("var", field.getKey());
        for (final String value : field.getValue()) {
            f.addChild("value").setText(value);
        }
    }

    Futures.addCallback(component.sendIQ(config), new FutureCallback<IQ>() {
        @Override
        public void onSuccess(IQ result) {
            updateSubject();
            future.set(null);
        }

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

    return future;
}

From source file:org.apache.omid.transaction.HBaseSyncPostCommitter.java

@Override
public ListenableFuture<Void> removeCommitTableEntry(AbstractTransaction<? extends CellId> transaction) {

    SettableFuture<Void> updateSCFuture = SettableFuture.create();

    HBaseTransaction tx = HBaseTransactionManager.enforceHBaseTransactionAsParam(transaction);

    commitTableUpdateTimer.start();/*from   w w  w. j a  va 2 s .co  m*/

    try {
        commitTableClient.completeTransaction(tx.getStartTimestamp()).get();
        updateSCFuture.set(null);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.warn("{}: interrupted during commit table entry delete", tx, e);
        updateSCFuture.setException(
                new TransactionManagerException(tx + ": interrupted during commit table entry delete"));
    } catch (ExecutionException e) {
        LOG.warn("{}: can't remove commit table entry", tx, e);
        updateSCFuture.setException(new TransactionManagerException(tx + ": can't remove commit table entry"));
    } finally {
        commitTableUpdateTimer.stop();
    }

    return updateSCFuture;

}

From source file:org.opendaylight.ovsdb.lib.impl.StalePassiveConnectionService.java

/**
 * This method makes sure that all stale connections from the same node are properly cleaned up before processing
 * new connection request.// ww w  .  j  ava2  s  . c o m
 *
 * @param newOvsdbClient the connecting OvsdbClient
 * @param clientsFromSameNode list of existing OvsdbClients from the same node as the new OvsdbClient
 */
public void handleNewPassiveConnection(final OvsdbClient newOvsdbClient,
        final List<OvsdbClient> clientsFromSameNode) {
    final Map<OvsdbClient, SettableFuture> clientFutureMap = new ConcurrentHashMap<>();
    pendingConnectionClients.put(newOvsdbClient, clientFutureMap);

    // scheduled task for ping response timeout. Connections that don't response to the
    // ping or haven't disconnected after the timeout will be closed
    final ScheduledFuture<?> echoTimeoutFuture = executorService.schedule(new Runnable() {
        @Override
        public void run() {
            for (OvsdbClient client : clientFutureMap.keySet()) {
                Future<?> clientFuture = clientFutureMap.get(client);
                if (!clientFuture.isDone() && !clientFuture.isCancelled()) {
                    clientFuture.cancel(true);
                }
                if (client.isActive()) {
                    client.disconnect();
                }
            }
        }
    }, ECHO_TIMEOUT, TimeUnit.SECONDS);

    // for every connection create a SettableFuture, save it to 'clientFutureMap', and send a ping (echo).
    // The ping results in either:
    // 1. ping response returns - the connection is active
    // 2. the netty connection is closed due to IO exception -
    // The future is removed from the 'clientFutureMap' when the onSuccess event for each future arrives
    // If the map is empty we proceed with new connection process
    for (final OvsdbClient client : clientsFromSameNode) {
        SettableFuture clientFuture = SettableFuture.create();
        clientFutureMap.put(client, clientFuture);
        Futures.addCallback(clientFuture, createStaleConnectionFutureCallback(client, newOvsdbClient,
                clientFutureMap, echoTimeoutFuture));
        Futures.addCallback(client.echo(), createStaleConnectionFutureCallback(client, newOvsdbClient,
                clientFutureMap, echoTimeoutFuture));
    }
}

From source file:ro.startx.ups.server.Sender.java

/**
 * Asynchronously send a message with a context to be passed in the future result.
 *
 * @param message The message to send.//w ww  .  j av a 2 s .  c o m
 * @param requestContext An opaque context to include the future result.
 * @return The future.
 */
public ListenableFuture<Result> send(final Message message, final Object requestContext) {
    return executor.getFutureWithRetry(new RetryCallable<ListenableFuture<Result>>() {
        @Override
        public ListenableFuture<Result> call(RetryContext context) throws Exception {
            SettableFuture<Result> future = SettableFuture.create();
            HttpPost request = new HttpPost(url);

            request.setEntity(new StringEntity(message.serialize(), ContentType.parse("application/json")));

            client.execute(request, new ResponseHandler(future, requestContext));

            return future;
        }
    });
}

From source file:com.twitter.heron.statemgr.localfs.LocalFileSystemStateManager.java

protected ListenableFuture<Boolean> deleteData(String path) {
    final SettableFuture<Boolean> future = SettableFuture.create();
    boolean ret = FileUtils.deleteFile(path);
    future.set(ret);/*from w w  w . jav a2 s. co  m*/

    return future;
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.RadioHeadConnectionProviderImpl.java

@Override
public ListenableFuture<Boolean> startup() {
    LOG.debug("Startup summoned");
    ListenableFuture<Boolean> result = null;
    try {//from w w w  . j  av  a2s .c om
        serverFacade = createAndConfigureServer();
        if (radioHeadConnectionHandler == null) {
            throw new IllegalStateException("RadioHeadConnectionHandler is not set");
        }
        new Thread(serverFacade).start();
        result = serverFacade.getIsOnlineFuture();
    } catch (Exception e) {
        SettableFuture<Boolean> exResult = SettableFuture.create();
        exResult.setException(e);
        result = exResult;
    }
    return result;
}

From source file:com.google.NithPoints.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.
 * @return/*from  www  .ja v  a 2 s. c  om*/
 */
public static ListenableFuture<TCPNetworkConnection> connectTo(NetworkParameters params,
        InetSocketAddress address, int connectTimeoutMsec) {
    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());
    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:org.opendaylight.netconf.topology.pipeline.tx.ProxyReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture = Futures.makeChecked(settableFuture,
            new Function<Exception, ReadFailedException>() {
                @Nullable/*from   w w w . j a v a  2 s .c  o  m*/
                @Override
                public ReadFailedException apply(Exception cause) {
                    return new ReadFailedException("Read from transaction failed", cause);
                }
            });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(Throwable throwable, Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:com.google.digitalcoin.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.
 * @return/* w  w  w.j a v  a  2  s  . c om*/
 */
public static ListenableFuture<TCPNetworkConnection> connectTo(NetworkParameters params,
        InetSocketAddress address, int connectTimeoutMsec) {
    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();
    pipeline.addLast("codec", conn.getHandler());
    clientBootstrap.setPipeline(pipeline);
    clientBootstrap.setOption("connectTimeoutMillis", Integer.valueOf(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.windowsazure.mobileservices.http.MobileServiceHttpClient.java

/**
 * Makes a request over HTTP/* www  .j  ava 2s  . co m*/
 *
 * @param path           The path of the request URI
 * @param content        The string to send as the request body
 * @param httpMethod     The HTTP Method used to invoke the API
 * @param requestHeaders The extra headers to send in the request
 * @param parameters     The query string parameters sent in the request
 * @param features       The features used in the request
 * @throws java.io.UnsupportedEncodingException If the content cannot be converted into a byte array.
 */
public ListenableFuture<ServiceFilterResponse> request(String path, String content, String httpMethod,
        List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters,
        EnumSet<MobileServiceFeatures> features) {
    try {
        byte[] byteContent = null;

        if (content != null) {
            byteContent = content.getBytes(MobileServiceClient.UTF8_ENCODING);
        }

        return this.request(path, byteContent, httpMethod, requestHeaders, parameters, features);
    } catch (UnsupportedEncodingException e) {
        SettableFuture<ServiceFilterResponse> future = SettableFuture.create();
        future.setException(e);
        return future;
    }
}