Example usage for io.netty.channel ChannelOutboundHandlerAdapter ChannelOutboundHandlerAdapter

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

Introduction

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

Prototype

ChannelOutboundHandlerAdapter

Source Link

Usage

From source file:org.apache.hadoop.hbase.ipc.TestIPC.java

License:Apache License

@Test
public void testRTEDuringAsyncConnectionSetup() throws Exception {
    Configuration conf = HBaseConfiguration.create();

    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = new AsyncRpcClient(conf, HConstants.CLUSTER_ID_DEFAULT, null,
            new ChannelInitializer<SocketChannel>() {

                @Override/*from ww  w. ja  v  a 2  s.  c om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            promise.setFailure(new RuntimeException("Injected fault"));
                        }
                    });
                }
            });
    try {
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
        controller.notifyOnFail(new RpcCallback<IOException>() {
            @Override
            public void run(IOException e) {
                done.set(true);
                LOG.info("Caught expected exception: " + e.toString());
                assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
            }
        });

        channel.callMethod(md, controller, param, md.getOutputType().toProto(), new RpcCallback<Message>() {
            @Override
            public void run(Message parameter) {
                done.set(true);
                fail("Expected an exception to have been thrown!");
            }
        });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:org.elasticsearch.http.nio.NettyAdaptor.java

License:Apache License

NettyAdaptor(ChannelHandler... handlers) {
    nettyChannel = new EmbeddedChannel();
    nettyChannel.pipeline().addLast("write_captor", new ChannelOutboundHandlerAdapter() {

        @Override//from  ww  w . j a  va2 s  . c  om
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            // This is a little tricky. The embedded channel will complete the promise once it writes the message
            // to its outbound buffer. We do not want to complete the promise until the message is sent. So we
            // intercept the promise and pass a different promise back to the rest of the pipeline.

            try {
                ByteBuf message = (ByteBuf) msg;
                promise.addListener((f) -> message.release());
                NettyListener listener = NettyListener.fromChannelPromise(promise);
                flushOperations.add(new FlushOperation(message.nioBuffers(), listener));
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    });
    nettyChannel.pipeline().addLast(handlers);
}

From source file:org.ethereum.net.NettyTest.java

License:Open Source License

@Test
public void pipelineTest() {

    final int[] int2 = new int[1];
    final boolean[] exception = new boolean[1];

    final ByteToMessageDecoder decoder2 = new ByteToMessageDecoder() {
        @Override/*  ww  w. j a  v  a 2  s .com*/
        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]);
}

From source file:org.onosproject.xmpp.core.ctl.handlers.XmppChannelHandler.java

License:Apache License

public XmppChannelHandler(XmppDeviceFactory deviceFactory) {
    ChannelInboundHandlerAdapter inboundHandlerAdapter = new ChannelInboundHandlerAdapter();
    ChannelOutboundHandlerAdapter outboundHandlerAdapter = new ChannelOutboundHandlerAdapter();
    this.init(inboundHandlerAdapter, outboundHandlerAdapter);
    this.state = ChannelState.IDLE;
    this.deviceFactory = deviceFactory;
}

From source file:org.opendaylight.netconf.client.TcpClientChannelInitializer.java

License:Open Source License

@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
    final Future<NetconfClientSession> negotiationFuture = promise;

    //We have to add this channel outbound handler to channel pipeline, in order
    //to get notifications from netconf negotiatior. Set connection promise to
    //success only after successful negotiation.
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
        ChannelPromise connectPromise;//from   ww  w . j a  v  a 2 s .  co m
        GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;

        @Override
        public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
                final SocketAddress localAddress, final ChannelPromise channelPromise) throws Exception {
            connectPromise = channelPromise;
            ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);

            negotiationFutureListener = new GenericFutureListener<Future<NetconfClientSession>>() {
                @Override
                public void operationComplete(final Future<NetconfClientSession> future) throws Exception {
                    if (future.isSuccess()) {
                        connectPromise.setSuccess();
                    }
                }
            };

            tcpConnectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(final Future<? super Void> future) throws Exception {
                    if (future.isSuccess()) {
                        //complete connection promise with netconf negotiation future
                        negotiationFuture.addListener(negotiationFutureListener);
                    } else {
                        connectPromise.setFailure(future.cause());
                    }
                }
            });
            ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
        }

        @Override
        public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
            // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
            if (connectPromise.isSuccess()) {
                ctx.fireChannelInactive();
            }

            //If connection promise is not already set, it means negotiation failed
            //we must set connection promise to failure
            if (!connectPromise.isDone()) {
                connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
            }

            //Remove listener from negotiation future, we don't want notifications
            //from negotiation anymore
            negotiationFuture.removeListener(negotiationFutureListener);

            super.disconnect(ctx, promise);
            promise.setSuccess();
        }
    });

    super.initialize(ch, promise);
}

From source file:org.opendaylight.netconf.impl.NetconfServerSessionTest.java

License:Open Source License

@Test
public void testStopExiCommunication() throws Exception {
    channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
            new ChannelInboundHandlerAdapter());
    channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
            new ChannelOutboundHandlerAdapter());
    session.stopExiCommunication();/*from  w  w  w  .j a v  a2 s  . c  o m*/
    //handler is replaced only after next send message call
    final ChannelHandler exiEncoder = channel.pipeline()
            .get(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER);
    Assert.assertTrue(ChannelOutboundHandlerAdapter.class.equals(exiEncoder.getClass()));
    session.sendMessage(msg);
    channel.runPendingTasks();
    final ChannelHandler decoder = channel.pipeline().get(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER);
    Assert.assertTrue(NetconfXMLToMessageDecoder.class.equals(decoder.getClass()));
    final ChannelHandler encoder = channel.pipeline().get(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER);
    Assert.assertTrue(NetconfMessageToXMLEncoder.class.equals(encoder.getClass()));
}

From source file:org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiatorTest.java

License:Open Source License

@Test
public void testStartNegotiationNotEstablished() throws Exception {
    final ChannelOutboundHandler closedDetector = Mockito.spy(new ChannelOutboundHandlerAdapter());
    channel.pipeline().addLast("closedDetector", closedDetector);
    doReturn(false).when(promise).isDone();
    doReturn(false).when(promise).isCancelled();
    negotiator.startNegotiation();/*from w ww .ja  v  a2 s  .  c o  m*/
    verify(closedDetector, timeout(2000)).close(any(), any());
}

From source file:org.openremote.agent.protocol.io.AbstractIoServer.java

License:Open Source License

/**
 * Initialise the specified client channel (will be called when a new client connection is made)
 *///from w  w w .ja  v a 2s . c  o m
protected void initClientChannel(U channel) {
    LOG.fine("Client initialising: " + getClientDescriptor(channel));

    // Add handler to track when a channel becomes active and to handle exceptions
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            onClientConnected(channel);
            super.channelActive(ctx);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            onClientDisconnected(channel);
            super.channelInactive(ctx);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            onDecodeException(ctx, cause);
            super.exceptionCaught(ctx, cause);
        }
    });

    channel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            onEncodeException(ctx, cause);
            super.exceptionCaught(ctx, cause);
        }
    });

    addDecoders(channel);
    addEncoders(channel);

    // Add handler to route the final messages
    channel.pipeline().addLast(new SimpleChannelInboundHandler<T>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, T msg) {
            onMessageReceived(channel, msg);
        }
    });
}

From source file:reactor.io.net.impl.netty.udp.NettyDatagramServer.java

License:Apache License

protected void bindChannel(ReactorChannelHandler<IN, OUT, ChannelStream<IN, OUT>> handler, Object _ioChannel) {
    NioDatagramChannel ioChannel = (NioDatagramChannel) _ioChannel;
    NettyChannelStream<IN, OUT> netChannel = new NettyChannelStream<IN, OUT>(getDefaultEnvironment(),
            getDefaultCodec(), getDefaultPrefetchSize(), getDefaultDispatcher(), ioChannel);

    ChannelPipeline pipeline = ioChannel.pipeline();

    if (log.isDebugEnabled()) {
        pipeline.addLast(new LoggingHandler(NettyDatagramServer.class));
    }/*from ww w.  ja  v a 2s. c om*/

    pipeline.addLast(new NettyChannelHandlerBridge<IN, OUT>(handler, netChannel) {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg != null && DatagramPacket.class.isAssignableFrom(msg.getClass())) {
                super.channelRead(ctx, ((DatagramPacket) msg).content());
            } else {
                super.channelRead(ctx, msg);
            }
        }
    }, new ChannelOutboundHandlerAdapter() {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            super.write(ctx, msg, promise);
        }
    });
}

From source file:reactor.io.net.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull EventBus reactor,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec,
        Collection<Consumer<NetChannel<IN, OUT>>> consumers) {
    super(env, reactor, listenAddress, multicastInterface, options, codec, consumers);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {/*from  ww  w.ja  v  a 2s .  co m*/
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = env.getProperty("reactor.udp.ioThreadCount", Integer.class, Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final NettyNetChannelInboundHandler inboundHandler = new NettyNetChannelInboundHandler() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, ((DatagramPacket) msg).content());
        }
    };

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    final NioDatagramChannel ch = new NioDatagramChannel();
                    DatagramChannelConfig config = ch.config();
                    config.setReceiveBufferSize(options.rcvbuf());
                    config.setSendBufferSize(options.sndbuf());
                    config.setReuseAddress(options.reuseAddr());

                    if (null != multicastInterface) {
                        config.setNetworkInterface(multicastInterface);
                    }

                    if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) {
                        nettyOptions.pipelineConfigurer().accept(ch.pipeline());
                    }

                    ch.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (log.isInfoEnabled()) {
                                log.info("CLOSE {}", ch);
                            }
                            close(ch);
                        }
                    });

                    netChannel = (NettyNetChannel<IN, OUT>) select(ch);
                    inboundHandler.setNetChannel(netChannel);

                    ch.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            super.write(ctx, msg, promise);
                        }
                    });

                    return ch;
                }
            }).handler(inboundHandler);

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}