Search in sources :

Example 76 with Context

use of io.vertx.core.Context in project vert.x by eclipse.

the class Http2ServerTest method testStreamWritability.

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 -> {
        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();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Buffer(io.vertx.core.buffer.Buffer) 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) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder)

Example 77 with Context

use of io.vertx.core.Context in project vert.x by eclipse.

the class Http2ServerTest method testStreamError.

@Test
public void testStreamError() throws Exception {
    waitFor(5);
    Future<Void> when = Future.future();
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        req.exceptionHandler(err -> {
            assertEquals(ctx, Vertx.currentContext());
            complete();
        });
        req.response().exceptionHandler(err -> {
            assertEquals(ctx, Vertx.currentContext());
            complete();
        });
        req.response().closeHandler(v -> {
            assertEquals(ctx, Vertx.currentContext());
            complete();
        });
        req.response().endHandler(v -> {
            assertEquals(ctx, Vertx.currentContext());
            complete();
        });
        when.complete();
    });
    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());
        request.context.flush();
        when.setHandler(ar -> {
            request.channel.write(Buffer.buffer(new byte[] { 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x00, 0x00, (byte) (id & 0xFF), 0x1F, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).getByteBuf());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) Test(org.junit.Test)

Example 78 with Context

use of io.vertx.core.Context in project vert.x by eclipse.

the class Http2ServerTest method testResetPendingPushPromise.

@Test
public void testResetPendingPushPromise() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        req.response().push(HttpMethod.GET, "/wibble", ar -> {
            assertFalse(ar.succeeded());
            assertOnIOContext(ctx);
            testComplete();
        });
    });
    startServer(ctx);
    TestClient client = new TestClient();
    client.settings.maxConcurrentStreams(0);
    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 onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
                request.encoder.writeRstStream(request.context, promisedStreamId, Http2Error.CANCEL.code(), request.context.newPromise());
                request.context.flush();
            }
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Test(org.junit.Test)

Example 79 with Context

use of io.vertx.core.Context in project vert.x by eclipse.

the class Http2ServerTest method testConnectionClose.

@Test
public void testConnectionClose() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        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();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) HttpConnection(io.vertx.core.http.HttpConnection) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) Test(org.junit.Test)

Example 80 with Context

use of io.vertx.core.Context in project vert.x by eclipse.

the class Http2ServerTest method testClientSettings.

@Test
public void testClientSettings() throws Exception {
    Context ctx = vertx.getOrCreateContext();
    io.vertx.core.http.Http2Settings initialSettings = TestUtils.randomHttp2Settings();
    io.vertx.core.http.Http2Settings updatedSettings = TestUtils.randomHttp2Settings();
    Future<Void> settingsRead = Future.future();
    AtomicInteger count = new AtomicInteger();
    server.connectionHandler(conn -> {
        io.vertx.core.http.Http2Settings settings = conn.remoteSettings();
        assertEquals(true, settings.isPushEnabled());
        assertEquals(io.vertx.core.http.Http2Settings.DEFAULT_MAX_FRAME_SIZE, settings.getMaxFrameSize());
        assertEquals(io.vertx.core.http.Http2Settings.DEFAULT_INITIAL_WINDOW_SIZE, settings.getInitialWindowSize());
        assertEquals((Long) (long) Integer.MAX_VALUE, (Long) (long) settings.getMaxConcurrentStreams());
        assertEquals(io.vertx.core.http.Http2Settings.DEFAULT_HEADER_TABLE_SIZE, settings.getHeaderTableSize());
        conn.remoteSettingsHandler(update -> {
            assertOnIOContext(ctx);
            switch(count.getAndIncrement()) {
                case 0:
                    assertEquals(initialSettings.isPushEnabled(), update.isPushEnabled());
                    assertEquals(initialSettings.getMaxHeaderListSize(), update.getMaxHeaderListSize());
                    assertEquals(initialSettings.getMaxFrameSize(), update.getMaxFrameSize());
                    assertEquals(initialSettings.getInitialWindowSize(), update.getInitialWindowSize());
                    assertEquals(initialSettings.getMaxConcurrentStreams(), update.getMaxConcurrentStreams());
                    assertEquals(initialSettings.getHeaderTableSize(), update.getHeaderTableSize());
                    assertEquals(initialSettings.get(''), update.get(7));
                    settingsRead.complete();
                    break;
                case 1:
                    assertEquals(updatedSettings.isPushEnabled(), update.isPushEnabled());
                    assertEquals(updatedSettings.getMaxHeaderListSize(), update.getMaxHeaderListSize());
                    assertEquals(updatedSettings.getMaxFrameSize(), update.getMaxFrameSize());
                    assertEquals(updatedSettings.getInitialWindowSize(), update.getInitialWindowSize());
                    assertEquals(updatedSettings.getMaxConcurrentStreams(), update.getMaxConcurrentStreams());
                    assertEquals(updatedSettings.getHeaderTableSize(), update.getHeaderTableSize());
                    assertEquals(updatedSettings.get(''), update.get(7));
                    testComplete();
                    break;
            }
        });
    });
    server.requestHandler(req -> {
        fail();
    });
    startServer(ctx);
    TestClient client = new TestClient();
    client.settings.putAll(HttpUtils.fromVertxSettings(initialSettings));
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        settingsRead.setHandler(ar -> {
            request.encoder.writeSettings(request.context, HttpUtils.fromVertxSettings(updatedSettings), request.context.newPromise());
            request.context.flush();
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFuture(io.netty.channel.ChannelFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Aggregations

Context (io.vertx.core.Context)125 Test (org.junit.Test)99 Handler (io.vertx.core.Handler)75 Vertx (io.vertx.core.Vertx)75 Before (org.junit.Before)58 Buffer (io.vertx.core.buffer.Buffer)57 TestContext (io.vertx.ext.unit.TestContext)57 Future (io.vertx.core.Future)53 Async (io.vertx.ext.unit.Async)53 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)53 RunWith (org.junit.runner.RunWith)53 JsonObject (io.vertx.core.json.JsonObject)49 HttpURLConnection (java.net.HttpURLConnection)48 StandardCharsets (java.nio.charset.StandardCharsets)48 Assert.assertThat (org.junit.Assert.assertThat)48 Mockito (org.mockito.Mockito)48 Rule (org.junit.Rule)39 CoreMatchers.is (org.hamcrest.CoreMatchers.is)38 ArgumentCaptor (org.mockito.ArgumentCaptor)38 Timeout (org.junit.rules.Timeout)36