Search in sources :

Example 66 with DefaultHttp2Headers

use of io.netty.handler.codec.http2.DefaultHttp2Headers in project grpc-java by grpc.

the class GrpcHttp2HeadersDecoderTest method decode_responseHeaders.

@Test
public void decode_responseHeaders() throws Http2Exception {
    Http2HeadersDecoder decoder = new GrpcHttp2ClientHeadersDecoder(DEFAULT_MAX_HEADER_LIST_SIZE);
    Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE);
    Http2Headers headers = new DefaultHttp2Headers(false);
    headers.add(of(":status"), of("200")).add(of("custom"), of("header"));
    encodedHeaders = Unpooled.buffer();
    encoder.encodeHeaders(1, /* randomly chosen */
    headers, encodedHeaders);
    Http2Headers decodedHeaders = decoder.decodeHeaders(3, /* randomly chosen */
    encodedHeaders);
    assertEquals(headers.get(of(":status")), decodedHeaders.get(of(":status")));
    assertEquals(headers.get(of("custom")), decodedHeaders.get(of("custom")));
    assertEquals(headers.size(), decodedHeaders.size());
    String toString = decodedHeaders.toString();
    assertContainsKeyAndValue(toString, ":status", decodedHeaders.get(of(":status")));
    assertContainsKeyAndValue(toString, "custom", decodedHeaders.get(of("custom")));
}
Also used : DefaultHttp2HeadersEncoder(io.netty.handler.codec.http2.DefaultHttp2HeadersEncoder) Http2HeadersEncoder(io.netty.handler.codec.http2.Http2HeadersEncoder) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) GrpcHttp2ClientHeadersDecoder(io.grpc.netty.GrpcHttp2HeadersDecoder.GrpcHttp2ClientHeadersDecoder) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Http2HeadersDecoder(io.netty.handler.codec.http2.Http2HeadersDecoder) DefaultHttp2HeadersEncoder(io.netty.handler.codec.http2.DefaultHttp2HeadersEncoder) Test(org.junit.Test)

Example 67 with DefaultHttp2Headers

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

the class ReadOnlyHttp2HeadersBenchmark method defaultClientHeaders.

@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int defaultClientHeaders() {
    Http2Headers headers = new DefaultHttp2Headers(false);
    for (int i = 0; i < headerCount; ++i) {
        headers.add(headerNames[i], headerValues[i]);
    }
    headers.method(HttpMethod.POST.asciiName());
    headers.scheme(HttpScheme.HTTPS.name());
    headers.path(path);
    headers.authority(authority);
    return iterate(headers);
}
Also used : ReadOnlyHttp2Headers(io.netty.handler.codec.http2.ReadOnlyHttp2Headers) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) BenchmarkMode(org.openjdk.jmh.annotations.BenchmarkMode) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 68 with DefaultHttp2Headers

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

the class InboundHttp2ToHttpAdapterTest method clientRequestMultipleHeaders.

@Test
public void clientRequestMultipleHeaders() throws Exception {
    boostrapEnv(1, 1, 1);
    // writeHeaders will implicitly add an END_HEADERS tag each time and so this test does not follow the HTTP
    // message flow. We currently accept this message flow and just add the second headers to the trailing headers.
    final String text = "";
    final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        HttpHeaders trailingHeaders = request.trailingHeaders();
        trailingHeaders.set(of("FoO"), of("goo"));
        trailingHeaders.set(of("foO2"), of("goo2"));
        trailingHeaders.add(of("fOo2"), of("goo3"));
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/some/path/resource2"));
        final Http2Headers http2Headers2 = new DefaultHttp2Headers().set(new AsciiString("foo"), new AsciiString("goo")).set(new AsciiString("foo2"), new AsciiString("goo2")).add(new AsciiString("foo2"), new AsciiString("goo3"));
        runInChannel(clientChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, false, newPromiseClient());
                clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
    } finally {
        request.release();
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Http2CodecUtil.getEmbeddedHttp2Exception(io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) FullHttpMessage(io.netty.handler.codec.http.FullHttpMessage) AsciiString(io.netty.util.AsciiString) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 69 with DefaultHttp2Headers

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

the class Http2ServerTest method testNetSocketConnect.

@Test
public void testNetSocketConnect() throws Exception {
    waitFor(2);
    List<Integer> callbacks = Collections.synchronizedList(new ArrayList<>());
    server.requestHandler(req -> {
        req.toNetSocket().onComplete(onSuccess(socket -> {
            AtomicInteger status = new AtomicInteger();
            socket.handler(buff -> {
                switch(status.getAndIncrement()) {
                    case 0:
                        assertEquals(Buffer.buffer("some-data"), buff);
                        socket.write(buff, onSuccess(v2 -> callbacks.add(0)));
                        break;
                    case 1:
                        assertEquals(Buffer.buffer("last-data"), buff);
                        break;
                    default:
                        fail();
                        break;
                }
            });
            socket.endHandler(v1 -> {
                assertEquals(2, status.getAndIncrement());
                socket.write(Buffer.buffer("last-data"), onSuccess(v2 -> callbacks.add(1)));
            });
            socket.closeHandler(v -> {
                assertEquals(2, callbacks.size());
                assertEquals(Arrays.asList(0, 1), callbacks);
                complete();
            });
        }));
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        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 -> {
                    assertEquals("200", headers.status().toString());
                    assertFalse(endStream);
                });
                request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0, false, request.context.newPromise());
                request.context.flush();
            }

            StringBuilder received = new StringBuilder();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                String s = data.toString(StandardCharsets.UTF_8);
                received.append(s);
                if (received.toString().equals("some-data")) {
                    received.setLength(0);
                    vertx.runOnContext(v -> {
                        assertFalse(endOfStream);
                    });
                    request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0, true, request.context.newPromise());
                } else if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals("last-data", received.toString());
                        complete();
                    });
                }
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, new DefaultHttp2Headers().method("CONNECT").authority("example.com:80"), 0, false, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) 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) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) 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) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) 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) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) 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) HttpUtils(io.vertx.core.http.impl.HttpUtils) 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) ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Example 70 with DefaultHttp2Headers

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

the class Http2ClientTest method testStreamPriorityChange.

@Test
public void testStreamPriorityChange() throws Exception {
    StreamPriority requestStreamPriority = new StreamPriority().setDependency(123).setWeight((short) 45).setExclusive(true);
    StreamPriority requestStreamPriority2 = new StreamPriority().setDependency(223).setWeight((short) 145).setExclusive(false);
    StreamPriority responseStreamPriority = new StreamPriority().setDependency(153).setWeight((short) 75).setExclusive(false);
    StreamPriority responseStreamPriority2 = new StreamPriority().setDependency(253).setWeight((short) 175).setExclusive(true);
    waitFor(5);
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> 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 -> {
                assertEquals(requestStreamPriority.getDependency(), streamDependency);
                assertEquals(requestStreamPriority.getWeight(), weight);
                assertEquals(requestStreamPriority.isExclusive(), exclusive);
                assertFalse(endStream);
                complete();
            });
        }

        @Override
        public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight, boolean exclusive) throws Http2Exception {
            vertx.runOnContext(v -> {
                assertEquals(requestStreamPriority2.getDependency(), streamDependency);
                assertEquals(requestStreamPriority2.getWeight(), weight);
                assertEquals(requestStreamPriority2.isExclusive(), exclusive);
                complete();
            });
        }

        @Override
        public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
            if (endOfStream) {
                encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), responseStreamPriority.getDependency(), responseStreamPriority.getWeight(), responseStreamPriority.isExclusive(), 0, false, ctx.newPromise());
                ctx.flush();
                encoder.writePriority(ctx, streamId, responseStreamPriority2.getDependency(), responseStreamPriority2.getWeight(), responseStreamPriority2.isExclusive(), ctx.newPromise());
                ctx.flush();
                encoder.writeData(ctx, streamId, Buffer.buffer("hello").getByteBuf(), 0, true, ctx.newPromise());
                ctx.flush();
                vertx.runOnContext(v -> {
                    complete();
                });
            }
            return super.onDataRead(ctx, streamId, data, padding, endOfStream);
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        client.request(new RequestOptions().setPort(DEFAULT_HTTPS_PORT).setHost(DEFAULT_HTTPS_HOST).setURI("/somepath")).onComplete(onSuccess(req -> {
            req.response(onSuccess(resp -> {
                assertEquals(responseStreamPriority, resp.request().getStreamPriority());
                Context ctx = vertx.getOrCreateContext();
                assertOnIOContext(ctx);
                resp.streamPriorityHandler(streamPriority -> {
                    assertOnIOContext(ctx);
                    assertEquals(responseStreamPriority2, streamPriority);
                    assertEquals(responseStreamPriority2, resp.request().getStreamPriority());
                    complete();
                });
                resp.endHandler(v -> {
                    assertOnIOContext(ctx);
                    assertEquals(responseStreamPriority2, resp.request().getStreamPriority());
                    complete();
                });
            })).setStreamPriority(requestStreamPriority);
            req.sendHead(h -> {
                req.setStreamPriority(requestStreamPriority2);
                req.end();
            });
        }));
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : Arrays(java.util.Arrays) io.netty.handler.codec.http2(io.netty.handler.codec.http2) BiFunction(java.util.function.BiFunction) MultiMap(io.vertx.core.MultiMap) AsciiString(io.netty.util.AsciiString) Context(io.vertx.core.Context) HttpClientConnection(io.vertx.core.http.impl.HttpClientConnection) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Cert(io.vertx.test.tls.Cert) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Assume(org.junit.Assume) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) AtomicLong(java.util.concurrent.atomic.AtomicLong) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelFuture(io.netty.channel.ChannelFuture) Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Aggregations

DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)72 Http2Headers (io.netty.handler.codec.http2.Http2Headers)58 AsciiString (io.netty.util.AsciiString)56 ByteBuf (io.netty.buffer.ByteBuf)54 Test (org.junit.Test)49 Test (org.junit.jupiter.api.Test)32 ChannelFuture (io.netty.channel.ChannelFuture)27 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)19 ChannelPromise (io.netty.channel.ChannelPromise)17 Channel (io.netty.channel.Channel)16 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)15 List (java.util.List)15 ChannelInitializer (io.netty.channel.ChannelInitializer)14 ChannelPipeline (io.netty.channel.ChannelPipeline)14 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)14 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)14 Http2Runnable (io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable)14 ApplicationProtocolNames (io.netty.handler.ssl.ApplicationProtocolNames)14 ApplicationProtocolNegotiationHandler (io.netty.handler.ssl.ApplicationProtocolNegotiationHandler)14