NettyHttpServerCodec extends ChannelDuplexHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { FullHttpResponse nettyResponse; if (msg instanceof NettyHttpResponse) { nettyResponse = ((NettyHttpResponse) msg).netty(); } else if (msg instanceof HttpResponse) { nettyResponse = NettyHttpResponse.getNettyResponse((HttpResponse) msg, ctx.alloc()); } else if (msg instanceof FullHttpResponse) { nettyResponse = (FullHttpResponse) msg; } else { nettyResponse = null; } if (nettyResponse != null) { try { if (keepAlive) { nettyResponse.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(nettyResponse, promise); } else { ctx.write(nettyResponse).addListener(ChannelFutureListener.CLOSE); } ctx.flush(); } finally { ReferenceCountUtil.release(msg); } } }  @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise);  }
@Test public void testWrite() throws Exception { NettyHttpServerCodec codec = new NettyHttpServerCodec(); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); ByteBufAllocator allocator = new PooledByteBufAllocator(); when(ctx.alloc()).thenReturn(allocator); ChannelPromise promise = mock(ChannelPromise.class); HttpResponse httpResponse = StandardHttpResponse.newBuilder().build(); codec.write(ctx, httpResponse, promise); codec.write(ctx, NettyHttpResponse.getNettyResponse(httpResponse, allocator), promise); NettyHttpResponse nettyResponse = new NettyHttpResponse(httpResponse, allocator); codec.write(ctx, nettyResponse, promise); assertTrue(nettyResponse.netty().content().release()); codec.write(ctx, "message", promise); }