Search in sources :

Example 1 with ChannelOutboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter in project MinecraftForge by MinecraftForge.

the class PacketLoggingHandler method register.

public static void register(NetworkManager manager) {
    ChannelPipeline pipeline = manager.channel().pipeline();
    final EnumPacketDirection direction = manager.getDirection();
    if (manager.isLocalChannel()) {
        pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<Packet<?>>() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, Packet<?> msg) throws Exception {
                PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
                msg.writePacketData(buf);
                FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
                ctx.fireChannelRead(msg);
            }
        });
        pipeline.addBefore("splitter", "prepender", new ChannelOutboundHandlerAdapter() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");

            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                if (msg instanceof Packet<?>) {
                    PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
                    ((Packet<?>) msg).writePacketData(buf);
                    FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
                }
                ctx.write(msg, promise);
            }
        });
    } else {
        pipeline.replace("splitter", "splitter", new NettyVarint21FrameDecoder() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");

            @Override
            protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception {
                super.decode(context, input, output);
                Iterator<Object> itr = output.iterator();
                while (itr.hasNext()) {
                    ByteBuf pkt = (ByteBuf) itr.next();
                    pkt.markReaderIndex();
                    FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(pkt));
                    pkt.resetReaderIndex();
                }
            }
        });
        pipeline.replace("prepender", "prepender", new NettyVarint21FrameEncoder() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");

            @Override
            protected void encode(ChannelHandlerContext context, ByteBuf input, ByteBuf output) throws Exception {
                input.markReaderIndex();
                FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(input));
                input.resetReaderIndex();
                super.encode(context, input, output);
            }
        });
    }
}
Also used : Packet(net.minecraft.network.Packet) NettyVarint21FrameDecoder(net.minecraft.network.NettyVarint21FrameDecoder) EnumPacketDirection(net.minecraft.network.EnumPacketDirection) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) ChannelPipeline(io.netty.channel.ChannelPipeline) Iterator(java.util.Iterator) NettyVarint21FrameEncoder(net.minecraft.network.NettyVarint21FrameEncoder) PacketBuffer(net.minecraft.network.PacketBuffer)

Example 2 with ChannelOutboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter in project netty by netty.

the class Http2MultiplexCodecTest method failedOutboundStreamCreationThrowsAndClosesChannel.

/**
     * Test failing the promise of the first headers frame of an outbound stream. In practice this error case would most
     * likely happen due to the max concurrent streams limit being hit or the channel running out of stream identifiers.
     */
@Test(expected = Http2NoMoreStreamIdsException.class)
public void failedOutboundStreamCreationThrowsAndClosesChannel() throws Exception {
    parentChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            promise.tryFailure(new Http2NoMoreStreamIdsException());
        }
    });
    LastInboundHandler inboundHandler = new LastInboundHandler();
    childChannelInitializer.handler = inboundHandler;
    Http2StreamChannelBootstrap b = new Http2StreamChannelBootstrap();
    Channel childChannel = b.parentChannel(parentChannel).handler(childChannelInitializer).connect().channel();
    assertTrue(childChannel.isActive());
    childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
    parentChannel.flush();
    assertFalse(childChannel.isActive());
    assertFalse(childChannel.isOpen());
    inboundHandler.checkException();
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) Test(org.junit.Test)

Example 3 with ChannelOutboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter in project riposte by Nike-Inc.

the class VerifyCornerCasesComponentTest method invalid_http_call_should_result_in_expected_400_error.

@Test
public void invalid_http_call_should_result_in_expected_400_error() throws Exception {
    // given
    // Normal request, but fiddle with the first chunk as it's going out to remove the HTTP version and make it an
    // invalid HTTP call.
    NettyHttpClientRequestBuilder request = request().withMethod(HttpMethod.GET).withUri(BasicEndpoint.MATCHING_PATH).withPipelineAdjuster(p -> p.addFirst(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            String msgAsString = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
            if (msgAsString.contains("HTTP/1.1")) {
                msg = Unpooled.copiedBuffer(msgAsString.replace("HTTP/1.1", ""), CharsetUtil.UTF_8);
            }
            super.write(ctx, msg, promise);
        }
    }));
    // when
    NettyHttpClientResponse response = request.execute(downstreamServerConfig.endpointsPort(), 3000);
    // then
    verifyErrorReceived(response.payload, response.statusCode, new ApiErrorWithMetadata(SampleCoreApiError.MALFORMED_REQUEST, Pair.of("cause", "Invalid HTTP request")));
}
Also used : ApiErrorWithMetadata(com.nike.backstopper.apierror.ApiErrorWithMetadata) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) NettyHttpClientResponse(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) NettyHttpClientRequestBuilder(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientRequestBuilder) Test(org.junit.Test)

Example 4 with ChannelOutboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter in project cassandra by apache.

the class EntireSSTableStreamConcurrentComponentMutationTest method createMockNettyChannel.

private EmbeddedChannel createMockNettyChannel(ByteBuf serializedFile) {
    WritableByteChannel wbc = new WritableByteChannel() {

        private boolean isOpen = true;

        public int write(ByteBuffer src) {
            int size = src.limit();
            serializedFile.writeBytes(src);
            return size;
        }

        public boolean isOpen() {
            return isOpen;
        }

        public void close() {
            isOpen = false;
        }
    };
    return new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof BufferPoolAllocator.Wrapped) {
                ByteBuffer buf = ((BufferPoolAllocator.Wrapped) msg).adopt();
                wbc.write(buf);
            } else {
                ((SharedDefaultFileRegion) msg).transferTo(wbc, 0);
            }
            super.write(ctx, msg, promise);
        }
    });
}
Also used : WritableByteChannel(java.nio.channels.WritableByteChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) BufferPoolAllocator(org.apache.cassandra.net.BufferPoolAllocator) ByteBuffer(java.nio.ByteBuffer) RangesAtEndpoint(org.apache.cassandra.locator.RangesAtEndpoint) IOException(java.io.IOException)

Example 5 with ChannelOutboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter in project cassandra by apache.

the class ConnectionTest method testCRCCorruption.

@Test
public void testCRCCorruption() throws Throwable {
    test((inbound, outbound, endpoint) -> {
        int version = outbound.settings().acceptVersions.max;
        if (version < VERSION_40)
            return;
        unsafeSetSerializer(Verb._TEST_1, () -> new IVersionedSerializer<Object>() {

            public void serialize(Object o, DataOutputPlus out, int version) throws IOException {
                out.writeInt((Integer) o);
            }

            public Object deserialize(DataInputPlus in, int version) throws IOException {
                return in.readInt();
            }

            public long serializedSize(Object o, int version) {
                return Integer.BYTES;
            }
        });
        connect(outbound);
        outbound.unsafeGetChannel().pipeline().addFirst(new ChannelOutboundHandlerAdapter() {

            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                ByteBuf bb = (ByteBuf) msg;
                bb.setByte(0, 0xAB);
                ctx.write(msg, promise);
            }
        });
        outbound.enqueue(Message.out(Verb._TEST_1, 0xffffffff));
        CompletableFuture.runAsync(() -> {
            while (outbound.isConnected() && !Thread.interrupted()) {
            }
        }).get(10, SECONDS);
        Assert.assertFalse(outbound.isConnected());
        // TODO: count corruptions
        connect(outbound);
    });
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) DataInputPlus(org.apache.cassandra.io.util.DataInputPlus) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) DataOutputPlus(org.apache.cassandra.io.util.DataOutputPlus) UnknownColumnException(org.apache.cassandra.exceptions.UnknownColumnException) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)32 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)32 ChannelPromise (io.netty.channel.ChannelPromise)30 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)18 Test (org.junit.jupiter.api.Test)17 ByteBuf (io.netty.buffer.ByteBuf)10 Test (org.junit.Test)9 IOException (java.io.IOException)7 ClosedChannelException (java.nio.channels.ClosedChannelException)7 ChannelFuture (io.netty.channel.ChannelFuture)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Channel (io.netty.channel.Channel)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 SslContext (io.netty.handler.ssl.SslContext)3 ByteBuffer (java.nio.ByteBuffer)3 WritableByteChannel (java.nio.channels.WritableByteChannel)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ApiErrorWithMetadata (com.nike.backstopper.apierror.ApiErrorWithMetadata)2 NettyHttpClientRequestBuilder (com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientRequestBuilder)2 NettyHttpClientResponse (com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientResponse)2