LocalHostPermitHandler extends ChannelHandlerAdapter { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } } } LocalHostPermitHandler(boolean acceptForeignIp); @Override void handlerAdded(ChannelHandlerContext ctx);  }
@Test public void testHandlerAdded() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); InetAddress addr = mock(InetAddress.class); when(addr.isLoopbackAddress()).thenReturn(false); InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); LocalHostPermitHandler handler = new LocalHostPermitHandler(false); handler.handlerAdded(context); ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class); verify(context).writeAndFlush(captor.capture()); assertThat(new String(captor.getValue().array()), containsString("Foreign Ip Not Permitted")); verify(future).addListener(ChannelFutureListener.CLOSE); }