Example usage for io.netty.handler.codec MessageToMessageEncoder MessageToMessageEncoder

List of usage examples for io.netty.handler.codec MessageToMessageEncoder MessageToMessageEncoder

Introduction

In this page you can find the example usage for io.netty.handler.codec MessageToMessageEncoder MessageToMessageEncoder.

Prototype

protected MessageToMessageEncoder() 

Source Link

Document

Create a new instance which will try to detect the types to match out of the type parameter of the class.

Usage

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        ChannelHandler handler) {/*from   ww  w  .j  a v  a  2s  . co m*/
    if (this.uri.getScheme().equals("wss")) {
        if (keyCertChainFile == null) {
            log.warn("No certificate provided for WSS endpoint - will use self-signed");
            try {
                SelfSignedCertificate certificate = new SelfSignedCertificate();
                keyCertChainFile = certificate.certificate();
                keyFile = certificate.privateKey();
                usingSelfSignedCertificate = true;
            } catch (CertificateException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            serverSslContext = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else if (!this.uri.getScheme().equals("ws")) {
        throw new IllegalArgumentException("Invalid scheme '" + uri.getScheme() + "' for web socket endpoint");
    }

    ServerBootstrap server = new ServerBootstrap();
    server.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (serverSslContext != null) {
                        pipeline.addLast(serverSslContext.newHandler(ch.alloc()));
                    }
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    //                        pipeline.addLast(new WebSocketServerCompressionHandler());
                    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/"));
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                                ChannelPipeline pipeline = ctx.channel().pipeline();
                                pipeline.addAfter("websocket", "ws-decoder-xx",
                                        new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                            @Override
                                            protected void decode(ChannelHandlerContext ctx,
                                                    BinaryWebSocketFrame msg, List<Object> out)
                                                    throws Exception {
                                                out.add(msg.content().retain());
                                            }
                                        });

                                pipeline.addAfter("websocket", "ws-encoder-xx",
                                        new MessageToMessageEncoder<ByteBuf>() {
                                            @Override
                                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg,
                                                    List<Object> out) throws Exception {
                                                out.add(new BinaryWebSocketFrame(msg).retain());
                                            }
                                        });
                            }

                            super.userEventTriggered(ctx, evt);
                        }
                    });

                    pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
                    pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
                    pipeline.addLast(handler);
                }
            });

    server.bind(uri.getPort());
    return server;
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;//from  w ww.j  a  v  a 2  s  .  c o  m
    if (this.uri.getScheme().equals("wss")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1 << 30));
            pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker));
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                        ChannelPipeline pipeline = ctx.channel().pipeline();
                        pipeline.addAfter("websocket", "ws-decoder-xx",
                                new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg,
                                            List<Object> out) throws Exception {
                                        out.add(msg.content().retain());
                                    }
                                });

                        pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                                    throws Exception {
                                out.add(new BinaryWebSocketFrame(msg).retain());
                            }
                        });
                    }

                    super.userEventTriggered(ctx, evt);
                }
            });

            pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
            pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}

From source file:reactor.ipc.netty.NettyOutboundTest.java

License:Open Source License

@Test
public void sendFileWithoutTlsUsesFileRegion() throws URISyntaxException, IOException {
    List<Class<?>> messageClasses = new ArrayList<>(2);

    EmbeddedChannel channel = new EmbeddedChannel(new MessageToMessageEncoder<FileRegion>() {

        @Override//from w  ww .  j  a  va 2  s. co  m
        protected void encode(ChannelHandlerContext ctx, FileRegion msg, List<Object> out) throws Exception {
            ByteArrayOutputStream bais = new ByteArrayOutputStream();
            WritableByteChannel wbc = Channels.newChannel(bais);

            msg.transferTo(wbc, msg.position());
            out.add(new String(bais.toByteArray()));
        }
    }, new MessageToMessageEncoder<Object>() {
        @Override
        protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            messageClasses.add(msg.getClass());
            ReferenceCountUtil.retain(msg);
            out.add(msg);
        }
    });
    NettyContext mockContext = () -> channel;
    NettyOutbound outbound = new NettyOutbound() {
        @Override
        public NettyContext context() {
            return mockContext;
        }

        @Override
        public FileChunkedStrategy getFileChunkedStrategy() {
            return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE;
        }
    };
    channel.writeOneOutbound(1);

    outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then().block();

    assertThat(channel.inboundMessages()).isEmpty();
    assertThat(channel.outboundMessages()).hasSize(2);
    assertThat(messageClasses).containsExactly(Integer.class, DefaultFileRegion.class);

    assertThat(channel.outboundMessages()).element(1).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("GARBAGE\nEnd of File");
}

From source file:reactor.ipc.netty.NettyOutboundTest.java

License:Open Source License

@Test
public void sendFileWithTlsUsesChunkedFile()
        throws URISyntaxException, NoSuchAlgorithmException, SSLException, CertificateException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    final SslHandler sslHandler = sslCtx.newHandler(ByteBufAllocator.DEFAULT);

    List<Class<?>> messageWritten = new ArrayList<>(2);
    List<Object> clearMessages = new ArrayList<>(2);

    EmbeddedChannel channel = new EmbeddedChannel(
            //outbound: pipeline reads inverted
            //bytes are encrypted
            sslHandler,/*from   ww  w  .ja v  a 2  s.c  o m*/
            //capture the chunks unencrypted, transform as Strings:
            new MessageToMessageEncoder<ByteBuf>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                        throws Exception {
                    clearMessages.add(msg.toString(CharsetUtil.UTF_8));
                    out.add(msg.retain()); //the encoder will release the buffer, make sure it is retained for SslHandler
                }
            },
            //transform the ChunkedFile into ByteBuf chunks:
            new ChunkedWriteHandler(),
            //helps to ensure a ChunkedFile was written outs
            new MessageToMessageEncoder<Object>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
                        throws Exception {
                    messageWritten.add(msg.getClass());
                    //passing the ChunkedFile through this method releases it, which is undesired
                    ReferenceCountUtil.retain(msg);
                    out.add(msg);
                }
            });

    NettyContext mockContext = () -> channel;
    NettyOutbound outbound = new NettyOutbound() {
        @Override
        public NettyContext context() {
            return mockContext;
        }

        @Override
        public FileChunkedStrategy getFileChunkedStrategy() {
            return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE;
        }
    };
    channel.writeOneOutbound(1);

    try {
        outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then()
                .block(Duration.ofSeconds(1)); //TODO investigate why this hangs
    } catch (IllegalStateException e) {
        if (!"Timeout on blocking read for 1000 MILLISECONDS".equals(e.getMessage()))
            throw e;
        System.err.println(e);
    }

    assertThat(messageWritten).containsExactly(Integer.class, ChunkedFile.class);

    assertThat(clearMessages).hasSize(2).element(0).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("1024 mark here ->");
    assertThat(clearMessages).element(1).asString().startsWith("<- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.NettyOutboundTest.java

License:Open Source License

@Test
public void sendFileWithForceChunkedFileUsesStrategyChunks()
        throws URISyntaxException, NoSuchAlgorithmException, IOException {
    List<Class<?>> messageWritten = new ArrayList<>(2);
    EmbeddedChannel channel = new EmbeddedChannel(
            //outbound: pipeline reads inverted
            //transform the ByteBuf chunks into Strings:
            new MessageToMessageEncoder<ByteBuf>() {
                @Override//  w w  w.ja  v a2  s  .c  o  m
                protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                        throws Exception {
                    out.add(msg.toString(CharsetUtil.UTF_8));
                }
            },
            //transform the ChunkedFile into ByteBuf chunks:
            new ChunkedWriteHandler(),
            //helps to ensure a ChunkedFile was written outs
            new MessageToMessageEncoder<Object>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
                        throws Exception {
                    messageWritten.add(msg.getClass());
                    out.add(msg);
                }
            });
    NettyContext mockContext = () -> channel;
    NettyOutbound outbound = new NettyOutbound() {
        @Override
        public NettyContext context() {
            return mockContext;
        }

        @Override
        public FileChunkedStrategy getFileChunkedStrategy() {
            return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE;
        }
    };
    Path path = Paths.get(getClass().getResource("/largeFile.txt").getFile());

    channel.writeOneOutbound(1);
    outbound.sendFileChunked(path, 0, Files.size(path)).then().block();

    assertThat(channel.inboundMessages()).isEmpty();
    assertThat(messageWritten).containsExactly(Integer.class, ChunkedFile.class);

    assertThat(channel.outboundMessages()).hasSize(3).element(1).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("1024 mark here ->");

    assertThat(channel.outboundMessages()).last().asString().startsWith("<- 1024 mark here")
            .endsWith("End of File");
}