Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void handlerRemovedFailuresPropagated() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
                @Override/*www  .j a  va 2s. c om*/
                public void handlerRemoved(ChannelHandlerContext ctx) {
                    ctx.pipeline()
                            .remove(ctx.pipeline().context(WriteBufferingAndExceptionHandler.class).name());
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    chan.connect(addr);
    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.pipeline().removeFirst();

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
        assertThat(status.getDescription()).contains("Buffer removed");
    }
}

From source file:io.hekate.network.netty.NettyClientHandshakeHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (trace) {/*  w w w.ja v a2 s .  com*/
        log.trace("Received handshake response [from={}, message={}]", id, msg);
    }

    NetworkProtocol handshakeMsg = (NetworkProtocol) msg;

    if (handshakeMsg.type() == NetworkProtocol.Type.HANDSHAKE_REJECT) {
        HandshakeReject reject = (HandshakeReject) handshakeMsg;

        String reason = reject.reason();

        if (debug) {
            log.debug("Server rejected connection [to={}, reason={}]", id, reason);
        }

        ctx.fireExceptionCaught(new ConnectException(reason));
    } else {
        HandshakeAccept accept = (HandshakeAccept) handshakeMsg;

        // Unregister self from the pipeline (handshake is a one time event).
        ctx.pipeline().remove(this);

        // Fire handshake event.
        ctx.fireUserEventTriggered(new NettyClientHandshakeEvent(accept));
    }
}

From source file:io.hekate.network.netty.NettyClientTimeoutHandler.java

License:Apache License

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    if (connTimeout != null && connTimeout > 0) {
        if (trace) {
            log.trace("Registering connect timeout handler [to={}, timeout={}]", id, connTimeout);
        }/*  w  ww . j av  a  2  s . c o m*/

        IdleStateHandler connectTimeoutHandler = new IdleStateHandler(connTimeout, 0, 0, TimeUnit.MILLISECONDS);

        ctx.pipeline().addFirst(CONNECT_TIMEOUT_HANDLER_ID, connectTimeoutHandler);
    }

    super.channelRegistered(ctx);
}

From source file:io.hekate.network.netty.NettyClientTimeoutHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof NettyClientHandshakeEvent) {
        NettyClientHandshakeEvent handshake = (NettyClientHandshakeEvent) evt;

        handshakeDone = true;/*ww w  . j  a v  a  2 s  .co  m*/

        // Unregister connect timeout handler.
        if (ctx.pipeline().get(CONNECT_TIMEOUT_HANDLER_ID) != null) {
            ctx.pipeline().remove(CONNECT_TIMEOUT_HANDLER_ID);
        }

        // Register heartbeat handler.
        mayBeRegisterHeartbeatHandler(handshake, ctx);

        super.userEventTriggered(ctx, evt);
    } else if (evt instanceof AutoReadChangeEvent) {
        if (evt == AutoReadChangeEvent.PAUSE) {
            // Completely ignore read timeouts.
            ignoreTimeouts = -1;
        } else {
            // Ignore next timeout.
            ignoreTimeouts = 1;
        }

        super.userEventTriggered(ctx, evt);
    } else if (evt instanceof IdleStateEvent) {
        IdleStateEvent idle = (IdleStateEvent) evt;

        if (idle.state() == IdleState.WRITER_IDLE) {
            if (hbFlushed) {
                // Make sure that we don't push multiple heartbeats to the network buffer simultaneously.
                // Need to perform this check since remote peer can hang and stop reading
                // while this channel will still be trying to put more and more heartbeats on its send buffer.
                hbFlushed = false;

                ctx.writeAndFlush(Heartbeat.INSTANCE).addListener(hbOnFlush);
            }
        } else {
            // Reader idle.
            // Ignore if auto-reading was disabled since in such case we will not read any heartbeats.
            if (ignoreTimeouts != -1 && ctx.channel().config().isAutoRead()) {
                // Check if timeout should be ignored.
                if (ignoreTimeouts > 0) {
                    // Decrement the counter of ignored timeouts.
                    ignoreTimeouts--;
                } else {
                    if (handshakeDone) {
                        ctx.fireExceptionCaught(
                                new SocketTimeoutException("Timeout while reading data from " + id));
                    } else {
                        ctx.fireExceptionCaught(
                                new ConnectTimeoutException("Timeout while connecting to " + id));
                    }
                }
            }
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}

From source file:io.hekate.network.netty.NettyClientTimeoutHandler.java

License:Apache License

private void mayBeRegisterHeartbeatHandler(NettyClientHandshakeEvent evt, ChannelHandlerContext ctx) {
    int interval = evt.hbInterval();
    int threshold = evt.hbLossThreshold();
    boolean disableHeartbeats = evt.isHbDisabled();

    ChannelPipeline pipe = ctx.pipeline();

    if (idleTimeout > 0) {
        if (trace) {
            log.trace("Registering idle connection handler [to={}, idle-timeout={}]", id, idleTimeout);
        }/*www .j a  v  a 2  s .  co  m*/

        pipe.addBefore(ctx.name(), "idle-channel-handler", new HeartbeatOnlyIdleStateHandler(idleTimeout));
    }

    if (interval > 0 && threshold > 0) {
        int readerIdle = interval * threshold;
        int writerIdle = disableHeartbeats ? 0 : interval;

        if (trace) {
            log.trace("Registering heartbeat handler [to={}, reader-idle={}, writer-idle={}]", id, readerIdle,
                    writerIdle);
        }

        pipe.addBefore(ctx.name(), "heartbeat-handler",
                new IdleStateHandler(readerIdle, writerIdle, 0, TimeUnit.MILLISECONDS));
    }
}

From source file:io.hekate.network.netty.NettyServerClient.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();

    if (trace) {// w  ww  .  j a  v  a  2  s.c o  m
        log.trace("Got connection [from={}]", channel.remoteAddress());
    }

    this.handlerCtx = ctx;

    mayBeCreateIdleStateHandler()
            .ifPresent(handler -> ctx.pipeline().addFirst(IdleStateHandler.class.getName(), handler));

    if (metrics != null) {
        metrics.onConnect();
    }
}

From source file:io.hekate.network.netty.NettyServerClient.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (isHandshakeDone()) {
        if (msg instanceof Heartbeat) {
            if (trace) {
                log.trace("Received network heartbeat from client [from={}]", address());
            }//from   w w w .j  a  v a  2s  .  c om
        } else {
            NettyMessage netMsg = (NettyMessage) msg;

            netMsg.prepare(log);

            if (trace) {
                log.trace("Message buffer prepared [from={}, message={}]", address(), netMsg);
            }

            if (metrics != null) {
                metrics.onMessageReceived();
            }

            try {
                serverHandler.onMessage(netMsg, this);
            } finally {
                netMsg.release();
            }
        }
    } else {
        if (trace) {
            log.trace("Received network handshake request [from={}, message={}]", address(), msg);
        }

        HandshakeRequest handshake = (HandshakeRequest) msg;

        String protocol;
        NettyServerHandler handlerReg;

        if (handshake == null) {
            protocol = null;
            handlerReg = null;
        } else {
            this.protocol = protocol = handshake.protocol();

            handlerReg = handlers.get(protocol);
        }

        if (handlerReg == null) {
            if (debug) {
                log.debug("Closing connection with unsupported protocol [from={}, protocol={}]", address(),
                        protocol);
            }

            HandshakeReject reject = new HandshakeReject("Unsupported protocol [protocol=" + protocol + ']');

            ctx.writeAndFlush(reject).addListener(ChannelFutureListener.CLOSE);
        } else {
            // Map connection to a thread.
            EventLoop eventLoop = mapToThread(handshake.threadAffinity(), handlerReg);

            // Check if we need to re-bind this channel to another thread.
            if (eventLoop.inEventLoop()) {
                // No need to rebind.
                init(ctx.channel(), handshake, handlerReg);
            } else {
                if (trace) {
                    log.trace("Registering channel to a custom NIO thread [from={}, protocol={}]", address(),
                            protocol);
                }

                // Unregister and then re-register IdleStateHandler in order to prevent RejectedExecutionException if same
                // instance is used on different threads.
                ctx.pipeline().remove(IdleStateHandler.class.getName());

                Channel channel = ctx.channel();

                channel.deregister().addListener(deregister -> {
                    if (deregister.isSuccess()) {
                        if (!eventLoop.isShutdown() && channel.isOpen()) {
                            eventLoop.register(channel).addListener(register -> {
                                if (register.isSuccess() && channel.isOpen()) {
                                    if (trace) {
                                        log.trace(
                                                "Registered channel to a custom NIO thread [from={}, protocol={}]",
                                                address(), protocol);
                                    }

                                    mayBeCreateIdleStateHandler().ifPresent(handler -> ctx.pipeline()
                                            .addFirst(IdleStateHandler.class.getName(), handler));

                                    init(channel, handshake, handlerReg);
                                }
                            });
                        }
                    }
                });
            }
        }
    }
}

From source file:io.hydramq.network.server.ProtocolSelector.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    ByteBuf buffer = (ByteBuf) msg;//from   www  .  j av a2s .c om
    for (ProtocolHandler protocolHandler : protocols) {
        if (protocolHandler.accept(buffer)) {
            logger.info("Loading {} protocol handler", protocolHandler);
            ctx.pipeline().addLast("commandEncoder",
                    new CommandEncoder(protocolHandler.getConversionContext()));
            ctx.pipeline().addLast("commandDecoder",
                    new CommandDecoder(protocolHandler.getConversionContext()));
            ctx.pipeline().addLast("protocol", protocolHandler);
            ctx.pipeline().addLast("responseHandler", completableFutureHandler);
            ctx.pipeline().remove(this);
            ctx.pipeline().fireChannelActive();
            ctx.fireChannelRead(msg);
            return;
        }
    }
    logger.error("No acceptable protocols found to handle client with protocol id of " + buffer.getInt(0));
    ctx.writeAndFlush(new Error(buffer.getInt(1), 5)).addListener(ChannelFutureListener.CLOSE);
}

From source file:io.jsync.http.impl.AsyncHttpHandler.java

License:Open Source License

@Override
protected void channelRead(final C connection, final DefaultContext context, final ChannelHandlerContext chctx,
        final Object msg) throws Exception {
    if (msg instanceof HttpObject) {
        DecoderResult result = ((HttpObject) msg).decoderResult();
        if (result.isFailure()) {
            chctx.pipeline().fireExceptionCaught(result.cause());
            return;
        }//  w w  w.  j  a  v  a2  s  .com
    }
    if (connection != null) {
        // we are reading from the channel
        Channel ch = chctx.channel();
        // We need to do this since it's possible the server is being used from a worker context
        if (context.isOnCorrectWorker(ch.eventLoop())) {
            try {
                async.setContext(context);
                doMessageReceived(connection, chctx, msg);
            } catch (Throwable t) {
                context.reportException(t);
            }
        } else {
            context.execute(new Runnable() {
                public void run() {
                    try {
                        doMessageReceived(connection, chctx, msg);
                    } catch (Throwable t) {
                        context.reportException(t);
                    }
                }
            });
        }
    } else {
        try {
            doMessageReceived(connection, chctx, msg);
        } catch (Throwable t) {
            chctx.pipeline().fireExceptionCaught(t);
        }
    }
}

From source file:io.jsync.http.impl.cgbystrom.FlashPolicyHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buffer = (ByteBuf) msg;//from  w  ww.j a  v  a 2 s  . co m
    int index = buffer.readerIndex();
    switch (state) {
    case MAGIC1:
        if (!buffer.isReadable()) {
            return;
        }
        final int magic1 = buffer.getUnsignedByte(index++);
        state = ParseState.MAGIC2;
        if (magic1 != '<') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
            return;
        }
        // fall through
    case MAGIC2:
        if (!buffer.isReadable()) {
            return;
        }
        final int magic2 = buffer.getUnsignedByte(index);
        if (magic2 != 'p') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
        } else {
            ctx.writeAndFlush(Unpooled.copiedBuffer(XML, CharsetUtil.UTF_8))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }
}