Example usage for io.netty.handler.codec.http2 Http2ServerUpgradeCodec Http2ServerUpgradeCodec

List of usage examples for io.netty.handler.codec.http2 Http2ServerUpgradeCodec Http2ServerUpgradeCodec

Introduction

In this page you can find the example usage for io.netty.handler.codec.http2 Http2ServerUpgradeCodec Http2ServerUpgradeCodec.

Prototype

public Http2ServerUpgradeCodec(Http2MultiplexCodec http2Codec) 

Source Link

Document

Creates the codec using a default name for the connection handler when adding to the pipeline.

Usage

From source file:Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
 *///from   w w  w .  j a  v a 2  s.c  o  m
private static void configureClearText(SocketChannel ch) {
    HttpServerCodec sourceCodec = new HttpServerCodec();
    HttpServerUpgradeHandler.UpgradeCodec upgradeCodec = new Http2ServerUpgradeCodec(
            new HelloWorldHttp2Handler());
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec,
            Collections.singletonList(upgradeCodec), 65536);

    ch.pipeline().addLast(sourceCodec);
    ch.pipeline().addLast(upgradeHandler);
    ch.pipeline().addLast(new UserEventLogger());
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpServerInitializer.java

License:Open Source License

/**
 * initChannel is called by Netty when a channel is first used.
 *///  ww  w  . ja va2 s  . co  m
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    ch.config().setAllocator(NettyChannelContext.ALLOCATOR);
    ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE);
    ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE);

    SslHandler sslHandler = null;
    if (this.sslContext != null) {
        sslHandler = this.sslContext.newHandler(ch.alloc());
        SslClientAuthMode mode = this.host.getState().sslClientAuthMode;
        if (mode != null) {
            switch (mode) {
            case NEED:
                sslHandler.engine().setNeedClientAuth(true);
                break;
            case WANT:
                sslHandler.engine().setWantClientAuth(true);
                break;
            default:
                break;
            }
        }
        p.addLast(SSL_HANDLER, sslHandler);
    }

    // The HttpServerCodec combines the HttpRequestDecoder and the HttpResponseEncoder, and it
    // also provides a method for upgrading the protocol, which we use to support HTTP/2. It
    // also supports a couple other minor features (support for HEAD and CONNECT), which
    // probably don't matter to us.
    HttpServerCodec http1_codec = new HttpServerCodec(NettyChannelContext.MAX_INITIAL_LINE_LENGTH,
            NettyChannelContext.MAX_HEADER_SIZE, NettyChannelContext.MAX_CHUNK_SIZE, false);
    p.addLast(HTTP1_CODEC, http1_codec);
    if (this.sslContext == null) {
        // Today we only use HTTP/2 when SSL is disabled
        final HttpToHttp2ConnectionHandler connectionHandler = makeHttp2ConnectionHandler();
        UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
            @Override
            public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
                if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                    return new Http2ServerUpgradeCodec(connectionHandler);
                } else {
                    return null;
                }
            }
        };
        // On upgrade, the upgradeHandler will remove the http1_codec and replace it
        // with the connectionHandler. Ideally we'd remove the aggregator (chunked transfer
        // isn't allowed in HTTP/2) and the WebSocket handler (we don't support it over HTTP/2 yet)
        // but we're not doing that yet.

        HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(http1_codec,
                upgradeCodecFactory);

        p.addLast(HTTP2_UPGRADE_HANDLER, upgradeHandler);
    }

    p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(this.responsePayloadSizeLimit));
    p.addLast(WEBSOCKET_HANDLER, new NettyWebSocketRequestHandler(this.host,
            ServiceUriPaths.CORE_WEB_SOCKET_ENDPOINT, ServiceUriPaths.WEB_SOCKET_SERVICE_PREFIX));
    p.addLast(HTTP_REQUEST_HANDLER,
            new NettyHttpClientRequestHandler(this.host, sslHandler, this.responsePayloadSizeLimit));
}

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

License:Apache License

@Test
public void plaintextUpgradeNegotiator() throws Exception {
    LocalAddress addr = new LocalAddress("plaintextUpgradeNegotiator");
    UpgradeCodecFactory ucf = new UpgradeCodecFactory() {

        @Override/*from  ww  w.j  ava 2  s  .  c om*/
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new Http2ServerUpgradeCodec(FakeGrpcHttp2ConnectionHandler.newHandler());
        }
    };
    final HttpServerCodec serverCodec = new HttpServerCodec();
    final HttpServerUpgradeHandler serverUpgradeHandler = new HttpServerUpgradeHandler(serverCodec, ucf);
    Channel serverChannel = new ServerBootstrap().group(group).channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(serverCodec, serverUpgradeHandler);
                }
            }).bind(addr).sync().channel();

    FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler();
    ProtocolNegotiator nego = ProtocolNegotiators.plaintextUpgrade();
    ChannelHandler ch = nego.newHandler(gh);
    WriteBufferingAndExceptionHandler wbaeh = new WriteBufferingAndExceptionHandler(ch);

    Channel channel = new Bootstrap().group(group).channel(LocalChannel.class).handler(wbaeh).register().sync()
            .channel();

    ChannelFuture write = channel.writeAndFlush(NettyClientHandler.NOOP_MESSAGE);
    channel.connect(serverChannel.localAddress());

    boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    if (!completed) {
        assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
        // sync should fail if we are in this block.
        write.sync();
        throw new AssertionError("neither wrote nor negotiated");
    }

    channel.close().sync();
    serverChannel.close();

    assertThat(gh.securityInfo).isNull();
    assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.NONE);
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr);
}

From source file:io.vertx.core.http.Http2ClientTest.java

License:Open Source License

private ServerBootstrap createH2CServer(
        BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler,
        boolean upgrade) {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override//from w  ww  .j  av  a  2 s  .com
        protected void initChannel(Channel ch) throws Exception {
            if (upgrade) {
                HttpServerCodec sourceCodec = new HttpServerCodec();
                HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory = protocol -> {
                    if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                        Http2ConnectionHandler httpConnectionHandler = createHttpConnectionHandler((a, b) -> {
                            return new Http2FrameListenerDecorator(handler.apply(a, b)) {
                                @Override
                                public void onSettingsRead(ChannelHandlerContext ctx,
                                        io.netty.handler.codec.http2.Http2Settings settings)
                                        throws Http2Exception {
                                    super.onSettingsRead(ctx, settings);
                                    Http2Connection conn = a.connection();
                                    Http2Stream stream = conn.stream(1);
                                    DefaultHttp2Headers blah = new DefaultHttp2Headers();
                                    blah.status("200");
                                    b.frameWriter().writeHeaders(ctx, 1, blah, 0, true, ctx.voidPromise());
                                }
                            };
                        });
                        return new Http2ServerUpgradeCodec(httpConnectionHandler);
                    } else {
                        return null;
                    }
                };
                ch.pipeline().addLast(sourceCodec);
                ch.pipeline().addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
            } else {
                Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler);
                ch.pipeline().addLast("handler", clientHandler);
            }
        }
    });
    return bootstrap;
}

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

private ServerBootstrap createH2CServer(
        BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler,
        boolean upgrade) {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override/*from   ww w . ja  v  a 2  s  .com*/
        protected void initChannel(Channel ch) throws Exception {
            if (upgrade) {
                HttpServerCodec sourceCodec = new HttpServerCodec();
                HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory = protocol -> {
                    if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                        return new Http2ServerUpgradeCodec(createHttpConnectionHandler(handler));
                    } else {
                        return null;
                    }
                };
                ch.pipeline().addLast(sourceCodec);
                ch.pipeline().addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
            } else {
                Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler);
                ch.pipeline().addLast("handler", clientHandler);
            }
        }
    });
    return bootstrap;
}

From source file:netty.mmb.http2.Server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
 *//*  ww w  . java2s .co  m*/
private static void configureClearText(SocketChannel ch) {
    //        HttpServer
    HttpServerCodec sourceCodec = new HttpServerCodec();
    //        HttpServerUpgrade
    HttpServerUpgradeHandler.UpgradeCodec upgradeCodec = new Http2ServerUpgradeCodec(new Http2Handler());
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec,
            Collections.singletonList(upgradeCodec), 65536);

    ch.pipeline().addLast(sourceCodec);
    ch.pipeline().addLast(upgradeHandler);
    //        Invoked if the user triggered an event with some custom object
    ch.pipeline().addLast(new UserEventLogger());
}

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  ww w. j ava  2  s  .  c om
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.wso2.custom.inbound.InboundHttp2ServerInitializer.java

License:Apache License

public InboundHttp2ServerInitializer(SslContext sslCtx, int maxHttpContentLength, final InboundHttp2Configuration config) {
    if (maxHttpContentLength < 0) {
        throw new IllegalArgumentException("maxHttpContentLength (expected >= 0): " + maxHttpContentLength);
    }//  www .j  a v a2s .c om
    this.config=config;
    this.sslCtx = sslCtx;
    this.maxHttpContentLength = maxHttpContentLength;
    upgradeCodecFactory = new UpgradeCodecFactory() {

        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
                return new Http2ServerUpgradeCodec(new Http2Codec(true,
                        new InboundHttp2SourceHandler(config)));
            } else {
                return null;
            }
        }
    };
}