Example usage for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler

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

Introduction

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

Prototype

protected SimpleChannelInboundHandler() 

Source Link

Document

see #SimpleChannelInboundHandler(boolean) with true as boolean parameter.

Usage

From source file:org.springframework.cloud.stream.app.netty.tcp.source.NettyTcpReceivingChannelAdapter.java

License:Apache License

@Override
protected void onInit() {
    super.onInit();

    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override//w  w  w  . java2  s .  co m
        protected void initChannel(final SocketChannel socketChannel) throws Exception {
            final ChannelPipeline channelPipeline = socketChannel.pipeline();

            boolean first = true;
            ChannelInboundHandler[] channelInboundHandlers = channelInboundHandlerFactory
                    .createChannelInboundHandlers();
            for (ChannelInboundHandler channelInboundHandler : channelInboundHandlers) {
                if (first) {
                    channelPipeline.addFirst(channelInboundHandler);
                    first = false;
                } else {
                    channelPipeline.addLast(channelInboundHandler);
                }
            }

            channelPipeline.addLast("sourceOutputHandler", new SimpleChannelInboundHandler<ByteBuf>() {
                @Override
                protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                    byte[] data;
                    if (msg.hasArray()) {
                        data = msg.array();
                    } else {
                        data = new byte[msg.readableBytes()];
                        msg.readBytes(data);
                    }
                    AbstractIntegrationMessageBuilder<byte[]> builder = getMessageBuilderFactory()
                            .withPayload(data);
                    sendMessage(builder.build());
                }
            });
            socketChannel.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    socketChannel.close();
                }
            });
        }
    });
    serverBootstrap.validate();
}

From source file:org.wildfly.camel.test.lumberjack.LumberjackComponentTest.java

License:Apache License

private List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters)
        throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {/*from   ww  w  .  j  av  a2s .  c o m*/
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();

        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }

                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        Assert.assertEquals(msg.readUnsignedByte(), (short) '2');
                        Assert.assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };

        // Connect to the server
        Channel channel = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(initializer).connect("127.0.0.1", port).sync().channel();

        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window15"));
        TimeUnit.MILLISECONDS.sleep(100);

        channel.close();

        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}

From source file:org.wso2.custom.inbound.InboundHttp2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a clear text upgrade from HTTP to HTTP/2.0
 *//*from  w w  w.jav a  2s.c  o m*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            log.info("No upgrade done: continue with " + msg.protocolVersion());
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new InboundHttpSourceHandler(config));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(msg);
        }
    });
    p.addLast(new UserEventLogger());
}

From source file:org.wso2.esb.integration.common.utils.servers.http2.Http2ServerInitializer.java

License:Open Source License

private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);//from w w w .j  av  a2  s  .com
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new Http1Handler("Direct. No Upgrade Attempted."));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(msg);
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:ws.wamp.jawampa.transport.netty.NettyWampClientConnectorProvider.java

License:Apache License

@Override
public IWampConnector createConnector(final URI uri, IWampClientConnectionConfig configuration,
        List<WampSerialization> serializations, final SocketAddress proxyAddress) throws Exception {

    String scheme = uri.getScheme();
    scheme = scheme != null ? scheme : "";

    // Check if the configuration is a netty configuration.
    // However null is an allowed value
    final NettyWampConnectionConfig nettyConfig;
    if (configuration instanceof NettyWampConnectionConfig) {
        nettyConfig = (NettyWampConnectionConfig) configuration;
    } else if (configuration != null) {
        throw new ApplicationError(ApplicationError.INVALID_CONNECTION_CONFIGURATION);
    } else {//ww  w. j a  v  a  2  s .  c om
        nettyConfig = null;
    }

    if (scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")) {

        // Check the host and port field for validity
        if (uri.getHost() == null || uri.getPort() == 0) {
            throw new ApplicationError(ApplicationError.INVALID_URI);
        }

        // Initialize SSL when required
        final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss");
        final SslContext sslCtx0;
        if (needSsl && (nettyConfig == null || nettyConfig.sslContext() == null)) {
            // Create a default SslContext when we got none provided through the constructor
            try {
                sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
            } catch (SSLException e) {
                throw e;
            }
        } else if (needSsl) {
            sslCtx0 = nettyConfig.sslContext();
        } else {
            sslCtx0 = null;
        }

        final String subProtocols = WampSerialization.makeWebsocketSubprotocolList(serializations);

        final int maxFramePayloadLength = (nettyConfig == null)
                ? NettyWampConnectionConfig.DEFAULT_MAX_FRAME_PAYLOAD_LENGTH
                : nettyConfig.getMaxFramePayloadLength();

        // Return a factory that creates a channel for websocket connections
        return new IWampConnector() {
            @Override
            public IPendingWampConnection connect(final ScheduledExecutorService scheduler,
                    final IPendingWampConnectionListener connectListener,
                    final IWampConnectionListener connectionListener) {

                // Use well-known ports if not explicitly specified
                final int port;
                if (uri.getPort() == -1) {
                    if (needSsl)
                        port = 443;
                    else
                        port = 80;
                } else
                    port = uri.getPort();

                final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                        WebSocketVersion.V13, subProtocols, false, new DefaultHttpHeaders(),
                        maxFramePayloadLength);

                /**
                 * Netty handler for that receives and processes WampMessages and state
                 * events from the pipeline.
                 * A new instance of this is created for each connection attempt.
                 */
                final ChannelHandler connectionHandler = new SimpleChannelInboundHandler<WampMessage>() {
                    boolean connectionWasEstablished = false;
                    /** Guard to prevent forwarding events aftert the channel was closed */
                    boolean wasClosed = false;

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        if (wasClosed)
                            return;
                        wasClosed = true;
                        if (connectionWasEstablished) {
                            connectionListener.transportClosed();
                        } else {
                            // The transport closed before the websocket handshake was completed
                            connectListener
                                    .connectFailed(new ApplicationError(ApplicationError.TRANSPORT_CLOSED));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        if (wasClosed)
                            return;
                        wasClosed = true;
                        if (connectionWasEstablished) {
                            connectionListener.transportError(cause);
                        } else {
                            // The transport closed before the websocket handshake was completed
                            connectListener.connectFailed(cause);
                        }
                        super.exceptionCaught(ctx, cause);
                    }

                    @Override
                    public void userEventTriggered(final ChannelHandlerContext ctx, Object evt)
                            throws Exception {
                        if (wasClosed)
                            return;
                        if (evt instanceof ConnectionEstablishedEvent) {
                            ConnectionEstablishedEvent ev = (ConnectionEstablishedEvent) evt;
                            final WampSerialization serialization = ev.serialization();

                            IWampConnection connection = new IWampConnection() {
                                @Override
                                public WampSerialization serialization() {
                                    return serialization;
                                }

                                @Override
                                public boolean isSingleWriteOnly() {
                                    return false;
                                }

                                @Override
                                public void sendMessage(WampMessage message,
                                        final IWampConnectionPromise<Void> promise) {
                                    ChannelFuture f = ctx.writeAndFlush(message);
                                    f.addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future) throws Exception {
                                            if (future.isSuccess() || future.isCancelled())
                                                promise.fulfill(null);
                                            else
                                                promise.reject(future.cause());
                                        }
                                    });
                                }

                                @Override
                                public void close(boolean sendRemaining,
                                        final IWampConnectionPromise<Void> promise) {
                                    // sendRemaining is ignored. Remaining data is always sent
                                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                            .addListener(new ChannelFutureListener() {
                                                @Override
                                                public void operationComplete(ChannelFuture future)
                                                        throws Exception {
                                                    future.channel().close()
                                                            .addListener(new ChannelFutureListener() {
                                                                @Override
                                                                public void operationComplete(
                                                                        ChannelFuture future) throws Exception {
                                                                    if (future.isSuccess()
                                                                            || future.isCancelled())
                                                                        promise.fulfill(null);
                                                                    else
                                                                        promise.reject(future.cause());
                                                                }
                                                            });
                                                }
                                            });
                                }
                            };

                            connectionWasEstablished = true;

                            // Connection to the remote host was established
                            // However the WAMP session is not established until the handshake was finished
                            connectListener.connectSucceeded(connection);
                        }
                    }

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
                        if (wasClosed)
                            return;
                        assert (connectionWasEstablished);
                        connectionListener.messageReceived(msg);
                    }
                };

                // If the assigned scheduler is a netty eventloop use this
                final EventLoopGroup nettyEventLoop;
                if (scheduler instanceof EventLoopGroup) {
                    nettyEventLoop = (EventLoopGroup) scheduler;
                } else {
                    connectListener.connectFailed(new ApplicationError(ApplicationError.INCOMATIBLE_SCHEDULER));
                    return IPendingWampConnection.Dummy;
                }

                Bootstrap b = new Bootstrap();

                // things should be resolved on via the socks5 proxy
                if (proxyAddress != null)
                    b.resolver(NoopAddressResolverGroup.INSTANCE);

                b.group(nettyEventLoop).channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) {
                                ChannelPipeline p = ch.pipeline();
                                if (proxyAddress != null) {
                                    p.addFirst("proxy", new Socks5ProxyHandler(proxyAddress));
                                }
                                if (sslCtx0 != null) {
                                    p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port));
                                }
                                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                                        new WebSocketClientProtocolHandler(handshaker, false),
                                        new WebSocketFrameAggregator(
                                                WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE),
                                        new WampClientWebsocketHandler(handshaker), connectionHandler);
                            }
                        });

                final ChannelFuture connectFuture = b.connect(uri.getHost(), port);
                connectFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            // Do nothing. The connection is only successful when the websocket handshake succeeds
                        } else {
                            // Remark: Might be called directly in addListener
                            // Therefore addListener should be the last call
                            // Remark2: This branch will be taken upon cancellation.
                            // This is required by the contract.
                            connectListener.connectFailed(future.cause());
                        }
                    }
                });

                // Return the connection in progress with the ability for cancellation
                return new IPendingWampConnection() {
                    @Override
                    public void cancelConnect() {
                        connectFuture.cancel(false);
                    }
                };
            }
        };
    }

    throw new ApplicationError(ApplicationError.INVALID_URI);
}

From source file:ws.wamp.jawampa.transport.netty.WampServerWebsocketHandler.java

License:Apache License

private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    String subProtocols = WampSerialization.makeWebsocketSubprotocolList(supportedSerializations);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation, subProtocols, false,
            WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);

    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {//from ww  w  .  j a v  a  2  s  .  c o  m
        handshakeInProgress = true;
        // The next statement will throw if the handshake gets wrong. This will lead to an
        // exception in the channel which will close the channel (which is OK).
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        serialization = WampSerialization.fromString(actualProtocol);

        // In case of unsupported websocket subprotocols we close the connection.
        // Won't help us when the client will ignore our protocol response and send
        // invalid packets anyway
        if (serialization == WampSerialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }

        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }

        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }

        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);

        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline()
                .addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));

        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer", new WampSerializationHandler(serialization));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer",
                new WampDeserializationHandler(serialization));

        // Retrieve a listener for this new connection
        final IWampConnectionListener connectionListener = connectionAcceptor.createNewConnectionListener();

        // Create a Wamp connection interface on top of that
        final WampServerConnection connection = new WampServerConnection(serialization);

        ChannelHandler routerHandler = new SimpleChannelInboundHandler<WampMessage>() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                // Gets called once the channel gets added to the pipeline
                connection.ctx = ctx;
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                connectionAcceptor.acceptNewConnection(connection, connectionListener);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                connectionListener.transportClosed();
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
                connectionListener.messageReceived(msg);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                ctx.close();
                connectionListener.transportError(cause);
            }
        };

        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast("wamp-router", routerHandler);

        handshakeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    // The handshake was not successful. 
                    // Close the channel without registering
                    ctx.fireExceptionCaught(future.cause()); // TODO: This is a race condition if the router did not yet accept the connection
                } else {
                    // We successfully sent out the handshake
                    // Notify the router of that fact
                    ctx.fireChannelActive();
                }
            }
        });

        // TODO: Maybe there are frames incoming before the handshakeFuture is resolved
        // This might lead to frames getting sent to the router before it is activated
    }
}