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, String name, ChannelHandler handler);

Source Link

Document

Appends a ChannelHandler at the last position of this pipeline.

Usage

From source file:afred.javademo.proxy.rpc.ObjectEchoClient.java

License:Apache License

public void start(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from ww w  .  ja  v a2  s  .co m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
        });

        channel = b.connect(host, port).sync().channel();
    } finally {

    }
}

From source file:afred.javademo.proxy.rpc.ObjectEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  www.  j  ava2 s .c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(8080).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.avanza.astrix.netty.client.NettyRemotingClient.java

License:Apache License

public void connect(String host, int port) {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override//  w  w w  .  jav  a2 s. c o m
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                    nettyRemotingClientHandler);
        }
    });

    // Start the connection attempt.
    ChannelFuture channel = b.connect(host, port);
    try {
        if (channel.await(1, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    destroy();
    throw new IllegalArgumentException(
            String.format("Failed to connect to remoting server: %s:%d", host, port));
}

From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w  ww .ja v  a 2 s  .c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new NettyRemotingServerHandler(serviceActivator));
                }
            });

    // Bind and start to accept incoming connections. Binds to all interfaces
    // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port
    ChannelFuture channel = b.bind(port);
    try {
        if (channel.await(2, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort();
                log.info("NettyRemotingServer started listening on port={}", port);
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port);
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w  .  j a  va 2  s.c  o  m
 * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 */
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception {
    try {
        final String uri = msg.uri();
        final Channel channel = ctx.channel();
        if (uri.endsWith("/favicon.ico")) {
            final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, favicon);
            resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon");
            resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize);
            ctx.writeAndFlush(resp);
            return;
        } else if (uri.equals("/api/put") || uri.equals("/api/metadata")) {
            final ChannelPipeline p = ctx.pipeline();
            //            p.addLast(loggingHandler, jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            p.addLast(jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            //            if(msg instanceof FullHttpRequest) {
            //               ByteBuf b = ((FullHttpRequest)msg).content().copy();
            //               ctx.fireChannelRead(b);
            //            }
            ctx.fireChannelRead(msg);
            p.remove("requestManager");
            log.info("Switched to JSON Trace Processor");
            return;
        }
        final TSDBHttpRequest r = new TSDBHttpRequest(msg, ctx.channel(), ctx);
        final HttpRequestHandler handler = requestHandlers.get(r.getRoute());
        if (handler == null) {
            r.send404().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> f) throws Exception {
                    log.info("404 Not Found for {} Complete: success: {}", r.getRoute(), f.isSuccess());
                    if (!f.isSuccess()) {
                        log.error("Error sending 404", f.cause());
                    }
                };
            });
            return;
        }
        handler.process(r);
    } catch (Exception ex) {
        log.error("HttpRequest Routing Error", ex);
    }
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpSwitch.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final HttpRequest msg, final List<Object> out)
        throws Exception {
    final String uri = msg.uri();
    log.info("-----------------------> URI [{}]", uri);
    if (uri.endsWith("/favicon.ico")) {
        final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, favicon);
        resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon");
        resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize);
        ctx.writeAndFlush(resp);/*from www  .  java  2s .  c  o  m*/
        return;
    }
    ReferenceCountUtil.retain(msg);
    final ChannelPipeline p = ctx.pipeline();

    final int index = uri.indexOf("/api/");
    final String endpoint = index == -1 ? "" : uri.substring(5);
    if (index != -1 && pureJsonEndPoints.contains(endpoint)) {
        log.info("Switching to PureJSON handler");
        p.addLast(eventExecutorGroup, "httpToJson", httpToJson);
        //         p.addLast("jsonLogger", loggingHandler);
        p.addLast("jsonDecoder", new JsonObjectDecoder(true));
        //         p.addLast("jsonLogger", loggingHandler);
        p.addLast("traceHandler", traceHandler);
        p.remove(this);
        if (msg instanceof FullHttpMessage) {
            out.add(msg);
        }

    } else {
        log.info("Switching to Http Request Manager");
        out.add(msg);
        p.addLast(eventExecutorGroup, "requestManager", HttpRequestManager.getInstance());
        p.remove(this);
    }
}