Search in sources :

Example 1 with DefaultHttp2Connection

use of io.netty.handler.codec.http2.DefaultHttp2Connection in project netty by netty.

the class Http2ClientInitializer method initChannel.

@Override
public void initChannel(SocketChannel ch) throws Exception {
    final Http2Connection connection = new DefaultHttp2Connection(false);
    connectionHandler = new HttpToHttp2ConnectionHandlerBuilder().frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength).propagateSettings(true).build())).frameLogger(logger).connection(connection).build();
    responseHandler = new HttpResponseHandler();
    settingsHandler = new Http2SettingsHandler(ch.newPromise());
    if (sslCtx != null) {
        configureSsl(ch);
    } else {
        configureClearText(ch);
    }
}
Also used : DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) DelegatingDecompressorFrameListener(io.netty.handler.codec.http2.DelegatingDecompressorFrameListener) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Connection(io.netty.handler.codec.http2.Http2Connection) InboundHttp2ToHttpAdapterBuilder(io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterBuilder) HttpToHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.HttpToHttp2ConnectionHandlerBuilder)

Example 2 with DefaultHttp2Connection

use of io.netty.handler.codec.http2.DefaultHttp2Connection in project netty by netty.

the class Http2FrameWriterBenchmark method boostrapEnvWithTransport.

private static Environment boostrapEnvWithTransport(final EnvironmentType environmentType) {
    final EnvironmentParameters params = environmentType.params();
    ServerBootstrap sb = new ServerBootstrap();
    Bootstrap cb = new Bootstrap();
    final TransportEnvironment environment = new TransportEnvironment(cb, sb);
    EventLoopGroup serverEventLoopGroup = params.newEventLoopGroup();
    sb.group(serverEventLoopGroup, serverEventLoopGroup);
    sb.channel(params.serverChannelClass());
    sb.option(ChannelOption.ALLOCATOR, params.serverAllocator());
    sb.childOption(ChannelOption.ALLOCATOR, params.serverAllocator());
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
        }
    });
    cb.group(params.newEventLoopGroup());
    cb.channel(params.clientChannelClass());
    cb.option(ChannelOption.ALLOCATOR, params.clientAllocator());
    final CountDownLatch latch = new CountDownLatch(1);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(false);
            Http2RemoteFlowController remoteFlowController = params.remoteFlowController();
            if (remoteFlowController != null) {
                connection.remote().flowController(params.remoteFlowController());
            }
            Http2LocalFlowController localFlowController = params.localFlowController();
            if (localFlowController != null) {
                connection.local().flowController(localFlowController);
            }
            environment.writer(new DefaultHttp2FrameWriter());
            Http2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, environment.writer());
            Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, new DefaultHttp2FrameReader());
            Http2ConnectionHandler connectionHandler = new Http2ConnectionHandlerBuilder().encoderEnforceMaxConcurrentStreams(false).frameListener(new Http2FrameAdapter()).codec(decoder, encoder).build();
            p.addLast(connectionHandler);
            environment.context(p.lastContext());
            // Must wait for context to be set.
            latch.countDown();
        }
    });
    environment.serverChannel(sb.bind(params.address()));
    params.address(environment.serverChannel().localAddress());
    environment.clientChannel(cb.connect(params.address()));
    try {
        if (!latch.await(5, SECONDS)) {
            throw new RuntimeException("Channel did not initialize in time");
        }
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
    return environment;
}
Also used : Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Connection(io.netty.handler.codec.http2.Http2Connection) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) DefaultHttp2ConnectionEncoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder) Http2RemoteFlowController(io.netty.handler.codec.http2.Http2RemoteFlowController) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) DefaultHttp2ConnectionDecoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder) Http2ConnectionHandlerBuilder(io.netty.handler.codec.http2.Http2ConnectionHandlerBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DefaultHttp2FrameReader(io.netty.handler.codec.http2.DefaultHttp2FrameReader) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) OioServerSocketChannel(io.netty.channel.socket.oio.OioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) OioSocketChannel(io.netty.channel.socket.oio.OioSocketChannel) Channel(io.netty.channel.Channel) DefaultHttp2ConnectionDecoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultHttp2FrameWriter(io.netty.handler.codec.http2.DefaultHttp2FrameWriter) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) Http2LocalFlowController(io.netty.handler.codec.http2.Http2LocalFlowController) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2ConnectionEncoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder)

Example 3 with DefaultHttp2Connection

use of io.netty.handler.codec.http2.DefaultHttp2Connection in project netty by netty.

the class Http2FrameWriterBenchmark method boostrapEmbeddedEnv.

private static Environment boostrapEmbeddedEnv(final EnvironmentType environmentType) {
    final ByteBufAllocator alloc = environmentType.params().clientAllocator();
    final EmbeddedEnvironment env = new EmbeddedEnvironment(new DefaultHttp2FrameWriter());
    final Http2Connection connection = new DefaultHttp2Connection(false);
    Http2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, env.writer());
    Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, new DefaultHttp2FrameReader());
    Http2ConnectionHandler connectionHandler = new Http2ConnectionHandlerBuilder().encoderEnforceMaxConcurrentStreams(false).frameListener(new Http2FrameAdapter()).codec(decoder, encoder).build();
    env.context(new EmbeddedChannelWriteReleaseHandlerContext(alloc, connectionHandler) {

        @Override
        protected void handleException(Throwable t) {
            handleUnexpectedException(t);
        }
    });
    return env;
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Connection(io.netty.handler.codec.http2.Http2Connection) DefaultHttp2ConnectionDecoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) DefaultHttp2FrameWriter(io.netty.handler.codec.http2.DefaultHttp2FrameWriter) DefaultHttp2ConnectionEncoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) DefaultHttp2ConnectionDecoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder) Http2ConnectionHandlerBuilder(io.netty.handler.codec.http2.Http2ConnectionHandlerBuilder) EmbeddedChannelWriteReleaseHandlerContext(io.netty.microbench.channel.EmbeddedChannelWriteReleaseHandlerContext) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2ConnectionEncoder(io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder) DefaultHttp2FrameReader(io.netty.handler.codec.http2.DefaultHttp2FrameReader)

Example 4 with DefaultHttp2Connection

use of io.netty.handler.codec.http2.DefaultHttp2Connection in project netty by netty.

the class DefaultHttp2ConnectionEncoderTest method setup.

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(channel.isActive()).thenReturn(true);
    when(channel.pipeline()).thenReturn(pipeline);
    when(writer.configuration()).thenReturn(writerConfig);
    when(writerConfig.frameSizePolicy()).thenReturn(frameSizePolicy);
    when(frameSizePolicy.maxFrameSize()).thenReturn(64);
    doAnswer(new Answer<ChannelFuture>() {

        @Override
        public ChannelFuture answer(InvocationOnMock in) throws Throwable {
            return ((ChannelPromise) in.getArguments()[2]).setSuccess();
        }
    }).when(writer).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class));
    doAnswer(new Answer<ChannelFuture>() {

        @Override
        public ChannelFuture answer(InvocationOnMock in) throws Throwable {
            ((ByteBuf) in.getArguments()[3]).release();
            return ((ChannelPromise) in.getArguments()[4]).setSuccess();
        }
    }).when(writer).writeGoAway(eq(ctx), anyInt(), anyInt(), any(ByteBuf.class), any(ChannelPromise.class));
    writtenData = new ArrayList<String>();
    writtenPadding = new ArrayList<Integer>();
    when(writer.writeData(eq(ctx), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean(), any(ChannelPromise.class))).then(new Answer<ChannelFuture>() {

        @Override
        public ChannelFuture answer(InvocationOnMock in) throws Throwable {
            // Make sure we only receive stream closure on the last frame and that void promises
            // are used for all writes except the last one.
            ChannelPromise promise = (ChannelPromise) in.getArguments()[5];
            if (streamClosed) {
                fail("Stream already closed");
            } else {
                streamClosed = (Boolean) in.getArguments()[4];
            }
            writtenPadding.add((Integer) in.getArguments()[3]);
            ByteBuf data = (ByteBuf) in.getArguments()[2];
            writtenData.add(data.toString(UTF_8));
            // Release the buffer just as DefaultHttp2FrameWriter does
            data.release();
            // Let the promise succeed to trigger listeners.
            return promise.setSuccess();
        }
    });
    when(writer.writeHeaders(eq(ctx), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(), any(ChannelPromise.class))).then(new Answer<ChannelFuture>() {

        @Override
        public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable {
            ChannelPromise promise = (ChannelPromise) invocationOnMock.getArguments()[8];
            if (streamClosed) {
                fail("Stream already closed");
            } else {
                streamClosed = (Boolean) invocationOnMock.getArguments()[5];
            }
            return promise.setSuccess();
        }
    });
    payloadCaptor = ArgumentCaptor.forClass(Http2RemoteFlowController.FlowControlled.class);
    doNothing().when(remoteFlow).addFlowControlled(any(Http2Stream.class), payloadCaptor.capture());
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ctx.channel()).thenReturn(channel);
    doAnswer(new Answer<ChannelPromise>() {

        @Override
        public ChannelPromise answer(InvocationOnMock in) throws Throwable {
            return newPromise();
        }
    }).when(ctx).newPromise();
    doAnswer(new Answer<ChannelFuture>() {

        @Override
        public ChannelFuture answer(InvocationOnMock in) throws Throwable {
            return newSucceededFuture();
        }
    }).when(ctx).newSucceededFuture();
    when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden"));
    when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT);
    // Use a server-side connection so we can test server push.
    connection = new DefaultHttp2Connection(true);
    connection.remote().flowController(remoteFlow);
    encoder = new DefaultHttp2ConnectionEncoder(connection, writer);
    encoder.lifecycleManager(lifecycleManager);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelPromise(io.netty.channel.ChannelPromise) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) FlowControlled(io.netty.handler.codec.http2.Http2RemoteFlowController.FlowControlled) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) AssertionFailedError(junit.framework.AssertionFailedError) Before(org.junit.Before)

Example 5 with DefaultHttp2Connection

use of io.netty.handler.codec.http2.DefaultHttp2Connection in project vert.x by eclipse.

the class Http2ServerTest method testPriorKnowledge.

@Test
public void testPriorKnowledge() throws Exception {
    server.close();
    server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
    server.requestHandler(req -> {
        req.response().end("Hello World");
    });
    startServer();
    TestClient client = new TestClient() {

        @Override
        protected ChannelInitializer channelInitializer(int port, String host, Consumer<Connection> handler) {
            return new ChannelInitializer() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    Http2Connection connection = new DefaultHttp2Connection(false);
                    TestClientHandlerBuilder clientHandlerBuilder = new TestClientHandlerBuilder(handler);
                    TestClientHandler clientHandler = clientHandlerBuilder.build(connection);
                    p.addLast(clientHandler);
                }
            };
        }
    };
    ChannelFuture fut = client.connect(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
                vertx.runOnContext(v -> {
                    testComplete();
                });
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Exception(io.netty.handler.codec.http2.Http2Exception) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Connection(io.netty.handler.codec.http2.Http2Connection) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPipeline(io.netty.channel.ChannelPipeline) BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Aggregations

DefaultHttp2Connection (io.netty.handler.codec.http2.DefaultHttp2Connection)10 Http2Connection (io.netty.handler.codec.http2.Http2Connection)8 Http2ConnectionDecoder (io.netty.handler.codec.http2.Http2ConnectionDecoder)5 Bootstrap (io.netty.bootstrap.Bootstrap)4 Channel (io.netty.channel.Channel)4 ChannelFuture (io.netty.channel.ChannelFuture)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 DefaultHttp2ConnectionEncoder (io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder)4 Http2ConnectionEncoder (io.netty.handler.codec.http2.Http2ConnectionEncoder)4 Http2ConnectionHandler (io.netty.handler.codec.http2.Http2ConnectionHandler)4 Http2FrameAdapter (io.netty.handler.codec.http2.Http2FrameAdapter)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 ByteBuf (io.netty.buffer.ByteBuf)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)3 Http2Settings (io.netty.handler.codec.http2.Http2Settings)3 Http2Stream (io.netty.handler.codec.http2.Http2Stream)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2