Example usage for io.netty.channel ChannelPipeline context

List of usage examples for io.netty.channel ChannelPipeline context

Introduction

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

Prototype

ChannelHandlerContext context(Class<? extends ChannelHandler> handlerType);

Source Link

Document

Returns the context object of the ChannelHandler of the specified type in this pipeline.

Usage

From source file:io.netlibs.bgp.netty.handlers.BGPv4ClientEndpoint.java

License:Apache License

@Override
// public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception
public void channelActive(final ChannelHandlerContext ctx) throws Exception {

    log.info("connected to client " + ctx.channel().remoteAddress());

    final BGPv4FSM fsm = this.fsmRegistry.lookupFSM((InetSocketAddress) ctx.channel().remoteAddress());

    if (fsm == null) {
        log.error("Internal Error: client for address " + ctx.channel().remoteAddress() + " is unknown");
        ctx.channel().close();/*w  w w . jav  a  2  s .  c  o m*/
    } else {

        final ChannelPipeline pipeline = ctx.pipeline();
        final PeerConnectionInformation pci = fsm.getPeerConnectionInformation();

        pipeline.forEach(e -> {

            ChannelHandler handler = e.getValue();

            if (handler.getClass().isAnnotationPresent(PeerConnectionInformationAware.class)) {
                log.info("attaching peer connection information " + pci + " to handler " + e.getKey()
                        + " for client " + ctx.channel().remoteAddress());
                pipeline.context(e.getKey()).attr(PEER_CONNECTION_INFO).set(pci);
            }

        });

        fsm.handleClientConnected(ctx.channel());

        ctx.fireChannelActive();

    }

}

From source file:io.netlibs.bgp.netty.handlers.BGPv4ServerEndpoint.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel clientChannel = ctx.channel();

    log.info("connected to client " + clientChannel.remoteAddress());

    BGPv4FSM fsm = fsmRegistry.lookupFSM(((InetSocketAddress) clientChannel.remoteAddress()).getAddress());

    if (fsm == null) {
        log.error("Internal Error: client for address " + clientChannel.remoteAddress() + " is unknown");
        clientChannel.close();//w  w w  . ja va  2s  .com
    } else if (fsm.isCanAcceptConnection()) {

        ChannelPipeline pipeline = ctx.pipeline();
        PeerConnectionInformation pci = fsm.getPeerConnectionInformation();

        pipeline.forEach(e -> {

            ChannelHandler handler = e.getValue();

            if (handler.getClass().isAnnotationPresent(PeerConnectionInformationAware.class)) {
                log.info("attaching peer connection information {} to handler {} for client {}", pci,
                        e.getKey(), clientChannel.remoteAddress());
                pipeline.context(handler).attr(BGPv4ClientEndpoint.PEER_CONNECTION_INFO).set(pci);
            }

        });

        fsm.handleServerOpened(clientChannel);

        trackedChannels.add(clientChannel);
        ctx.fireChannelActive();

    } else {
        log.info("Connection from client {} cannot be accepted", clientChannel.remoteAddress());
        clientChannel.close();
    }

}

From source file:io.reactivex.netty.pipeline.ReadTimeoutPipelineConfigurator.java

License:Apache License

public static void disableReadTimeout(ChannelPipeline pipeline) {

    /**/*w w  w  .  j a v  a2s  . c o  m*/
     * Since, ChannelPipeline.remove() is blocking when not called from the associated eventloop, we do not remove
     * the handler. Instead we decativate the handler (invoked by the associated eventloop) here so that it does not
     * generate any more timeouts.
     * The handler is activated on next write to this pipeline.
     *
     * See issue: https://github.com/Netflix/RxNetty/issues/145
     */
    final ChannelHandler timeoutHandler = pipeline.get(READ_TIMEOUT_HANDLER_NAME);
    if (timeoutHandler != null) {
        final ChannelHandlerContext handlerContext = pipeline.context(timeoutHandler);
        EventExecutor executor = handlerContext.executor();

        // Since, we are calling the handler directly, we need to make sure, it is in the owner eventloop, else it
        // can get concurrent callbacks.
        if (executor.inEventLoop()) {
            disableHandler(timeoutHandler, handlerContext);
        } else {
            executor.submit(new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    disableHandler(timeoutHandler, handlerContext);
                    return null;
                }
            });
        }
    }
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientHandler.java

License:Apache License

private void finishHandshake(ChannelHandlerContext ctx, FullHttpResponse msg, Channel ch) {
    try {/* w ww  . jav a  2s  . c  om*/
        handshaker.finishHandshake(ch, msg);
    } catch (WebSocketHandshakeException e) {
        eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_FAILURE,
                Clock.onEndMillis(handshakeStartTime));
        handshakeFuture.setFailure(e);
        ctx.close();
        return;
    }
    eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_SUCCESS, Clock.onEndMillis(handshakeStartTime));

    ChannelPipeline p = ctx.pipeline();
    ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class);
    p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ClientReadMetricsHandler(eventsSubject));
    ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class);
    p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ClientWriteMetricsHandler(eventsSubject));
    if (messageAggregation) {
        p.addAfter("websocket-read-metrics", "websocket-frame-aggregator",
                new WebSocketFrameAggregator(maxFramePayloadLength));
    }
    p.remove(HttpObjectAggregator.class);
    p.remove(this);

    handshakeFuture.setSuccess();
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java

License:Apache License

private void updatePipeline(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class);
    p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ServerWriteMetricsHandler(eventsSubject));
    ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class);
    p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ServerReadMetricsHandler(eventsSubject));
    if (messageAggregator) {
        p.addAfter("websocket-read-metrics", "websocket-frame-aggregator",
                new WebSocketFrameAggregator(maxFramePayloadLength));
    }/*from   w  ww  .  j  av  a 2s  .c  o  m*/
    p.remove(this);
}

From source file:me.netty.http.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 *//*from  w w  w .j  a  v  a  2  s .  com*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new Http1Handler());
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

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

License:Apache License

private void established(Channel ch) throws IOException {
    ChannelPipeline p = ch.pipeline();
    String addBeforeHandler = p.context(BufferCallBeforeInitHandler.class).name();
    p.addBefore(addBeforeHandler, null,/*from www .j  a  va  2  s.co m*/
            new IdleStateHandler(0, rpcClient.minIdleTimeBeforeClose, 0, TimeUnit.MILLISECONDS));
    p.addBefore(addBeforeHandler, null, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    p.addBefore(addBeforeHandler, null,
            new NettyRpcDuplexHandler(this, rpcClient.cellBlockBuilder, codec, compressor));
    p.fireUserEventTriggered(BufferCallEvent.success());
}

From source file:org.apache.hadoop.hbase.security.NettyHBaseRpcConnectionHeaderHandler.java

License:Apache License

/**
 * Remove handlers for sasl encryption and add handlers for Crypto AES encryption
 *///w  ww .  j a v  a2  s.  c  o  m
private void setupCryptoAESHandler(ChannelPipeline p, CryptoAES cryptoAES) {
    p.remove(SaslWrapHandler.class);
    p.remove(SaslUnwrapHandler.class);
    String lengthDecoder = p.context(LengthFieldBasedFrameDecoder.class).name();
    p.addAfter(lengthDecoder, null, new CryptoAESUnwrapHandler(cryptoAES));
    p.addAfter(lengthDecoder, null, new CryptoAESWrapHandler(cryptoAES));
}

From source file:org.glassfish.jersey.netty.httpserver.JerseyServerInitializer.java

License:Open Source License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
 *//*from  w w w.j a  v a2s.  com*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, new HttpServerUpgradeHandler.UpgradeCodecFactory() {
        @Override
        public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                return new Http2ServerUpgradeCodec(
                        new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container)));
            } else {
                return null;
            }
        }
    }));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            // "Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");

            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new JerseyServerHandler(baseUri, container));
            pipeline.replace(this, null, new ChunkedWriteHandler());
            ctx.fireChannelRead(msg);
        }
    });
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClientHandshaker.java

License:Apache License

public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {

    channel.writeAndFlush(Unpooled.wrappedBuffer(version.getBytes())).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            promise.setFailure(future.cause());
            return;
        }/*from w  w  w .  jav  a 2  s. c om*/

        ChannelPipeline p = future.channel().pipeline();
        ChannelHandlerContext ctx = p.context(ProtocolHandshakeHandler.class);
        p.addBefore(ctx.name(), "rfb-handshake-decoder", newRfbClientDecoder());
        p.addBefore(ctx.name(), "rfb-handshake-encoder", newRfbClientEncoder());
        promise.setSuccess();

    });
    return promise;
}