Search in sources :

Example 21 with ChannelOutboundHandlerAdapter

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

the class CommandAndControlMqttIT method injectMqttClientPubAckBlocker.

private Future<Void> injectMqttClientPubAckBlocker(final AtomicBoolean outboundPubAckBlocked) {
    // Therefore the underlying NetSocket pipeline is used here to filter out the outbound PubAck messages.
    try {
        final Method connectionMethod = MqttClientImpl.class.getDeclaredMethod("connection");
        connectionMethod.setAccessible(true);
        final NetSocketInternal connection = (NetSocketInternal) connectionMethod.invoke(mqttClient);
        connection.channelHandlerContext().pipeline().addBefore("handler", "OutboundPubAckBlocker", new ChannelOutboundHandlerAdapter() {

            @Override
            public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
                if (outboundPubAckBlocked.get() && msg instanceof io.netty.handler.codec.mqtt.MqttPubAckMessage) {
                    LOGGER.debug("suppressing PubAck, message id: {}", ((MqttPubAckMessage) msg).variableHeader().messageId());
                } else {
                    super.write(ctx, msg, promise);
                }
            }
        });
        return Future.succeededFuture();
    } catch (final Exception e) {
        LOGGER.error("failed to inject PubAck blocking handler");
        return Future.failedFuture(new Exception("failed to inject PubAck blocking handler", e));
    }
}
Also used : MqttPubAckMessage(io.netty.handler.codec.mqtt.MqttPubAckMessage) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) Method(java.lang.reflect.Method) IllegalStateException(javax.jms.IllegalStateException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal)

Example 22 with ChannelOutboundHandlerAdapter

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

the class NettyTest method pipelineTest.

@Test
public void pipelineTest() {
    final int[] int2 = new int[1];
    final boolean[] exception = new boolean[1];
    final ByteToMessageDecoder decoder2 = new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int i = in.readInt();
            System.out.println("decoder2 read int (4 bytes): " + Integer.toHexString(i));
            int2[0] = i;
            if (i == 0)
                out.add("aaa");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder2 exception: " + cause);
        }
    };
    final MessageToMessageCodec decoder3 = new MessageToMessageCodec<Object, Object>() {

        @Override
        protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            System.out.println("NettyTest.decode: msg = [" + msg + "]");
            if (msg == "aaa") {
                throw new RuntimeException("Test exception 3");
            }
        }

        @Override
        protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            throw new RuntimeException("Test exception 4");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder3 exception: " + cause);
            exception[0] = true;
        }
    };
    final ByteToMessageDecoder decoder1 = new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int i = in.readInt();
            System.out.println("decoder1 read int (4 bytes). Needs no more: " + Integer.toHexString(i));
            ctx.pipeline().addAfter("decoder1", "decoder2", decoder2);
            ctx.pipeline().addAfter("decoder2", "decoder3", decoder3);
            ctx.pipeline().remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder1 exception: " + cause);
        }
    };
    ChannelInboundHandlerAdapter initiator = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.pipeline().addFirst("decoder1", decoder1);
            System.out.println("NettyTest.channelActive");
        }
    };
    EmbeddedChannel channel0 = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            throw new RuntimeException("Test");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Exception caught: " + cause);
        }
    });
    EmbeddedChannel channel = new EmbeddedChannel(initiator);
    ByteBuf buffer = Unpooled.buffer();
    buffer.writeInt(0x12345678);
    buffer.writeInt(0xabcdefff);
    channel.writeInbound(buffer);
    Assert.assertEquals(0xabcdefff, int2[0]);
    channel.writeInbound(Unpooled.buffer().writeInt(0));
    Assert.assertTrue(exception[0]);
// Need the following for the exception in outbound handler to be fired
// ctx.writeAndFlush(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
// exception[0] = false;
// channel.writeOutbound("outMsg");
// Assert.assertTrue(exception[0]);
}
Also used : MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) List(java.util.List) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 23 with ChannelOutboundHandlerAdapter

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

the class TsiFrameHandlerTest method flushAfterCloseShouldWork.

@Test
public void flushAfterCloseShouldWork() throws InterruptedException {
    ByteBuf msg = Unpooled.copiedBuffer("message after handshake failed", CharsetUtil.UTF_8);
    channel.write(msg);
    channel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {

        @Override
        public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
            // We have to call flush while doing a close, since close() tears down the pipeline
            // immediately after.
            channel.flush();
            super.close(ctx, promise);
        }
    });
    assertThat(channel.outboundMessages()).isEmpty();
    channel.close().sync();
    Object actual = channel.readOutbound();
    assertWithMessage("pending write should be flushed on close").that(actual).isEqualTo(msg);
    channel.checkException();
}
Also used : ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) GeneralSecurityException(java.security.GeneralSecurityException) Test(org.junit.Test)

Example 24 with ChannelOutboundHandlerAdapter

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

the class CassandraEntireSSTableStreamWriterTest method createMockNettyChannel.

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

        private boolean isOpen = true;

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

        public boolean isOpen() {
            return isOpen;
        }

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

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            ((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) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException)

Example 25 with ChannelOutboundHandlerAdapter

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

the class ChunkedWriteHandlerTest method testStopConsumingChunksWhenFailed.

// See https://github.com/netty/netty/issues/8700.
@Test
public void testStopConsumingChunksWhenFailed() {
    final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
    final AtomicInteger chunks = new AtomicInteger(0);
    ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() {

        @Override
        public boolean isEndOfInput() throws Exception {
            return chunks.get() >= 5;
        }

        @Override
        public void close() throws Exception {
        // no-op
        }

        @Deprecated
        @Override
        public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
            return readChunk(ctx.alloc());
        }

        @Override
        public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
            chunks.incrementAndGet();
            return buffer.retainedDuplicate();
        }

        @Override
        public long length() {
            return -1;
        }

        @Override
        public long progress() {
            return 1;
        }
    };
    ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            ReferenceCountUtil.release(msg);
            promise.tryFailure(new RuntimeException());
        }
    };
    EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler());
    ch.writeAndFlush(nonClosableInput).awaitUninterruptibly();
    // Should be `false` as we do not expect any messages to be written
    assertFalse(ch.finish());
    buffer.release();
    // We should expect only single chunked being read from the input.
    // It's possible to get a race condition here between resolving a promise and
    // allocating a new chunk, but should be fine when working with embedded channels.
    assertEquals(1, chunks.get());
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.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