Example usage for io.netty.util.concurrent Future addListener

List of usage examples for io.netty.util.concurrent Future addListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future addListener.

Prototype

Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);

Source Link

Document

Adds the specified listener to this future.

Usage

From source file:de.unipassau.isl.evs.ssh.app.handler.AppRegisterNewDeviceHandler.java

License:Open Source License

/**
 * Sends a request message for a token to the master. {@code requestToken()} does not return a Future like other
 * functions that are sending messages. Use the {@code RegisterNewDeviceListener} to get notified when a reply
 * message is handled by this handler.//from  w w w .  j av a2 s  .c  om
 *
 * @param user the user who is registered
 */
public void requestToken(UserDevice user) {
    Message message = new Message(new GenerateNewRegisterTokenPayload(null, user));
    final Future<GenerateNewRegisterTokenPayload> future = newResponseFuture(
            sendMessageToMaster(MASTER_USER_REGISTER, message));
    future.addListener(new FutureListener<GenerateNewRegisterTokenPayload>() {
        @Override
        public void operationComplete(Future<GenerateNewRegisterTokenPayload> future) throws Exception {
            if (future.isSuccess()) {
                handleUserRegisterResponse(future.get());
            } else {
                fireTokenError();
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppSlaveManagementHandler.java

License:Open Source License

/**
 * Sends a message to master to registers a new slave.
 *
 * @param slaveID                  the device ID of the new slave
 * @param slaveName                the name of the new slave
 * @param passiveRegistrationToken the passive Registration token
 *//*from w  w w . ja  v  a2s. com*/
public void registerNewSlave(DeviceID slaveID, String slaveName, byte[] passiveRegistrationToken) {
    RegisterSlavePayload payload = new RegisterSlavePayload(slaveName, slaveID, passiveRegistrationToken);
    final Future<Void> future = newResponseFuture(
            sendMessageToMaster(MASTER_SLAVE_REGISTER, new Message(payload)));
    future.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            fireSlaveRegistered(future.isSuccess());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppSlaveManagementHandler.java

License:Open Source License

/**
 * Sends a message to master to delete the given slave.
 *
 * @param slaveID the slave to delete/*from  w  ww.  j  a v a 2 s.  c om*/
 */
public void deleteSlave(DeviceID slaveID) {
    DeleteDevicePayload payload = new DeleteDevicePayload(slaveID);
    final Future<Void> future = newResponseFuture(
            sendMessageToMaster(MASTER_SLAVE_DELETE, new Message(payload)));
    future.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            fireSlaveRemoved(future.isSuccess());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AppUserConfigurationHandler.java

License:Open Source License

private void sendUserConfigMessage(Message message, RoutingKey<? extends MessagePayload> key,
        final UserConfigurationEvent.EventType eventType) {
    final Future<Void> future = newResponseFuture(sendMessageToMaster(key, message));
    future.addListener(new FutureListener<Void>() {
        @Override/*from w  ww .j a  v a  2 s.com*/
        public void operationComplete(Future<Void> future) throws Exception {
            final boolean success = future.isSuccess();
            fireUserInfoUpdated(new UserConfigurationEvent(eventType, success));
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.OutgoingRouter.java

License:Open Source License

private Message.AddressedMessage sendMessage(DeviceID toID, String routingKey, Message msg, boolean log) {
    final Message.AddressedMessage amsg = msg.setDestination(getOwnID(), toID, routingKey);
    final Future<Void> future = doSendMessage(amsg);
    amsg.setSendFuture(future);//from   ww  w . j  a va  2 s .  co  m
    if (log) {
        future.addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (future.isSuccess()) {
                    Log.v(TAG, "SENT " + amsg);
                } else {
                    Log.w(TAG, "Could not send Message " + amsg + " because of "
                            + Log.getStackTraceString(future.cause()));
                }
            }
        });
    }
    final AccessLogger logger = getComponent(AccessLogger.KEY);
    if (logger != null) {
        logger.logAccess(RoutingKey.forMessage(amsg));
    }
    return amsg;
}

From source file:de.unipassau.isl.evs.ssh.core.network.Client.java

License:Open Source License

/**
 * Initializes the netty client and tries to connect to the server.
 */// w  w  w . ja v  a  2 s .  c  o  m
protected synchronized void initClient() {
    Log.d(TAG, "initClient");
    if (!isActive) {
        Log.w(TAG, "Not starting Client that has been explicitly shut-down");
        return;
    }
    if (isChannelOpen()) {
        Log.w(TAG, "Not starting Client that is already connected");
        return;
    } else {
        // Close channels open from previous connections
        if (channelFuture != null && channelFuture.channel() != null) {
            Log.v(TAG, "Cleaning up " + (channelFuture.channel().isOpen() ? "open" : "closed")
                    + " Channel from previous connection attempt");
            channelFuture.channel().close();
        }
        // Clean-up the closed channel as it is no longer needed
        channelFuture = null;
    }

    // And queue the (re-)connect
    final Future<?> future = requireComponent(ExecutionServiceComponent.KEY).submit(new Runnable() {
        @Override
        public void run() {
            attemptConnectClient();
        }
    });
    future.addListener(new FutureListener<Object>() {
        @Override
        public void operationComplete(Future future) throws Exception {
            if (!future.isSuccess()) {
                Log.w(TAG, "Could not schedule connect to master", future.cause());
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.drivers.lib.EdimaxPlugSwitch.java

License:Open Source License

/**
 * Switches the Smart Plug on/*from  w  w w. j  av  a 2s.  c o  m*/
 *
 * @see #setOn(boolean)
 */
public Future<Boolean> setOnAsync(final boolean on) {
    final Future<Boolean> future = requireComponent(ExecutionServiceComponent.KEY)
            .submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return setOn(on);
                }
            });
    if (CoreConstants.TRACK_STATISTICS) {
        future.addListener(new TimingListener());
    }
    return future;
}

From source file:de.unipassau.isl.evs.ssh.drivers.lib.EdimaxPlugSwitch.java

License:Open Source License

/**
 * Checks the current status of the Smart Plug
 *
 * @see #isOn()/*from ww  w  .  j  ava2 s .c om*/
 */
public Future<Boolean> isOnAsync() {
    final Future<Boolean> future = requireComponent(ExecutionServiceComponent.KEY)
            .submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return isOn();
                }
            });
    if (CoreConstants.TRACK_STATISTICS) {
        future.addListener(new TimingListener());
    }
    return future;
}

From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl clientContext, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    ContextImpl context;//  www  .j ava  2  s. c o m
    if (clientContext == null) {
        // Embedded
        context = vertx.getOrCreateContext();
    } else {
        context = clientContext;
    }
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.nettyEventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, options.getMaxChunkSize(), false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        SSLHandshakeException sslException = new SSLHandshakeException(
                                "Failed to create SSL connection");
                        Optional.ofNullable(fut2.cause()).ifPresent(sslException::initCause);
                        connectionFailed(context, ch, connectErrorHandler, sslException, listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}

From source file:io.airlift.drift.transport.netty.client.ConnectionPool.java

License:Apache License

private Future<Channel> createConnection(ConnectionKey key) {
    Future<Channel> future = connectionFactory.getConnection(key.getConnectionParameters(), key.getAddress());

    // remove connection from cache when it is closed
    future.addListener(channelFuture -> {
        if (future.isSuccess()) {
            future.getNow().closeFuture()
                    .addListener(closeFuture -> cachedConnections.asMap().remove(key, future));
        }/*from  w  w w. j  av  a 2s .  c o  m*/
    });

    return future;
}