Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

List of usage examples for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

Introduction

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

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

From source file:com.kixeye.kixmpp.p2p.node.NodeServerTest.java

License:Apache License

@Test
public void clientSendAndServerReceiveTest() throws InterruptedException {
    final MessageRegistry messageRegistry = new MessageRegistry();
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    final BlockingQueue<Object> serverMessages = new LinkedBlockingQueue<>();
    final NodeAddress address = new NodeAddress("a", 8001);

    NodeServer server = new NodeServer();
    server.initialize("127.0.0.1", 8042, bossGroup, workerGroup, messageRegistry,
            new ChannelInboundHandlerAdapter() {
                @Override/*  w  w w.  j a  va  2 s.  com*/
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    serverMessages.offer(msg);
                }
            });

    NodeClient client = new NodeClient();
    client.initialize("127.0.0.1", 8042, workerGroup, messageRegistry, new ChannelInboundHandlerAdapter());
    client.send(new JoinRequest(new NodeId(42), address));
    client.send(new JoinResponse(JoinResponse.ResponseCode.OK, new NodeId(42), address));

    Object msg = serverMessages.poll(5, TimeUnit.SECONDS);
    Assert.assertNotNull(msg);
    Assert.assertEquals(msg.getClass(), JoinRequest.class);
    Assert.assertEquals(((JoinRequest) msg).getJoinerId(), new NodeId(42));
    Assert.assertEquals(((JoinRequest) msg).getJoinerAddress(), address);

    msg = serverMessages.poll(5, TimeUnit.SECONDS);
    Assert.assertNotNull(msg);
    Assert.assertEquals(msg.getClass(), JoinResponse.class);
    Assert.assertEquals(((JoinResponse) msg).getResult(), JoinResponse.ResponseCode.OK);

    client.shutdown();
    server.shutdown();
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
}

From source file:com.lambdaworks.redis.ProtectedModeTests.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {

    server = new MockTcpServer();

    server.addHandler(() -> {//from  w  w  w.  ja v a  2s . com
        return new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {

                String message = getMessage();
                ByteBuf buffer = ctx.alloc().buffer(message.length() + 3);
                buffer.writeBytes("-".getBytes());
                buffer.writeBytes(message.getBytes());
                buffer.writeByte('\r').writeByte('\n');

                ctx.writeAndFlush(buffer).addListener(future -> {
                    ctx.close();
                });
            }
        };
    });

    server.initialize(TestSettings.nonexistentPort());

    client = RedisClient.create(TestClientResources.get(),
            RedisURI.create(TestSettings.host(), TestSettings.nonexistentPort()));
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

/**
 * @see <a href="https://http2.github.io/http2-spec/#discover-https">HTTP/2 specification</a>
 *//*w  ww .j  a  v  a 2s  . c  o  m*/
private void configureAsHttps(Channel ch) {
    final ChannelPipeline p = ch.pipeline();
    final SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
    p.addLast(sslHandler);
    p.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!(evt instanceof SslHandshakeCompletionEvent)) {
                ctx.fireUserEventTriggered(evt);
                return;
            }

            final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
            if (!handshakeEvent.isSuccess()) {
                // The connection will be closed automatically by SslHandler.
                return;
            }

            final SessionProtocol protocol;
            if (isHttp2Protocol(sslHandler)) {
                if (httpPreference == HttpPreference.HTTP1_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H1, H2, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp2ConnectionHandler(ch));
                protocol = H2;
            } else {
                if (httpPreference != HttpPreference.HTTP1_REQUIRED) {
                    SessionProtocolNegotiationCache.setUnsupported(ctx.channel().remoteAddress(), H2);
                }

                if (httpPreference == HttpPreference.HTTP2_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H2, H1, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp1Codec());
                protocol = H1;
            }
            finishSuccessfully(p, protocol);
            p.remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Exceptions.logIfUnexpected(logger, ctx.channel(), cause);
            ctx.close();
        }
    });
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*  w  ww  . j a  va  2  s.com*/
        break;
    case HTTP2_PREFERRED:
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (options.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            Http1ClientCodec http1Codec = newHttp1Codec();
            Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec());

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

/**
 * See <a href="https://http2.github.io/http2-spec/#discover-https">HTTP/2 specification</a>.
 *//*w  w w. j  a va2 s .  c  o  m*/
private void configureAsHttps(Channel ch, InetSocketAddress remoteAddr) {
    assert sslCtx != null;

    final ChannelPipeline p = ch.pipeline();
    final SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), remoteAddr.getHostString(),
            remoteAddr.getPort());
    p.addLast(sslHandler);
    p.addLast(TrafficLoggingHandler.CLIENT);
    p.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!(evt instanceof SslHandshakeCompletionEvent)) {
                ctx.fireUserEventTriggered(evt);
                return;
            }

            final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
            if (!handshakeEvent.isSuccess()) {
                // The connection will be closed automatically by SslHandler.
                return;
            }

            final SessionProtocol protocol;
            if (isHttp2Protocol(sslHandler)) {
                if (httpPreference == HttpPreference.HTTP1_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H1, H2, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp2ConnectionHandler(ch));
                protocol = H2;
            } else {
                if (httpPreference != HttpPreference.HTTP1_REQUIRED) {
                    SessionProtocolNegotiationCache.setUnsupported(ctx.channel().remoteAddress(), H2);
                }

                if (httpPreference == HttpPreference.HTTP2_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H2, H1, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(p, newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                        clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize()));
                protocol = H1;
            }
            finishSuccessfully(p, protocol);
            p.remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Exceptions.logIfUnexpected(logger, ctx.channel(), cause);
            ctx.close();
        }
    });
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(TrafficLoggingHandler.CLIENT);

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*from  ww w  .  j  a v a 2  s .c  o  m*/
        break;
    case HTTP2_PREFERRED:
        assert remoteAddress != null;
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (clientFactory.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            final Http1ClientCodec http1Codec = newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                    clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize());
            final Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            final HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize()));

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.HttpConfigurator.java

License:Apache License

private void configureAsHttps(Channel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
    pipeline.addLast(sslHandler);/*from  w w w . ja  va 2 s .  co m*/
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!(evt instanceof SslHandshakeCompletionEvent)) {
                ctx.fireUserEventTriggered(evt);
                return;
            }

            final SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
            if (!handshakeEvent.isSuccess()) {
                // The connection will be closed automatically by SslHandler.
                return;
            }

            final SessionProtocol protocol;
            if (isHttp2Protocol(sslHandler)) {
                if (httpPreference == HttpPreference.HTTP1_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H1, H2, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(pipeline, newHttp2ConnectionHandler(ch));
                protocol = H2;
            } else {
                if (httpPreference != HttpPreference.HTTP1_REQUIRED) {
                    SessionProtocolNegotiationCache.setUnsupported(ctx.channel().remoteAddress(), H2);
                }

                if (httpPreference == HttpPreference.HTTP2_REQUIRED) {
                    finishWithNegotiationFailure(ctx, H2, H1, "unexpected protocol negotiation result");
                    return;
                }

                addBeforeSessionHandler(pipeline, newHttp1Codec());
                protocol = H1;
            }
            finishSuccessfully(pipeline, protocol);
            pipeline.remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Exceptions.logIfUnexpected(logger, ctx.channel(), null, cause);
            ctx.close();
        }
    });
}

From source file:com.linecorp.armeria.client.HttpConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*from   ww w .  j  a v a2  s  .c om*/
        break;
    case HTTP2_PREFERRED:
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        if (options.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(newHttp2ConnectionHandler(ch));
        } else {
            Http1ClientCodec http1Codec = newHttp1Codec();
            Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(
                    newHttp2ConnectionHandler(ch));
            HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, options.maxFrameLength());

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler());
        }
    } else {
        pipeline.addLast(newHttp1Codec());

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override//from w ww. j  a va  2  s . c o m
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:com.spotify.ffwd.http.HttpProtocolServer.java

License:Apache License

@Override
public final ChannelInitializer<Channel> initializer() {
    return new ChannelInitializer<Channel>() {
        @Override/*from   w  w w. j av a  2  s  .c  om*/
        protected void initChannel(Channel ch) throws Exception {
            final ChannelInboundHandlerAdapter exceptionHandler = new ChannelInboundHandlerAdapter() {
                @Override
                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause)
                        throws Exception {
                    if (cause instanceof HttpException) {
                        final HttpException e = (HttpException) cause;
                        sendResponse(ctx, e.getStatus());
                        return;
                    }

                    if (cause instanceof DecoderException) {
                        exceptionCaught(ctx, cause.getCause());
                        return;
                    }

                    log.error("error in pipeline: ", cause);
                    sendResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                }
            };
            ch.pipeline().addLast(new HttpRequestDecoder(), new HttpContentDecompressor(),
                    new HttpObjectAggregator(Integer.MAX_VALUE), decoder, exceptionHandler, handler);
            ch.pipeline().addLast(new HttpResponseEncoder());
        }
    };
}