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

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

Introduction

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

Prototype

protected MessageToMessageDecoder() 

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:de.minigames.mclib.nms.v18.NetworkManager1_8.java

License:Open Source License

/**
 * Hook into network traffic and listen for resource pack status changes. Spigot 1.8 does not have the proper event to listen for this packet.
 * //from   w w w .ja v a  2 s .  com
 * @param player
 * @param consumer
 */
public static void hookResourcePackStatus(Player player, BiConsumer<Player, ResourcePackStatus> consumer) {
    final NetworkManager manager = ((CraftPlayer) player).getHandle().playerConnection.networkManager;
    Channel channel = null;
    try {
        channel = (Channel) channelField.get(manager);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        // TODO logging
        return;
    }

    final ChannelPipeline pipe = channel.pipeline();

    final ChannelHandler handler = new MessageToMessageDecoder<Packet>() {
        @Override
        protected void decode(ChannelHandlerContext chc, Packet packet, List<Object> out) throws Exception {
            if (packet instanceof PacketPlayInResourcePackStatus) {
                try {
                    final EnumResourcePackStatus status = (EnumResourcePackStatus) enumField.get(packet);
                    switch (status) {
                    case ACCEPTED:
                        consumer.accept(player, ResourcePackStatus.ACCEPTED);
                        break;
                    case DECLINED:
                        consumer.accept(player, ResourcePackStatus.DECLINED);
                        break;
                    case FAILED_DOWNLOAD:
                        consumer.accept(player, ResourcePackStatus.FAILED_DOWNLOAD);
                        break;
                    case SUCCESSFULLY_LOADED:
                        consumer.accept(player, ResourcePackStatus.SUCCESSFULLY_LOADED);
                        break;
                    default:
                        break;
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    // TODO logging
                }
            }
            out.add(packet);
        }
    };

    pipe.addAfter("decoder", //$NON-NLS-1$
            "mclib", //$NON-NLS-1$
            handler);
}

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

License:Apache License

@Override
public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        ChannelHandler handler) {//from  w ww  . j  av  a 2 s  .c o  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  w w  .j  a  v  a2s  .co 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:me.dominik.oneversusone.utils.NPC.java

License:Open Source License

public static void injectNetty(final Player player) {
    try {//ww  w  .j a v  a2s. c om
        Channel channel = (Channel) channelField
                .get(((CraftPlayer) player).getHandle().playerConnection.networkManager);
        if (channel != null) {
            channel.pipeline().addAfter("decoder", "npc_interact", new MessageToMessageDecoder<Packet>() {
                @Override
                protected void decode(ChannelHandlerContext chc, Packet packet, List<Object> out)
                        throws Exception {
                    if (packet instanceof PacketPlayInUseEntity) {
                        PacketPlayInUseEntity usePacket = (PacketPlayInUseEntity) packet;
                        if (usePacket.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT) {
                            int entityId = (int) idField.get(usePacket);
                            if (npcs.containsKey(entityId)) {
                                Bukkit.getPluginManager()
                                        .callEvent(new PlayerInteractNPCEvent(player, npcs.get(entityId)));
                            }
                        }
                    }
                    out.add(packet);
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.enderstone.server.packet.NetworkManager.java

License:Open Source License

public void setupEncryption(final SecretKey key) throws IOException {
    final Cipher decrypter = generateKey(2, key);
    final Cipher encrypter = generateKey(1, key);
    ctx.pipeline().addBefore("packet_rw_converter", "decrypt", new MessageToMessageDecoder<ByteBuf>() {

        NetworkEncrypter chipper = new NetworkEncrypter(decrypter);

        @Override/*from   w ww.j  ava  2s  .c  om*/
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                throws ShortBufferException {
            System.out.println("Decrypting " + in.readableBytes());
            this.chipper.decrypt(ctx, in);
        }

    });
    ctx.pipeline().addBefore("packet_rw_converter", "encrypt", new MessageToByteEncoder<ByteBuf>() {

        NetworkEncrypter chipper = new NetworkEncrypter(encrypter);

        @Override
        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
            System.out.println("Encrypting " + msg.readableBytes());
            this.chipper.encrypt(msg, out);
        }

    });
}

From source file:reactor.io.net.tcp.syslog.SyslogTcpServerTests.java

License:Open Source License

@Test
@Ignore/*from www .  j  a  v a 2s. c  o  m*/
public void testSyslogServer() throws InterruptedException, IOException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    Configuration conf = new Configuration();
    conf.addResource("/usr/local/Cellar/hadoop/1.1.2/libexec/conf/core-site.xml");
    final HdfsConsumer hdfs = new HdfsConsumer(conf, "loadtests", "syslog");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).localAddress(3000).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("framer",
                            new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("syslogDecoder", new MessageToMessageDecoder<String>() {
                        Function<Buffer, SyslogMessage> decoder = new SyslogCodec().decoder(null);

                        @Override
                        public void decode(ChannelHandlerContext ctx, String msg, List<Object> messages)
                                throws Exception {
                            messages.add(decoder.apply(Buffer.wrap(msg + "\n")));
                        }
                    });
                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            latch.countDown();
                            hdfs.accept((SyslogMessage) msg);
                        }
                    });
                }
            });

    // Bind and start to accept incoming connections.
    ChannelFuture channelFuture = b.bind().awaitUninterruptibly();

    for (int i = 0; i < threads; i++) {
        new SyslogMessageWriter(3000).start();
    }

    latch.await(60, TimeUnit.SECONDS);
    end.set(System.currentTimeMillis());

    assertThat("latch was counted down", latch.getCount(), is(0L));

    double elapsed = (end.get() - start.get()) * 1.0;
    System.out.println("elapsed: " + (int) elapsed + "ms");
    System.out.println("throughput: " + (int) ((msgs * threads) / (elapsed / 1000)) + "/sec");

    channelFuture.channel().close().awaitUninterruptibly();
}