Example usage for io.netty.channel ChannelPipeline addLast

List of usage examples for io.netty.channel ChannelPipeline addLast

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline addLast.

Prototype

ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);

Source Link

Document

Inserts ChannelHandler s at the last position of this pipeline.

Usage

From source file:com.qq.servlet.demo.netty.sample.socksproxy.SocksServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline channelPipeline = socketChannel.pipeline();
    channelPipeline.addLast(SocksInitRequestDecoder.getName(), new SocksInitRequestDecoder());
    channelPipeline.addLast(SocksMessageEncoder.getName(), socksMessageEncoder);
    channelPipeline.addLast(SocksServerHandler.getName(), socksServerHandler);
}

From source file:com.qq.servlet.demo.netty.sample.telnet.TelnetClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add the text line codec combination first,
    //        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

    pipeline.addLast("decoder", DECODER);
    pipeline.addLast("encoder", ENCODER);

    // and then business logic.
    pipeline.addLast("handler", CLIENTHANDLER);
}

From source file:com.qq.servlet.demo.netty.sample.telnet.TelnetServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add the text line codec combination first,
    //        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    // the encoder and decoder are static as these are sharable
    pipeline.addLast("decoder", DECODER);
    pipeline.addLast("encoder", ENCODER);

    // and then business logic.
    pipeline.addLast("handler", SERVERHANDLER);
}

From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast("encoder", new NTMessageToByteEncoder());
    pipeline.addLast("decoder", new NTByteToMessageDecoder());

    // and then business logic.
    pipeline.addLast("handler", new NettyThriftClientHandler());
}

From source file:com.qualys.jserf.SerfClientInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();

    if (log.isDebugEnabled()) {
        pipeline.addFirst("loggingHandler", new LoggingHandler());
    }//from w w  w.  j  a v  a 2  s .  c om

    pipeline.addLast("reconnectHandler", new ReconnectClientHandler(channelManger));

    log.debug("Adding ByteArray Encoder");
    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());

    log.debug("Adding SerfClientHandler");
    pipeline.addLast("handler", new SerfClientHandler(extractorManager, messagePack, callBacksBySequence));
}

From source file:com.quavo.osrs.network.NetworkExecutor.java

License:Open Source License

/**
 * Starts the network for a {@link Server}.
 * /*from   ww w  . j a  va 2  s. com*/
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(boss, worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("decoder", new ConnectionDecoder());
            pipeline.addLast("encoder", new ConnectionEncoder());
            pipeline.addLast("adapter", new NetworkMessageHandler());
        }

    });
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

    try {
        bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address "
            + Constants.HOST_NAME + ".");
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpMetricsIngestionServer.java

License:Apache License

private void setupPipeline(SocketChannel channel, RouteMatcher router) {
    final ChannelPipeline pipeline = channel.pipeline();

    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder() {

        // if something bad happens during the decode, assume the client send bad data. return a 400.
        @Override//from www  . j  a  v a 2s. com
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable thr) throws Exception {
            try {
                if (ctx.channel().isWritable()) {
                    log.debug("request decoder error " + thr.getCause().toString() + " on channel "
                            + ctx.channel().toString());
                    ctx.channel().write(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))
                            .addListener(ChannelFutureListener.CLOSE);
                } else {
                    log.debug("channel " + ctx.channel().toString()
                            + " is no longer writeable, not sending 400 response back to client");
                }
            } catch (Exception ex) {
                // If we are getting exception trying to write,
                // don't propagate to caller. It may cause this
                // method to be called again and will produce
                // stack overflow. So just log it here.
                log.debug("Can't write to channel " + ctx.channel().toString(), ex);
            }
        }
    });
    pipeline.addLast("inflater", new HttpContentDecompressor());
    pipeline.addLast("chunkaggregator", new HttpObjectAggregator(httpMaxContentLength));
    pipeline.addLast("respdecoder", new HttpResponseDecoder());
    pipeline.addLast("handler", new QueryStringDecoderAndRouter(router));
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMetricDataQueryServer.java

License:Apache License

private void setupPipeline(SocketChannel channel, RouteMatcher router) {
    final ChannelPipeline pipeline = channel.pipeline();

    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder() {
        @Override/* ww  w  . ja  v  a 2 s . c om*/
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable thr) throws Exception {
            try {
                if (ctx.channel().isWritable()) {
                    log.debug("request decoder error " + thr.getCause().toString() + " on channel "
                            + ctx.channel().toString());
                    ctx.channel().write(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))
                            .addListener(ChannelFutureListener.CLOSE);
                } else {
                    log.debug("channel " + ctx.channel().toString()
                            + " is no longer writeable, not sending 400 response back to client");
                }
            } catch (Exception ex) {
                // If we are getting exception trying to write,
                // don't propagate to caller. It may cause this
                // method to be called again and will produce
                // stack overflow. So just log it here.
                log.debug("Can't write to channel " + ctx.channel().toString(), ex);
            }
        }
    });
    pipeline.addLast("chunkaggregator", new HttpObjectAggregator(httpMaxContentLength));
    pipeline.addLast("handler", new QueryStringDecoderAndRouter(router));
}

From source file:com.relayrides.pushy.apns.ApnsClientThread.java

License:Open Source License

/**
 * Constructs a new APNs client thread. The thread connects to the APNs gateway in the given {@code PushManager}'s
 * environment and reads notifications from the {@code PushManager}'s queue.
 * /*from w w w .  j av a 2 s  .  c o  m*/
 * @param pushManager the {@code PushManager} from which this client thread should read environment settings and
 * notifications
 */
public ApnsClientThread(final PushManager<T> pushManager) {
    super(String.format("ApnsClientThread-%d", ApnsClientThread.threadCounter.incrementAndGet()));

    this.pushManager = pushManager;

    this.sentNotificationBuffer = new SentNotificationBuffer<T>(SENT_NOTIFICATION_BUFFER_SIZE);

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(this.pushManager.getWorkerGroup());
    this.bootstrap.channel(NioSocketChannel.class);
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

    final ApnsClientThread<T> clientThread = this;
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            if (pushManager.getEnvironment().isTlsRequired()) {
                pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(),
                        pushManager.getKeyStorePassword()));
            }

            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsErrorHandler(clientThread));
        }
    });
}

From source file:com.relayrides.pushy.apns.ApnsConnection.java

License:Open Source License

/**
 * Asynchronously connects to the APNs gateway in this connection's environment. The outcome of the connection
 * attempt is reported via this connection's listener.
 *
 * @see ApnsConnectionListener#handleConnectionSuccess(ApnsConnection)
 * @see ApnsConnectionListener#handleConnectionFailure(ApnsConnection, Throwable)
 *//*from w  w w  .  jav a2s.  co m*/
@SuppressWarnings("deprecation")
public synchronized void connect() {

    final ApnsConnection<T> apnsConnection = this;

    if (this.connectFuture != null) {
        throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name));
    }

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // TODO Remove this when Netty 5 is available
    bootstrap.option(ChannelOption.AUTO_CLOSE, false);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = apnsConnection.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsConnectionHandler(apnsConnection));
        }
    });

    log.debug("{} beginning connection process.", apnsConnection.name);
    this.connectFuture = bootstrap.connect(this.environment.getApnsGatewayHost(),
            this.environment.getApnsGatewayPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(final ChannelFuture connectFuture) {
            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", apnsConnection.name);

                final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

                try {
                    sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

                        public void operationComplete(final Future<Channel> handshakeFuture) {
                            if (handshakeFuture.isSuccess()) {
                                log.debug("{} successfully completed TLS handshake.", apnsConnection.name);

                                apnsConnection.handshakeCompleted = true;
                                apnsConnection.listener.handleConnectionSuccess(apnsConnection);
                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs gateway.",
                                        apnsConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();
                                apnsConnection.listener.handleConnectionFailure(apnsConnection,
                                        handshakeFuture.cause());
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            apnsConnection.name);

                    connectFuture.channel().close();
                    apnsConnection.listener.handleConnectionFailure(apnsConnection, e);
                }
            } else {
                log.debug("{} failed to connect to APNs gateway.", apnsConnection.name, connectFuture.cause());

                apnsConnection.listener.handleConnectionFailure(apnsConnection, connectFuture.cause());
            }
        }
    });
}