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:com.king.platform.net.http.netty.SslInitializer.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {
    InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) remoteAddress;
    String peerHost = remoteInetSocketAddress.getHostString();
    int peerPort = remoteInetSocketAddress.getPort();

    SslHandler sslHandler = createSslHandler(peerHost, peerPort);

    ctx.pipeline().replace(NAME, NAME, sslHandler);

    ctx.connect(remoteAddress, localAddress, promise);
}

From source file:com.kingmed.bidir.gateway.server.GatewayServerHandler.java

License:Apache License

/**
 * ?????//from   w  w  w  .j ava2  s.c  o  m
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // TODO Auto-generated method stub
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {

                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(" " + InetAddress.getLocalHost().getHostName()
                            + "???!\n");
                    ctx.writeAndFlush("? "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");
                    channels.add(ctx.channel());
                }

            });
}

From source file:com.lampard.netty4.ssl.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // Once session is secured, send a greeting and register the channel to
    // the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override/*from  ww w  .j  av a2 s.  co m*/
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*from  w  w w  .  j  a va2 s  .  c  o m*/
        break;
    case HTTP2_PREFERRED:
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (options.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            Http1ClientCodec http1Codec = newHttp1Codec();
            Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec());

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

void finishWithNegotiationFailure(ChannelHandlerContext ctx, SessionProtocol expected, SessionProtocol actual,
        String reason) {//from  w ww  .  j  a v  a2  s .  co  m

    final ChannelPipeline pipeline = ctx.pipeline();
    pipeline.channel().eventLoop().execute(() -> pipeline
            .fireUserEventTriggered(new SessionProtocolNegotiationException(expected, actual, reason)));
    ctx.close();
}

From source file:com.linecorp.armeria.client.http.HttpSessionHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SessionProtocol) {
        assert protocol == null;
        assert responseDecoder == null;

        sessionTimeoutFuture.cancel(false);

        // Set the current protocol and its associated WaitsHolder implementation.
        final SessionProtocol protocol = (SessionProtocol) evt;
        this.protocol = protocol;
        switch (protocol) {
        case H1:/*  ww  w.  ja  v  a 2 s .c  o m*/
        case H1C:
            requestEncoder = new Http1ObjectEncoder(false);
            responseDecoder = ctx.pipeline().get(Http1ResponseDecoder.class);
            break;
        case H2:
        case H2C:
            final Http2ConnectionHandler handler = ctx.pipeline().get(Http2ConnectionHandler.class);
            requestEncoder = new Http2ObjectEncoder(handler.encoder());
            responseDecoder = ctx.pipeline().get(Http2ClientConnectionHandler.class).responseDecoder();
            break;
        default:
            throw new Error(); // Should never reach here.
        }

        if (!sessionPromise.trySuccess(ctx.channel())) {
            // Session creation has been failed already; close the connection.
            ctx.close();
        }
        return;
    }

    if (evt instanceof SessionProtocolNegotiationException) {
        sessionTimeoutFuture.cancel(false);
        sessionPromise.tryFailure((SessionProtocolNegotiationException) evt);
        ctx.close();
        return;
    }

    logger.warn("{} Unexpected user event: {}", ctx.channel(), evt);
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(TrafficLoggingHandler.CLIENT);

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;//  w  ww  . jav  a  2  s  .  co m
        break;
    case HTTP2_PREFERRED:
        assert remoteAddress != null;
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        final Http2ClientConnectionHandler http2Handler = newHttp2ConnectionHandler(ch);
        if (clientFactory.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(http2Handler);
        } else {
            final Http1ClientCodec http1Codec = newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                    clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize());
            final Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(http2Handler);
            final HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, (int) Math.min(Integer.MAX_VALUE, UPGRADE_RESPONSE_MAX_LENGTH));

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler(http2Handler.responseDecoder()));
        }
    } else {
        pipeline.addLast(newHttp1Codec(clientFactory.maxHttp1InitialLineLength(),
                clientFactory.maxHttp1HeaderSize(), clientFactory.maxHttp1ChunkSize()));

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.HttpConfigurator.java

License:Apache License

private void configureAsHttp(Channel ch) {
    final ChannelPipeline pipeline = ch.pipeline();

    final boolean attemptUpgrade;
    switch (httpPreference) {
    case HTTP1_REQUIRED:
        attemptUpgrade = false;/*from w  w w .j  a v  a  2  s . com*/
        break;
    case HTTP2_PREFERRED:
        attemptUpgrade = !SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C);
        break;
    case HTTP2_REQUIRED:
        attemptUpgrade = true;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    if (attemptUpgrade) {
        if (options.useHttp2Preface()) {
            pipeline.addLast(new DowngradeHandler());
            pipeline.addLast(newHttp2ConnectionHandler(ch));
        } else {
            Http1ClientCodec http1Codec = newHttp1Codec();
            Http2ClientUpgradeCodec http2ClientUpgradeCodec = new Http2ClientUpgradeCodec(
                    newHttp2ConnectionHandler(ch));
            HttpClientUpgradeHandler http2UpgradeHandler = new HttpClientUpgradeHandler(http1Codec,
                    http2ClientUpgradeCodec, options.maxFrameLength());

            pipeline.addLast(http1Codec);
            pipeline.addLast(new WorkaroundHandler());
            pipeline.addLast(http2UpgradeHandler);
            pipeline.addLast(new UpgradeRequestHandler());
        }
    } else {
        pipeline.addLast(newHttp1Codec());

        // NB: We do not call finishSuccessfully() immediately here
        //     because it assumes HttpSessionHandler to be in the pipeline,
        //     which is only true after the connection attempt is successful.
        pipeline.addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.pipeline().remove(this);
                finishSuccessfully(pipeline, H1C);
                ctx.fireChannelActive();
            }
        });
    }
}

From source file:com.linecorp.armeria.client.HttpSessionHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SessionProtocol) {
        assert protocol == null;
        assert responseDecoder == null;

        sessionTimeoutFuture.cancel(false);

        // Set the current protocol and its associated WaitsHolder implementation.
        final SessionProtocol protocol = (SessionProtocol) evt;
        this.protocol = protocol;
        if (protocol == H1 || protocol == H1C) {
            requestEncoder = new Http1ObjectEncoder(false, protocol.isTls());
            responseDecoder = ctx.pipeline().get(Http1ResponseDecoder.class);
        } else if (protocol == H2 || protocol == H2C) {
            final Http2ConnectionHandler handler = ctx.pipeline().get(Http2ConnectionHandler.class);
            requestEncoder = new Http2ObjectEncoder(handler.encoder());
            responseDecoder = ctx.pipeline().get(Http2ClientConnectionHandler.class).responseDecoder();
        } else {/*  w ww.  j  a v  a2  s  .co  m*/
            throw new Error(); // Should never reach here.
        }

        if (!sessionPromise.trySuccess(ctx.channel())) {
            // Session creation has been failed already; close the connection.
            ctx.close();
        }
        return;
    }

    if (evt instanceof SessionProtocolNegotiationException) {
        sessionTimeoutFuture.cancel(false);
        sessionPromise.tryFailure((SessionProtocolNegotiationException) evt);
        ctx.close();
        return;
    }

    if (evt instanceof Http2ConnectionPrefaceAndSettingsFrameWrittenEvent
            || evt instanceof SslCloseCompletionEvent || evt instanceof ChannelInputShutdownReadComplete) {
        // Expected events
        return;
    }

    logger.warn("{} Unexpected user event: {}", ctx.channel(), evt);
}

From source file:com.linecorp.armeria.common.http.Http1ClientCodec.java

License:Apache License

/**
 * Upgrades to another protocol from HTTP. Removes the {@link Decoder} and {@link Encoder} from
 * the pipeline.//from  w w  w . j  a  v a  2  s  . c  o  m
 */
@Override
public void upgradeFrom(ChannelHandlerContext ctx) {
    final ChannelPipeline p = ctx.pipeline();
    p.remove(this);
}