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 testPostFileUpload() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {/*from  ww w  .ja  v  a2s.  c  om*/
        Buffer tot = Buffer.buffer();
        req.setExpectMultipart(true);
        req.uploadHandler(upload -> {
            assertOnIOContext(ctx);
            assertEquals("file", upload.name());
            assertEquals("tmp-0.txt", upload.filename());
            assertEquals("image/gif", upload.contentType());
            upload.handler(tot::appendBuffer);
            upload.endHandler(v -> {
                assertEquals(tot, Buffer.buffer("some-content"));
                testComplete();
            });
        });
        req.endHandler(v -> {
            assertEquals(0, req.formAttributes().size());
            req.response().putHeader("content-type", "text/plain").end("done");
        });
    });
    startServer(ctx);

    String contentType = "multipart/form-data; boundary=a4e41223-a527-49b6-ac1c-315d76be757e";
    String contentLength = "225";
    String body = "--a4e41223-a527-49b6-ac1c-315d76be757e\r\n"
            + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n"
            + "Content-Type: image/gif; charset=utf-8\r\n" + "Content-Length: 12\r\n" + "\r\n"
            + "some-content\r\n" + "--a4e41223-a527-49b6-ac1c-315d76be757e--\r\n";

    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("/form").set("content-type", contentType).set("content-length", contentLength), 0, false,
                request.context.newPromise());
        request.encoder.writeData(request.context, id, Buffer.buffer(body).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

@Test
public void testInvalidPostFileUpload() throws Exception {
    server.requestHandler(req -> {//  w  w  w  .j  a v a  2s. c  o  m
        req.setExpectMultipart(true);
        AtomicInteger errCount = new AtomicInteger();
        req.exceptionHandler(err -> {
            errCount.incrementAndGet();
        });
        req.endHandler(v -> {
            assertTrue(errCount.get() > 0);
            testComplete();
        });
    });
    startServer();

    String contentType = "multipart/form-data; boundary=a4e41223-a527-49b6-ac1c-315d76be757e";
    String contentLength = "225";
    String body = "--a4e41223-a527-49b6-ac1c-315d76be757e\r\n"
            + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n"
            + "Content-Type: image/gif; charset=ABCD\r\n" + "Content-Length: 12\r\n" + "\r\n"
            + "some-content\r\n" + "--a4e41223-a527-49b6-ac1c-315d76be757e--\r\n";

    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("/form").set("content-type", contentType).set("content-length", contentLength), 0, false,
                request.context.newPromise());
        request.encoder.writeData(request.context, id, Buffer.buffer(body).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

@Test
public void testConnect() throws Exception {
    server.requestHandler(req -> {//w  ww . j  a va  2s  .  com
        assertEquals(HttpMethod.CONNECT, req.method());
        assertEquals("whatever.com", req.host());
        assertNull(req.path());
        assertNull(req.query());
        assertNull(req.scheme());
        assertNull(req.uri());
        assertNull(req.absoluteURI());
        testComplete();
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2Headers headers = new DefaultHttp2Headers().method("CONNECT").authority("whatever.com");
        request.encoder.writeHeaders(request.context, id, headers, 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 testStreamPauseResume(Function<HttpServerRequest, ReadStream<Buffer>> streamProvider)
        throws Exception {
    Buffer expected = Buffer.buffer();
    String chunk = TestUtils.randomAlphaString(1000);
    AtomicBoolean done = new AtomicBoolean();
    AtomicBoolean paused = new AtomicBoolean();
    Buffer received = Buffer.buffer();
    server.requestHandler(req -> {//from  w w w. j  a v  a2 s.c  o  m
        ReadStream<Buffer> stream = streamProvider.apply(req);
        vertx.setPeriodic(1, timerID -> {
            if (paused.get()) {
                vertx.cancelTimer(timerID);
                done.set(true);
                // Let some time to accumulate some more buffers
                vertx.setTimer(100, id -> {
                    stream.resume();
                });
            }
        });
        stream.handler(received::appendBuffer);
        stream.endHandler(v -> {
            assertEquals(expected, received);
            testComplete();
        });
        stream.pause();
    });
    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("/form").set("content-type", "text/plain"), 0,
                false, request.context.newPromise());
        request.context.flush();
        Http2Stream stream = request.connection.stream(id);
        class Anonymous {
            void send() {
                boolean writable = request.encoder.flowController().isWritable(stream);
                if (writable) {
                    Buffer buf = Buffer.buffer(chunk);
                    expected.appendBuffer(buf);
                    request.encoder.writeData(request.context, id, buf.getByteBuf(), 0, false,
                            request.context.newPromise());
                    request.context.flush();
                    request.context.executor().execute(this::send);
                } else {
                    request.encoder.writeData(request.context, id, Unpooled.EMPTY_BUFFER, 0, true,
                            request.context.newPromise());
                    request.context.flush();
                    paused.set(true);
                }
            }
        }
        new Anonymous().send();
    });
    fut.sync();
    await();
}

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

License:Open Source License

private void testStreamWritability(Function<HttpServerRequest, WriteStream<Buffer>> streamProvider)
        throws Exception {
    Context ctx = vertx.getOrCreateContext();
    String content = TestUtils.randomAlphaString(1024);
    StringBuilder expected = new StringBuilder();
    Future<Void> whenFull = Future.future();
    AtomicBoolean drain = new AtomicBoolean();
    server.requestHandler(req -> {/*  ww w  .  java2  s.  co m*/
        WriteStream<Buffer> stream = streamProvider.apply(req);
        vertx.setPeriodic(1, timerID -> {
            if (stream.writeQueueFull()) {
                stream.drainHandler(v -> {
                    assertOnIOContext(ctx);
                    expected.append("last");
                    stream.end(Buffer.buffer("last"));
                });
                vertx.cancelTimer(timerID);
                drain.set(true);
                whenFull.complete();
            } else {
                expected.append(content);
                Buffer buf = Buffer.buffer(content);
                stream.write(buf);
            }
        });
    });
    startServer(ctx);

    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        AtomicInteger toAck = new AtomicInteger();
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.decoder.frameListener(new Http2FrameAdapter() {

            StringBuilder received = new StringBuilder();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                received.append(data.toString(StandardCharsets.UTF_8));
                int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream);
                if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals(expected.toString(), received.toString());
                        testComplete();
                    });
                    return delta;
                } else {
                    if (drain.get()) {
                        return delta;
                    } else {
                        toAck.getAndAdd(delta);
                        return 0;
                    }
                }
            }
        });
        whenFull.setHandler(ar -> {
            request.context.executor().execute(() -> {
                try {
                    request.decoder.flowController().consumeBytes(request.connection.stream(id),
                            toAck.intValue());
                    request.context.flush();
                } catch (Http2Exception e) {
                    e.printStackTrace();
                    fail(e);
                }
            });
        });
    });

    fut.sync();

    await();
}

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

License:Open Source License

@Test
public void testTrailers() throws Exception {
    server.requestHandler(req -> {/*from   w w  w  . ja v  a2 s .c  om*/
        HttpServerResponse resp = req.response();
        resp.setChunked(true);
        resp.write("some-content");
        resp.putTrailer("Foo", "foo_value");
        resp.putTrailer("bar", "bar_value");
        resp.putTrailer("juu", (List<String>) Arrays.asList("juu_value_1", "juu_value_2"));
        resp.end();
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {
            int count;

            @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 -> {
                        assertFalse(endStream);
                    });
                    break;
                case 1:
                    vertx.runOnContext(v -> {
                        assertEquals("foo_value", headers.get("foo").toString());
                        assertEquals(1, headers.getAll("foo").size());
                        assertEquals("foo_value", headers.getAll("foo").get(0).toString());
                        assertEquals("bar_value", headers.getAll("bar").get(0).toString());
                        assertEquals(2, headers.getAll("juu").size());
                        assertEquals("juu_value_1", headers.getAll("juu").get(0).toString());
                        assertEquals("juu_value_2", headers.getAll("juu").get(1).toString());
                        assertTrue(endStream);
                        testComplete();
                    });
                    break;
                default:
                    vertx.runOnContext(v -> {
                        fail();
                    });
                    break;
                }
            }
        });
        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 testServerResetClientStream() throws Exception {
    server.requestHandler(req -> {/*from w ww . j  a  va2s  .c o m*/
        req.handler(buf -> {
            req.response().reset(8);
        });
    });
    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 onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals(8, errorCode);
                    testComplete();
                });
            }
        });
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        encoder.writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 0, false,
                request.context.newPromise());
    });

    fut.sync();

    await();
}

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

License:Open Source License

@Test
public void testClientResetServerStream() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    Future<Void> bufReceived = Future.future();
    AtomicInteger resetCount = new AtomicInteger();
    server.requestHandler(req -> {//from   w w w .  j a  va  2s .c  o m
        req.handler(buf -> {
            bufReceived.complete();
        });
        req.exceptionHandler(err -> {
            assertOnIOContext(ctx);
            if (err instanceof StreamResetException) {
                assertEquals(10L, ((StreamResetException) err).getCode());
                assertEquals(0, resetCount.getAndIncrement());
            }
        });
        req.response().exceptionHandler(err -> {
            assertOnIOContext(ctx);
            if (err instanceof StreamResetException) {
                assertEquals(10L, ((StreamResetException) err).getCode());
                assertEquals(1, resetCount.getAndIncrement());
                testComplete();
            }
        });
    });
    startServer(ctx);

    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        encoder.writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 0, false,
                request.context.newPromise());
        bufReceived.setHandler(ar -> {
            encoder.writeRstStream(request.context, id, 10, 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 testConnectionClose() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {//  w  w w .  j  a v  a 2 s .  c  o m
        HttpConnection conn = req.connection();
        conn.closeHandler(v -> {
            assertSame(ctx, Vertx.currentContext());
            testComplete();
        });
        req.response().putHeader("Content-Type", "text/plain").end();
    });
    startServer(ctx);

    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.decoder.frameListener(new Http2FrameAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                request.context.close();
            }
        });
    });
    fut.sync();
    await();
}

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

License:Open Source License

private void testPushPromise(Http2Headers requestHeaders,
        BiConsumer<HttpServerResponse, Handler<AsyncResult<HttpServerResponse>>> pusher,
        Consumer<Http2Headers> headerChecker) throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {/*from w w  w  .j av  a2s  .c o m*/
        Handler<AsyncResult<HttpServerResponse>> handler = ar -> {
            assertSame(ctx, Vertx.currentContext());
            assertTrue(ar.succeeded());
            HttpServerResponse response = ar.result();
            response./*putHeader("content-type", "application/plain").*/end("the_content");
            assertIllegalStateException(() -> response.push(HttpMethod.GET, "/wibble2", resp -> {
            }));
        };
        pusher.accept(req.response(), handler);
    });
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, requestHeaders, 0, true, request.context.newPromise());
        Map<Integer, Http2Headers> pushed = new HashMap<>();
        request.decoder.frameListener(new Http2FrameAdapter() {
            @Override
            public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
                    Http2Headers headers, int padding) throws Http2Exception {
                pushed.put(promisedStreamId, headers);
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream);
                String content = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(Collections.singleton(streamId), pushed.keySet());
                    assertEquals("the_content", content);
                    Http2Headers pushedHeaders = pushed.get(streamId);
                    headerChecker.accept(pushedHeaders);
                    testComplete();
                });
                return delta;
            }
        });
    });
    fut.sync();
    await();
}