Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

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

Introduction

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

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

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 .jav  a2  s.  c  o m
        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.jooby.Netty.java

License:Apache License

protected static ChannelHandler handler() {
    byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
    return new ChannelInboundHandlerAdapter() {
        @Override/*from   w  w  w  .  j ava  2  s .  com*/
        public void channelReadComplete(final ChannelHandlerContext ctx) {
            ctx.flush();
        }

        @Override
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
            if (msg instanceof HttpRequest) {
                HttpRequest req = (HttpRequest) msg;

                if (HttpHeaders.is100ContinueExpected(req)) {
                    ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
                }
                boolean keepAlive = HttpHeaders.isKeepAlive(req);
                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                        Unpooled.wrappedBuffer(helloWorld));
                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                if (!keepAlive) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    response.headers().set(CONNECTION, Values.KEEP_ALIVE);
                    ctx.write(response);
                }
            }

        }

        @Override
        public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    };
}

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.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 ww .  java  2 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

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    channel = new EmbeddedChannel();
    xmlToHello = new NetconfXMLToHelloMessageDecoder();
    channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
            new ChannelInboundHandlerAdapter());
    channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, xmlToHello);
    channel.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER,
            FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
    channel.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator());
    hello = NetconfHelloMessage.createClientHello(Collections.emptySet(), Optional.absent());
    helloBase11 = NetconfHelloMessage.createClientHello(
            Collections.singleton(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1), Optional.absent());
    prefs = new NetconfSessionPreferences(helloBase11);
    doReturn(promise).when(promise).setFailure(any());
    doReturn(promise).when(promise).setSuccess(any());
    negotiator = new TestSessionNegotiator(prefs, promise, channel, new HashedWheelTimer(), listener, 100L);
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCDispatcherImpl.java

License:Open Source License

@Override
public Future<PCEPSession> createClient(@Nonnull final InetSocketAddress remoteAddress,
        @Nonnull final long reconnectTime, @Nonnull final PCEPSessionListenerFactory listenerFactory,
        @Nonnull final PCEPSessionNegotiatorFactory negotiatorFactory, @Nonnull final KeyMapping keys,
        @Nullable final InetSocketAddress localAddress, @Nonnull final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);//from w  w w . j a va 2  s . c o m
    final Optional<KeyMapping> optionalKey = Optional.fromNullable(keys);
    setChannelFactory(b, optionalKey);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
    final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
    final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer,
            CONNECT_TIMEOUT, b);
    final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(listenerFactory, ch,
                    promise, new PCCPeerProposal(dbVersion)));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
                    if (promise.isCancelled()) {
                        return;
                    }

                    if (!promise.isInitialConnectFinished()) {
                        LOG.debug("Connection to {} was dropped during negotiation, reattempting",
                                remoteAddress);
                        return;
                    }
                    LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                    PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory,
                            negotiatorFactory, keys, localAddress, dbVersion);
                }
            });
        }
    };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
}

From source file:org.opendaylight.usc.agent.UscAgentUdp.java

License:Open Source License

public UscAgentUdp(boolean callHome, InetAddress host, String propertyFile) {
    final UscAgentUdp agent = this;
    UscConfigurationServiceImpl.setDefaultPropertyFilePath(propertyFile);
    secureService = UscServiceUtils.getService(UscSecureService.class);
    b.group(bossGroup);/* ww  w  .  j  ava 2s . co  m*/
    b.channel(NioDatagramChannel.class);
    b.handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        public void initChannel(NioDatagramChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            agentServerChannel = ch;
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    final Channel ch = ctx.channel();
                    final InetSocketAddress remoteAddress = ((DatagramPacket) msg).sender();

                    // this is to deal with UDP channels which don't by
                    // default have remote address
                    if (ch.remoteAddress() == null) {
                        ch.connect(remoteAddress);
                    }
                    ch.pipeline().remove(this);
                    super.channelRead(ctx, msg);
                }

            });
            if (secureService == null) {
                LOG.error("UscSecureService is not initialized!");
                return;
            }
            p.addLast(new LoggingHandler("UscAgnet Handler 5", LogLevel.TRACE));
            p.addLast(secureService.getUdpServerHandler(ch));
            p.addLast(new LoggingHandler("UscAgnet Handler 4", LogLevel.TRACE));
            p.addLast(new UscFrameEncoderUdp());
            p.addLast(new LoggingHandler("UscAgnet Handler 3", LogLevel.TRACE));
            p.addLast(new UscFrameDecoderUdp());
            p.addLast(new LoggingHandler("UscAgnet Handler 2", LogLevel.TRACE));
            p.addLast(new UscAgentUdpHandler(agent, ch));
            p.addLast(new LoggingHandler("UscAgnet Handler 1", LogLevel.TRACE));

        }
    });

    if (callHome) {
        cb.group(callHomeGroup);
        cb.channel(NioDatagramChannel.class);
        cb.handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                agentServerChannel = ch;
                p.addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        final Channel ch = ctx.channel();
                        final InetSocketAddress remoteAddress = ((DatagramPacket) msg).sender();

                        // this is to deal with UDP channels which don't by
                        // default have remote address
                        if (ch.remoteAddress() == null) {
                            ch.connect(remoteAddress);
                        }
                        ch.pipeline().remove(this);
                        super.channelRead(ctx, msg);
                    }

                });
                if (secureService == null) {
                    LOG.error("UscSecureService is not initialized!");
                    return;
                }
                p.addLast(new LoggingHandler("LOG2-5", LogLevel.TRACE));
                p.addLast(secureService.getUdpClientHandler(ch));
                p.addLast(new LoggingHandler("LOG2-4", LogLevel.TRACE));
                p.addLast(new UscFrameEncoderUdp());
                p.addLast(new LoggingHandler("LOG2-3", LogLevel.TRACE));
                p.addLast(new UscFrameDecoderUdp());
                p.addLast(new LoggingHandler("LOG2-2", LogLevel.TRACE));
                p.addLast(new UscAgentUdpHandler(agent, ch));
                p.addLast(new LoggingHandler("LOG2-1", LogLevel.TRACE));

            }
        });

        try {
            InetSocketAddress recipient = new InetSocketAddress(host, 1069);
            cb.connect(recipient).sync().channel();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.openremote.agent.protocol.AbstractNettyMessageProcessor.java

License:Open Source License

/**
 * Inserts the decoders and encoders into the channel pipeline
 *///w ww. j  ava  2  s . c om
protected void initChannel(Channel channel) {
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            synchronized (AbstractNettyMessageProcessor.this) {
                LOG.fine("Connected: " + getSocketAddressString());
                onConnectionStatusChanged(ConnectionStatus.CONNECTED);
            }
            super.channelActive(ctx);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            synchronized (AbstractNettyMessageProcessor.this) {
                if (connectionStatus != ConnectionStatus.DISCONNECTING) {
                    // This is a connection failure so ignore as reconnect logic will handle it
                    return;
                }

                LOG.fine("Disconnected: " + getSocketAddressString());
                onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);
            }
            super.channelInactive(ctx);
        }
    });
    channel.pipeline().addLast(new MessageDecoder());
    channel.pipeline().addLast(new MessageEncoder());
}

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 a2s  .  co 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:org.pumpkindb.Client.java

License:Mozilla Public License

public void connect() {
    workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);/* ww w . j  a  v a 2 s  .c om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);

    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));

            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new FrameEncoder());

            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    messageHandler.accept(buf);
                }
            });
        }

    });

    ChannelFuture channelFuture = b.connect(host, port).syncUninterruptibly();

    channel = channelFuture.channel();

}