Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

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

Prototype

GenericFutureListener

Source Link

Usage

From source file:com.turo.pushy.apns.server.BaseHttp2Server.java

License:Open Source License

BaseHttp2Server(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }/*ww w .  jav  a  2  s  .c om*/

    this.bootstrap = new ServerBootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.allChannels = new DefaultChannelGroup(this.bootstrap.config().group().next());

    this.bootstrap.channel(ServerChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline().addLast(ConnectionNegotiationErrorHandler.INSTANCE);

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) throws Exception {
                    if (handshakeFuture.isSuccess()) {
                        BaseHttp2Server.this.addHandlersToPipeline(sslHandler.engine().getSession(),
                                channel.pipeline());
                        channel.pipeline().remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        BaseHttp2Server.this.allChannels.add(channel);
                    } else {
                        log.debug("TLS handshake failed.", handshakeFuture.cause());
                    }
                }
            });
        }
    });
}

From source file:com.turo.pushy.apns.server.BaseHttp2Server.java

License:Open Source License

/**
 * <p>Shuts down this server and releases the port to which this server was bound. If a {@code null} event loop
 * group was provided at construction time, the server will also shut down its internally-managed event loop
 * group.</p>/*from ww w  .j av  a2  s . c o m*/
 *
 * <p>If a non-null {@code EventLoopGroup} was provided at construction time, mock servers may be reconnected and
 * reused after they have been shut down. If no event loop group was provided at construction time, mock servers may
 * not be restarted after they have been shut down via this method.</p>
 *
 * @return a {@code Future} that will succeed once the server has finished unbinding from its port and, if the
 * server was managing its own event loop group, its event loop group has shut down
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Future<Void> shutdown() {
    final Future<Void> channelCloseFuture = this.allChannels.close();

    final Future<Void> disconnectFuture;

    if (this.shouldShutDownEventLoopGroup) {
        // Wait for the channel to close before we try to shut down the event loop group
        channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() {

            @Override
            public void operationComplete(final Future<Void> future) throws Exception {
                BaseHttp2Server.this.bootstrap.config().group().shutdownGracefully();
            }
        });

        // Since the termination future for the event loop group is a Future<?> instead of a Future<Void>,
        // we'll need to create our own promise and then notify it when the termination future completes.
        disconnectFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);

        this.bootstrap.config().group().terminationFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(final Future future) throws Exception {
                ((Promise<Void>) disconnectFuture).trySuccess(null);
            }
        });
    } else {
        // We're done once we've closed all the channels, so we can return the closure future directly.
        disconnectFuture = channelCloseFuture;
    }

    disconnectFuture.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(final Future<Void> future) throws Exception {
            if (BaseHttp2Server.this.sslContext instanceof ReferenceCounted) {
                if (BaseHttp2Server.this.hasReleasedSslContext.compareAndSet(false, true)) {
                    ((ReferenceCounted) BaseHttp2Server.this.sslContext).release();
                }
            }
        }
    });

    return disconnectFuture;
}

From source file:com.whizzosoftware.hobson.hub.websockets.WebSocketsPlugin.java

License:Open Source License

@Override
public void onStartup(PropertyContainer config) {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();

    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new WebSocketServerInitializer(clientChannels, getAccessManager()));

    b.bind(PORT).addListener(new GenericFutureListener<ChannelFuture>() {
        @Override/*from   w w  w  . ja v a  2 s .  c om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            WebSocketsPlugin.this.channel = future.channel();
            logger.debug("WebSocket server started at port {}", PORT);
            getHubManager().getLocalManager().setWebSocketInfo("ws", PORT, null);
        }
    });
}

From source file:com.whizzosoftware.hobson.mysensors.MySensorsPlugin.java

License:Open Source License

@Override
public void onNodePresentation(int nodeId, int childSensorId, PresentationType type, String payload) {
    logger.debug("Received node presentation: {};{};{};{}", nodeId, childSensorId, type, payload);

    removeAssignableNodeId(nodeId);//from  ww w  .j  a  va  2s  . com

    if (nodeId > 0) {
        if (childSensorId < 255) {
            final String id = Integer.toString(nodeId) + NODE_ID_SEPERATOR + Integer.toString(childSensorId);
            if (!hasDeviceProxy(id)) {
                logger.debug("Detected new device: {} ({})", id, payload);
                MySensorsNodeInfo info = nodeInfoMap.get(nodeId);
                publishDeviceProxy(new MySensorsSensor(this, id,
                        payload != null ? payload : SensorNames.getDefaultName(type),
                        info != null ? info.getFirmwareVersion() : null))
                                .addListener(new GenericFutureListener() {
                                    @Override
                                    public void operationComplete(Future future) throws Exception {
                                        getDeviceProxy(id).setLastCheckin(System.currentTimeMillis());
                                    }
                                });
            }
        } else {
            setNodeInfo(nodeId, type, payload);
        }
    }
}

From source file:com.wuma.securechat.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {

                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }/*from w  ww .j  a v  a  2  s .c o  m*/
            });
}

From source file:com.xxx.netty.handle.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {// ?
    // System.out.println("channelactive!");

    // Once session is secured, send a greeting and register the channel to
    // the global channel
    // list so the channel received the messages from others.
    // ??//  w  w  w  .j av  a2 s  .co m
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("@Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    LOGGER.info("connected :{}" + ctx.channel().remoteAddress());
                }
            });

}

From source file:com.xx_dev.apn.socks.remote.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from   w ww  . j  a  va  2s  .  com
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));

    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.yahoo.pulsar.client.impl.ConsumerImpl.java

License:Apache License

private CompletableFuture<Void> sendAcknowledge(MessageId messageId, AckType ackType) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;
    final ByteBuf cmd = Commands.newAck(consumerId, msgId.getLedgerId(), msgId.getEntryId(), ackType, null);

    // There's no actual response from ack messages
    final CompletableFuture<Void> ackFuture = new CompletableFuture<Void>();

    if (isConnected()) {
        cnx().ctx().writeAndFlush(cmd).addListener(new GenericFutureListener<Future<Void>>() {
            @Override/* w  ww.  ja  va 2  s. co  m*/
            public void operationComplete(Future<Void> future) throws Exception {
                if (future.isSuccess()) {
                    if (ackType == AckType.Individual) {
                        unAckedMessageTracker.remove(msgId);
                        // increment counter by 1 for non-batch msg
                        if (!(messageId instanceof BatchMessageIdImpl)) {
                            stats.incrementNumAcksSent(1);
                        }
                    } else if (ackType == AckType.Cumulative) {
                        stats.incrementNumAcksSent(unAckedMessageTracker.removeMessagesTill(msgId));
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("[{}] [{}] [{}] Successfully acknowledged message - {}, acktype {}",
                                subscription, topic, consumerName, messageId, ackType);
                    }
                    ackFuture.complete(null);
                } else {
                    stats.incrementNumAcksFailed();
                    ackFuture.completeExceptionally(new PulsarClientException(future.cause()));
                }
            }
        });
    } else {
        stats.incrementNumAcksFailed();
        ackFuture.completeExceptionally(
                new PulsarClientException("Not connected to broker. State: " + state.get()));
    }

    return ackFuture;
}

From source file:com.zaradai.distributor.messaging.netty.handler.AbstractHandshakeHandler.java

License:Apache License

private Future<Channel> handshake(final ChannelHandlerContext handlerContext) {
    handshakePromise = new DefaultPromise<Channel>(handlerContext.executor());
    final ScheduledFuture<?> timeoutFuture;
    if (handshakeTimeout > 0) {
        timeoutFuture = handlerContext.executor().schedule(new Runnable() {
            @Override/*w ww  .java  2  s  . co m*/
            public void run() {
                if (handshakePromise.isDone()) {
                    return;
                }
                notifyHandshakeFailure(handlerContext, HANDSHAKE_TIMED_OUT);
            }
        }, handshakeTimeout, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    handshakePromise.addListener(new GenericFutureListener<Future<? super Channel>>() {
        @Override
        public void operationComplete(Future<? super Channel> future) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
        }
    });

    try {
        beginHandshake(handlerContext);
    } catch (Exception e) {
        notifyHandshakeFailure(handlerContext, e);
    }

    return handshakePromise;
}

From source file:connexion.ServerHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override//from   ww  w .  ja va 2 s.c  om
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("");

                    channels.add(ctx.channel());
                }
            });
}