Example usage for io.netty.channel ChannelFuture sync

List of usage examples for io.netty.channel ChannelFuture sync

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture sync.

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

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

License:Open Source License

@Test
public void testServerClose() throws Exception {
    waitFor(2);/* ww  w . ja  va 2 s .  c o m*/
    AtomicInteger status = new AtomicInteger();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        conn.shutdownHandler(v -> {
            assertEquals(0, status.getAndIncrement());
        });
        conn.closeHandler(v -> {
            assertEquals(1, status.getAndIncrement());
            complete();
        });
        conn.close();
    };
    server.requestHandler(requestHandler);
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.channel.closeFuture().addListener(v1 -> {
            vertx.runOnContext(v2 -> {
                complete();
            });
        });
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode,
                    ByteBuf debugData) throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals(0, errorCode);
                });
            }
        });
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();

    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testClientSendGoAwayNoError() throws Exception {
    Future<Void> abc = Future.future();
    Context ctx = vertx.getOrCreateContext();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        AtomicInteger numShutdown = new AtomicInteger();
        AtomicBoolean completed = new AtomicBoolean();
        conn.shutdownHandler(v -> {//from   w ww. ja  v  a 2s.c  om
            assertOnIOContext(ctx);
            numShutdown.getAndIncrement();
            vertx.setTimer(100, timerID -> {
                // Delay so we can check the connection is not closed
                completed.set(true);
                testComplete();
            });
        });
        conn.goAwayHandler(ga -> {
            assertOnIOContext(ctx);
            assertEquals(0, numShutdown.get());
            req.response().end();
        });
        conn.closeHandler(v -> {
            assertTrue(completed.get());
        });
        abc.complete();
    };
    server.requestHandler(requestHandler);
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
        abc.setHandler(ar -> {
            encoder.writeGoAway(request.context, id, 0, Unpooled.EMPTY_BUFFER, request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testClientSendGoAwayInternalError() throws Exception {
    Future<Void> abc = Future.future();
    Context ctx = vertx.getOrCreateContext();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        AtomicInteger status = new AtomicInteger();
        conn.goAwayHandler(ga -> {/*from   w  ww.j a  v a  2  s . co m*/
            assertOnIOContext(ctx);
            assertEquals(0, status.getAndIncrement());
            req.response().end();
        });
        conn.shutdownHandler(v -> {
            assertOnIOContext(ctx);
            assertEquals(1, status.getAndIncrement());
        });
        conn.closeHandler(v -> {
            assertEquals(2, status.getAndIncrement());
            testComplete();
        });
        abc.complete();
    };
    server.requestHandler(requestHandler);
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
        abc.setHandler(ar -> {
            encoder.writeGoAway(request.context, id, 3, Unpooled.EMPTY_BUFFER, request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testShutdownOverride() throws Exception {
    AtomicLong shutdown = new AtomicLong();
    Handler<HttpServerRequest> requestHandler = req -> {
        HttpConnection conn = req.connection();
        shutdown.set(System.currentTimeMillis());
        conn.shutdown(10000);/* w  ww . j a  v a  2s .co m*/
        vertx.setTimer(300, v -> {
            conn.shutdown(300);
        });
    };
    server.requestHandler(requestHandler);
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.channel.closeFuture().addListener(v1 -> {
            vertx.runOnContext(v2 -> {
                assertTrue(shutdown.get() - System.currentTimeMillis() < 1200);
                testComplete();
            });
        });
        Http2ConnectionEncoder encoder = request.encoder;
        int id = request.nextStreamId();
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testRequestResponseLifecycle() throws Exception {
    waitFor(2);/*from w w  w  .jav  a  2s. c om*/
    server.requestHandler(req -> {
        req.endHandler(v -> {
            assertIllegalStateException(() -> req.setExpectMultipart(false));
            assertIllegalStateException(() -> req.handler(buf -> {
            }));
            assertIllegalStateException(() -> req.uploadHandler(upload -> {
            }));
            assertIllegalStateException(() -> req.endHandler(v2 -> {
            }));
            complete();
        });
        HttpServerResponse resp = req.response();
        resp.setChunked(true).write(Buffer.buffer("whatever"));
        assertTrue(resp.headWritten());
        assertIllegalStateException(() -> resp.setChunked(false));
        assertIllegalStateException(() -> resp.setStatusCode(100));
        assertIllegalStateException(() -> resp.setStatusMessage("whatever"));
        assertIllegalStateException(() -> resp.putHeader("a", "b"));
        assertIllegalStateException(() -> resp.putHeader("a", (CharSequence) "b"));
        assertIllegalStateException(() -> resp.putHeader("a", (Iterable<String>) Arrays.asList("a", "b")));
        assertIllegalStateException(() -> resp.putHeader("a", (Arrays.<CharSequence>asList("a", "b"))));
        assertIllegalStateException(resp::writeContinue);
        resp.end();
        assertIllegalStateException(() -> resp.write("a"));
        assertIllegalStateException(() -> resp.write("a", "UTF-8"));
        assertIllegalStateException(() -> resp.write(Buffer.buffer("a")));
        assertIllegalStateException(resp::end);
        assertIllegalStateException(() -> resp.end("a"));
        assertIllegalStateException(() -> resp.end("a", "UTF-8"));
        assertIllegalStateException(() -> resp.end(Buffer.buffer("a")));
        assertIllegalStateException(() -> resp.sendFile("the-file.txt"));
        assertIllegalStateException(() -> resp.reset(0));
        assertIllegalStateException(() -> resp.closeHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.endHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.drainHandler(v -> {
        }));
        assertIllegalStateException(() -> resp.exceptionHandler(err -> {
        }));
        assertIllegalStateException(resp::writeQueueFull);
        assertIllegalStateException(() -> resp.setWriteQueueMaxSize(100));
        assertIllegalStateException(() -> resp.putTrailer("a", "b"));
        assertIllegalStateException(() -> resp.putTrailer("a", (CharSequence) "b"));
        assertIllegalStateException(() -> resp.putTrailer("a", (Iterable<String>) Arrays.asList("a", "b")));
        assertIllegalStateException(() -> resp.putTrailer("a", (Arrays.<CharSequence>asList("a", "b"))));
        assertIllegalStateException(() -> resp.push(HttpMethod.GET, "/whatever", ar -> {
        }));
        complete();
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testResponseCompressionDisabled() throws Exception {
    waitFor(2);/*from   w ww  . j av  a  2 s.c o  m*/
    String expected = TestUtils.randomAlphaString(1000);
    server.requestHandler(req -> {
        req.response().end(expected);
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_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 -> {
                    assertEquals(null, headers.get(HttpHeaderNames.CONTENT_ENCODING));
                    complete();
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                String s = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(expected, s);
                    complete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testResponseCompressionEnabled() throws Exception {
    waitFor(2);//  w w w  .  j  a  v a2s.co  m
    String expected = TestUtils.randomAlphaString(1000);
    server.close();
    server = vertx.createHttpServer(serverOptions.setCompressionSupported(true));
    server.requestHandler(req -> {
        req.response().end(expected);
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_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 -> {
                    assertEquals("gzip", headers.get(HttpHeaderNames.CONTENT_ENCODING).toString());
                    complete();
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                byte[] bytes = new byte[data.readableBytes()];
                data.readBytes(bytes);
                vertx.runOnContext(v -> {
                    String decoded;
                    try {
                        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bytes));
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while (true) {
                            int i = in.read();
                            if (i == -1) {
                                break;
                            }
                            baos.write(i);
                            ;
                        }
                        decoded = baos.toString();
                    } catch (IOException e) {
                        fail(e);
                        return;
                    }
                    assertEquals(expected, decoded);
                    complete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void testRequestCompressionEnabled() throws Exception {
    String expected = TestUtils.randomAlphaString(1000);
    byte[] expectedGzipped = TestUtils.compressGzip(expected);
    server.close();//ww  w .  j a v a 2  s. co  m
    server = vertx.createHttpServer(serverOptions.setDecompressionSupported(true));
    server.requestHandler(req -> {
        StringBuilder postContent = new StringBuilder();
        req.handler(buff -> {
            postContent.append(buff.toString());
        });
        req.endHandler(v -> {
            req.response().putHeader("content-type", "text/plain").end("");
            assertEquals(expected, postContent.toString());
            testComplete();
        });
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, POST("/").add("content-encoding", "gzip"), 0, false,
                request.context.newPromise());
        request.encoder.writeData(request.context, id, Buffer.buffer(expectedGzipped).getByteBuf(), 0, true,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

private void test100Continue() throws Exception {
    startServer();/* w  w w . ja va  2 s  .c o m*/
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {
            int count = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                switch (count++) {
                case 0:
                    vertx.runOnContext(v -> {
                        assertEquals("100", headers.status().toString());
                    });
                    request.encoder.writeData(request.context, id, Buffer.buffer("the-body").getByteBuf(), 0,
                            true, request.context.newPromise());
                    request.context.flush();
                    break;
                case 1:
                    vertx.runOnContext(v -> {
                        assertEquals("200", headers.status().toString());
                        assertEquals("wibble-value", headers.get("wibble").toString());
                        testComplete();
                    });
                    break;
                default:
                    vertx.runOnContext(v -> {
                        fail();
                    });
                }
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/").add("expect", "100-continue"), 0, false,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

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

License:Open Source License

@Test
public void test100ContinueRejectedManually() throws Exception {
    server.requestHandler(req -> {/*from  w  ww  . ja va2 s  .c om*/
        req.response().setStatusCode(405).end();
        req.handler(buf -> {
            fail();
        });
    });
    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() {
            int count = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                switch (count++) {
                case 0:
                    vertx.runOnContext(v -> {
                        assertEquals("405", headers.status().toString());
                        vertx.setTimer(100, v2 -> {
                            testComplete();
                        });
                    });
                    break;
                default:
                    vertx.runOnContext(v -> {
                        fail();
                    });
                }
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/").add("expect", "100-continue"), 0, false,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}