Example usage for io.netty.channel ChannelHandlerAdapter ChannelHandlerAdapter

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

Introduction

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

Prototype

ChannelHandlerAdapter

Source Link

Usage

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void uncaughtExceptionFailuresPropagated() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
            });/*from   ww  w . jav a  2s.com*/
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.connect(addr);
    chan.pipeline().fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.ABORTED);
        assertThat(status.getDescription()).contains("zap");
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void uncaughtException_closeAtMostOnce() throws Exception {
    final AtomicInteger closes = new AtomicInteger();
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelDuplexHandler() {
                @Override// www  . j a v a2 s . co  m
                public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                    closes.getAndIncrement();
                    // Simulates a loop between this handler and the WriteBufferingAndExceptionHandler.
                    ctx.fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());
                    super.close(ctx, promise);
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    chan.connect(addr).sync();
    chan.close().sync();
    assertEquals(1, closes.get());
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void handlerRemovedFailuresPropagated() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
                @Override/*from   w ww . ja va 2 s .c o  m*/
                public void handlerRemoved(ChannelHandlerContext ctx) {
                    ctx.pipeline()
                            .remove(ctx.pipeline().context(WriteBufferingAndExceptionHandler.class).name());
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    chan.connect(addr);
    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.pipeline().removeFirst();

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
        assertThat(status.getDescription()).contains("Buffer removed");
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void writesBuffered() throws Exception {
    final AtomicBoolean handlerAdded = new AtomicBoolean();
    final AtomicBoolean flush = new AtomicBoolean();
    final AtomicReference<Object> write = new AtomicReference<>();
    final WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelOutboundHandlerAdapter() {
                @Override/*from   ww w  .  ja  v a  2  s . c o  m*/
                public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                    assertFalse(handlerAdded.getAndSet(true));
                    super.handlerAdded(ctx);
                }

                @Override
                public void flush(ChannelHandlerContext ctx) throws Exception {
                    assertFalse(flush.getAndSet(true));
                    super.flush(ctx);
                }

                @Override
                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
                    assertNull(write.getAndSet(msg));
                    promise.setSuccess();
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    assertTrue(handlerAdded.get());

    chan.write(new Object());
    chan.connect(addr).sync();
    assertNull(write.get());

    chan.flush();
    assertNull(write.get());
    assertFalse(flush.get());

    assertThat(chan.pipeline().context(handler)).isNotNull();
    chan.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            handler.writeBufferedAndRemove(chan.pipeline().context(handler));
        }
    }).sync();

    assertThat(chan.pipeline().context(handler)).isNull();
    assertThat(write.get().getClass()).isSameInstanceAs(Object.class);
    assertTrue(flush.get());
    assertThat(chan.pipeline()).doesNotContain(handler);
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void uncaughtReadFails() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
            });//from  w  w w. j  a  v a 2 s  .  c  o m
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.connect(addr);
    chan.pipeline().fireChannelRead(Unpooled.copiedBuffer(new byte[] { 'a' }));

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
        assertThat(status.getDescription()).contains("channelRead() missed");
    }
}

From source file:mmo.server.RouteHandler.java

License:Open Source License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ctx.pipeline().addLast(dataToHttpEncoder);
    ctx.pipeline().addLast(PAGE_HANDLER_NAME, pageNotFoundHandler);
    ctx.pipeline().addLast(new ChannelHandlerAdapter() {
        @Override/*from www. j  ava 2s.c om*/
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            L.error("exception", cause);
        }
    });
    super.handlerAdded(ctx);
}

From source file:net.openbyte.server.CodeUpdateServer.java

License:MIT License

public void startTestClient() throws Exception {
    if (isTestClientRunning || !getNetworkManager().isRunning()) {
        return;//from  ww w  .  j  a  va  2s. c  o m
    }
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap clientBootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext context) throws Exception {
                            System.out.println(
                                    "Test client channel is active, sending validation packet to server!");
                            String name = "TEST_CLIENT";
                            String email = "client@example.org";
                            int clientId = -1; // test id

                            ByteBuf packet = new PacketBuilder().varInt(0x00).string(name).string(email)
                                    .varInt(clientId).build();

                            context.writeAndFlush(packet);
                        }

                        String authenticationId = null;

                        @Override
                        public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
                            ByteBuf read = (ByteBuf) msg;
                            int packetId = ByteBufDecoders.readVarInt(read);
                            System.out.println("Test client has received a packet (ID: " + packetId + ")");
                            if (packetId == 0x00) {
                                // okay packet
                                boolean validated = read.readBoolean();
                                if (!validated) {
                                    System.out.println(
                                            "Test client has not been given access to server. Stopping authentication process.");
                                    return;
                                }
                                authenticationId = ByteBufDecoders.readUTF8(read);
                                System.out.println("Test client has authenticated successfully! ("
                                        + authenticationId + ")");
                                System.out.println("Running server protocol tests...");
                                System.out.println("Running get clients packet protocol...");
                                ByteBuf packet = new PacketBuilder().varInt(0x03).string(authenticationId)
                                        .build();
                                System.out.println("Sending protocol packet (get clients)...");
                                context.writeAndFlush(packet);
                                System.out.println("Awaiting for packet response...");
                            }
                            if (packetId == 0x03) {
                                if (authPacketSent) {
                                    System.out.println("Authentication security failed!");
                                    System.exit(0);
                                }
                                // get client response
                                int clientsConnected = ByteBufDecoders.readVarInt(read);
                                String clients = ByteBufDecoders.readUTF8(read);

                                System.out.println(
                                        "Protocol packet (get clients) successfully executed with following results.");
                                System.out.println("Amount of clients connected: " + clientsConnected
                                        + ", clients connected:");
                                System.out.println(clients);

                                //System.out.println("Test client successfully executed tests.");
                                //System.exit(0);

                                System.out.println(
                                        "Running authentication security test (use fake authentication id)...");
                                ByteBuf packet = new PacketBuilder().varInt(0x03)
                                        .string(UUID.randomUUID().toString()).build();
                                context.writeAndFlush(packet);
                                System.out.println("Invalid authentication packet sent!");
                                authPacketSent = true;
                            }
                            if (packetId == 0x05) {
                                System.out.println("Security measures have been tested successfully!");
                                System.out.println("Tests are done, running disconnect protocol...");

                                ByteBuf packet = new PacketBuilder().varInt(0x08).string(authenticationId)
                                        .string("TEST_CLIENT").build();

                                context.writeAndFlush(packet);
                                System.out.println("Tests have completed. Conclusive results: SUCCESS");
                                System.exit(0);
                            }
                        }
                    });
                }
            });
    clientBootstrap.connect(InetAddress.getLocalHost(), 4000).sync();
    isTestClientRunning = true;
}

From source file:net.tridentsdk.server.window.TridentWindow.java

License:Apache License

@Volatile(policy = "DO NOT INVOKE OUTSIDE OF THIS CLASS", reason = "Extremely unsafe and causes unspecified behavior without proper handling", fix = "Do not use reflection on this method")
private void addClosedListener(Player player) {
    final PlayerConnection connection = ((TridentPlayer) player).getConnection();
    connection.getChannel().pipeline().addLast(new ChannelHandlerAdapter() {
        @Override/*from  w w w. ja va  2s  . c om*/
        // Occurs after the message should be decoded
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof PacketPlayInPlayerCloseWindow) {
                PacketPlayInPlayerCloseWindow windowClose = (PacketPlayInPlayerCloseWindow) msg;
                if (windowClose.getWindowId() == getId())
                    for (Player player1 : users)
                        if (connection.getChannel().equals(ctx.channel())) {
                            users.remove(player1);
                            ctx.pipeline().remove(this);
                        }
            }

            // Pass to the next channel handler
            super.channelRead(ctx, msg);
        }
    });
}

From source file:org.betawares.jorre.Client.java

License:Open Source License

/**
 * Connect to a {@link Server} using the specified {@link Connection} settings.  This call
 * will block until successful or an exception is thrown.
 * //  w ww. j ava2s  .c om
 * @param connection    a {@link Connection} instance specifying the connection settings
 * @return true if the connection was successful, false otherwise
 */
public boolean connect(Connection connection) {

    clientMessageHandler = new ClientMessageHandler(this, connection.getMaxResponseAge());
    group = new NioEventLoopGroup();
    try {
        if (connection.isSSL()) {
            sslCtx = SslContextBuilder.forClient().build();
        } else {
            sslCtx = null;
        }
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                if (sslCtx != null) {
                    ch.pipeline()
                            .addLast(sslCtx.newHandler(ch.alloc(), connection.getHost(), connection.getPort()));
                }
                ch.pipeline().addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null)));
                ch.pipeline().addLast(new ObjectEncoder());
                //                        ch.pipeline().addLast("messageInspector", new ClientMessageInspector());
                ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(),
                        connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS));
                ch.pipeline().addLast("heartbeatHandler", new ClientHeartbeatHandler(Client.this));
                ch.pipeline().addLast("pingMessageHandler", new PingMessageHandler());
                ch.pipeline().addLast("pongMessageHandler", new PongMessageHandler());

                ch.pipeline().addLast("clientMessageHandler", clientMessageHandler);

                ch.pipeline().addLast("exceptionHandler", new ChannelHandlerAdapter() {
                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        logger.error("Communications error", cause);
                        Client.this.disconnect(DisconnectReason.IOError, true);
                    }
                });
            }
        });

        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connection.getConnectionTimeout());
        ChannelFuture future = bootstrap.connect(connection.getHost(), connection.getPort());
        channel = future.sync().channel();
        return true;
    } catch (SSLException | InterruptedException ex) {
        logger.fatal("Error connecting", ex);
        disconnect(DisconnectReason.IOError, true);
    }
    return false;
}

From source file:reactor.ipc.netty.http.client.HttpClientOperationsTest.java

License:Open Source License

@Test
public void testConstructorWithProvidedReplacement() {
    EmbeddedChannel channel = new EmbeddedChannel();
    channel.pipeline().addFirst(NettyPipeline.SslHandler, new ChannelHandlerAdapter() {
    });// ww  w .j  a  va  2 s.co m

    HttpClientOperations ops1 = new HttpClientOperations(channel, (response, request) -> null, handler);
    ops1.followRedirect();
    ops1.failOnClientError(false);
    ops1.failOnServerError(false);

    HttpClientOperations ops2 = new HttpClientOperations(channel, ops1);

    assertSame(ops1.channel(), ops2.channel());
    assertSame(ops1.started, ops2.started);
    assertSame(ops1.redirectedFrom, ops2.redirectedFrom);
    assertSame(ops1.isSecure, ops2.isSecure);
    assertSame(ops1.nettyRequest, ops2.nettyRequest);
    assertSame(ops1.responseState, ops2.responseState);
    assertSame(ops1.redirectable, ops2.redirectable);
    assertSame(ops1.inboundPrefetch, ops2.inboundPrefetch);
    assertSame(ops1.requestHeaders, ops2.requestHeaders);
    assertSame(ops1.clientError, ops2.clientError);
    assertSame(ops1.serverError, ops2.serverError);
}