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

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

Introduction

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

Prototype

Http2EventAdapter

Source Link

Usage

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

License:Apache License

@Test
public void maxFrameSize() throws Exception {

    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();

        final ClientFactory clientFactory = new ClientFactoryBuilder().useHttp2Preface(true)
                .http2MaxFrameSize(DEFAULT_MAX_FRAME_SIZE * 2) // == 16384 * 2
                .build();/*from   w w w  .  j a  va  2s .c  om*/

        final HttpClient client = HttpClient.of(clientFactory, "http://127.0.0.1:" + port);
        final CompletableFuture<AggregatedHttpMessage> future = client.get("/").aggregate();

        try (Socket s = ss.accept()) {
            final InputStream in = s.getInputStream();
            final BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());

            readBytes(in, connectionPrefaceBuf().capacity()); // Read the connection preface and discard it.

            // Read a SETTINGS frame and validate it.
            assertSettingsFrameOfMaxFrameSize(in);

            sendEmptySettingsAndAckFrame(bos);

            readBytes(in, 9); // Read a SETTINGS_ACK frame and discard it.
            readHeadersFrame(in); // Read a HEADERS frame and discard it.

            sendHeaderFrame(bos);

            ////////////////////////////////////////
            // Transmission of data gets started. //
            ////////////////////////////////////////

            // Send a DATA frame that indicates sending data as much as 0x8000 for stream id 03.
            bos.write(new byte[] { 0x00, (byte) 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 });
            bos.write(EMPTY_DATA);
            bos.write(EMPTY_DATA);
            bos.flush();

            readBytes(in, 13); // Read a WINDOW_UPDATE frame for connection and discard it.
            readBytes(in, 13); // Read a WINDOW_UPDATE frame for stream id 03 and discard it.

            // Send a DATA frame that exceed MAX_FRAME_SIZE by 1.
            bos.write(new byte[] { 0x00, (byte) 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 });
            bos.flush(); // Triggers the client to send a GOAWAY frame for the connection.

            // The client send a GOAWAY frame and the server read it.
            final ByteBuf buffer = readGoAwayFrame(in);
            final DefaultHttp2FrameReader frameReader = new DefaultHttp2FrameReader();

            final CountDownLatch latch = new CountDownLatch(1);
            frameReader.readFrame(null, buffer, new Http2EventAdapter() {
                @Override
                public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode,
                        ByteBuf debugData) throws Http2Exception {
                    assertThat(lastStreamId).isZero(); // 0: connection error
                    assertThat(errorCode).isEqualTo(Http2Error.FRAME_SIZE_ERROR.code());
                    latch.countDown();
                }
            });
            latch.await();
            buffer.release();
        }
    }
}

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

License:Open Source License

@Test
public void testGet() throws Exception {
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> new Http2EventAdapter() {
        @Override/*from   www  . ja va 2  s .c o  m*/
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            vertx.runOnContext(v -> {
                assertTrue(endStream);
                encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true,
                        ctx.newPromise());
                ctx.flush();
            });
        }

        @Override
        public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
                throws Http2Exception {
            vertx.runOnContext(v -> {
                testComplete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        client.getNow(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
            Context ctx = vertx.getOrCreateContext();
            assertOnIOContext(ctx);
            resp.endHandler(v -> {
                assertOnIOContext(ctx);
                resp.request().connection().close();
            });
        }));
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

@Test
public void testStreamError() throws Exception {
    waitFor(3);//from  w w w .  j  a  v  a2s . c o  m
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false,
                    ctx.newPromise());
            // Send a corrupted frame on purpose to check we get the corresponding error in the request exception handler
            // the error is : greater padding value 0c -> 1F
            // ChannelFuture a = encoder.frameWriter().writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 12, false, request.context.newPromise());
            // normal frame    : 00 00 12 00 08 00 00 00 03 0c 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            // corrupted frame : 00 00 12 00 08 00 00 00 03 1F 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            ctx.channel()
                    .write(Buffer.buffer(new byte[] { 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x00, 0x00,
                            (byte) (streamId & 0xFF), 0x1F, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00,
                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).getByteBuf());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            })).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

@Test
public void testConnectionDecodeError() throws Exception {
    waitFor(3);//from  w w  w . j  a va 2  s. c o m
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false,
                    ctx.newPromise());
            enc.frameWriter().writeRstStream(ctx, 10, 0, ctx.newPromise());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            })).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertSame(ctx, Vertx.currentContext());
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

@Test
public void testInvalidServerResponse() throws Exception {
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override//from  w ww . j a  v  a 2s . com
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("xyz"), 0, false,
                    ctx.newPromise());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onFailure(err -> {
                assertOnIOContext(ctx);
                if (err instanceof NumberFormatException) {
                    testComplete();
                }
            })).connectionHandler(conn -> conn.exceptionHandler(err -> fail())).end();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

private void testClearText(boolean upgrade) throws Exception {
    ServerBootstrap bootstrap = createH2CServer((dec, enc) -> new Http2EventAdapter() {
        @Override/*from  w  w  w  .  j  av  a 2 s.  com*/
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }
    }, upgrade);
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT).sync();
    try {
        client.close();
        client = vertx.createHttpClient(
                clientOptions.setUseAlpn(false).setSsl(false).setHttp2ClearTextUpgrade(upgrade));
        client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", onSuccess(resp1 -> {
            HttpConnection conn = resp1.request().connection();
            assertEquals(HttpVersion.HTTP_2, resp1.version());
            client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", onSuccess(resp2 -> {
                assertSame(((HttpClientConnection) conn).channel(),
                        ((HttpClientConnection) resp2.request().connection()).channel());
                testComplete();
            })).exceptionHandler(this::fail).end();
        })).exceptionHandler(this::fail).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

@Test
public void testConnectionWindowSize() throws Exception {
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> new Http2EventAdapter() {
        @Override//from  w w w .j a v a 2  s  . co  m
        public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
                throws Http2Exception {
            vertx.runOnContext(v -> {
                assertEquals(65535, windowSizeIncrement);
                testComplete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    client.close();
    client = vertx
            .createHttpClient(new HttpClientOptions(clientOptions).setHttp2ConnectionWindowSize(65535 * 2));
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
    }).end();
    await();
}

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

License:Open Source License

@Test
public void testUpdateConnectionWindowSize() throws Exception {
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> new Http2EventAdapter() {
        @Override/*from w w w. j  a v  a2  s  .c  o m*/
        public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
                throws Http2Exception {
            vertx.runOnContext(v -> {
                assertEquals(65535, windowSizeIncrement);
                testComplete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
    }).connectionHandler(conn -> {
        assertEquals(65535, conn.getWindowSize());
        conn.setWindowSize(65535 + 10000);
        assertEquals(65535 + 10000, conn.getWindowSize());
        conn.setWindowSize(65535 + 65535);
        assertEquals(65535 + 65535, conn.getWindowSize());
    }).end();
    await();
}

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

License:Open Source License

@Test
public void testStreamPriority() throws Exception {
    StreamPriority requestStreamPriority = new StreamPriority().setDependency(123).setWeight((short) 45)
            .setExclusive(true);/*from  w w  w.j a  va 2s .  c o  m*/
    StreamPriority responseStreamPriority = new StreamPriority().setDependency(153).setWeight((short) 75)
            .setExclusive(false);
    waitFor(2);
    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);
                encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"),
                        responseStreamPriority.getDependency(), responseStreamPriority.getWeight(),
                        responseStreamPriority.isExclusive(), 0, true, ctx.newPromise());
                ctx.flush();
                if (endStream)
                    complete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
            assertEquals(responseStreamPriority, resp.request().getStreamPriority());
            Context ctx = vertx.getOrCreateContext();
            assertOnIOContext(ctx);
            resp.endHandler(v -> {
                complete();
            });
        })).setStreamPriority(requestStreamPriority).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}

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

License:Open Source License

@Test
public void testStreamPriorityChange() throws Exception {
    StreamPriority requestStreamPriority = new StreamPriority().setDependency(123).setWeight((short) 45)
            .setExclusive(true);/* ww  w .  j  a  v  a 2s.  com*/
    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 {
        HttpClientRequest req = client
                .get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", 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();
    }
}