Search in sources :

Example 21 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project jetty.project by eclipse.

the class SlowClientsTest method testSlowClientsWithSmallThreadPool.

@Test(timeout = 10000)
public void testSlowClientsWithSmallThreadPool() throws Exception {
    File keystore = MavenTestingUtils.getTestResourceFile("keystore");
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keystore.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("storepwd");
    sslContextFactory.setKeyManagerPassword("keypwd");
    int maxThreads = 6;
    int contentLength = 8 * 1024 * 1024;
    QueuedThreadPool serverThreads = new QueuedThreadPool(maxThreads);
    serverThreads.setDetailedDump(true);
    Server server = new Server(serverThreads);
    try {
        ServerConnector connector = new ServerConnector(server, 1, 1, sslContextFactory);
        connector.setPort(8888);
        server.addConnector(connector);
        server.setHandler(new AbstractHandler() {

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                baseRequest.setHandled(true);
                logger.info("SERVING {}", target);
                // Write some big content.
                response.getOutputStream().write(new byte[contentLength]);
                logger.info("SERVED {}", target);
            }
        });
        server.start();
        SSLContext sslContext = sslContextFactory.getSslContext();
        CompletableFuture[] futures = new CompletableFuture[2 * maxThreads];
        ExecutorService executor = Executors.newFixedThreadPool(futures.length);
        for (int i = 0; i < futures.length; i++) {
            int k = i;
            futures[i] = CompletableFuture.runAsync(() -> {
                try (SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) {
                    socket.setSoTimeout(contentLength / 1024);
                    OutputStream output = socket.getOutputStream();
                    String target = "/" + k;
                    String request = "GET " + target + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                    output.write(request.getBytes(StandardCharsets.UTF_8));
                    output.flush();
                    while (serverThreads.getIdleThreads() > 0) Thread.sleep(50);
                    InputStream input = socket.getInputStream();
                    while (true) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    logger.info("FINISHED {}", target);
                } catch (IOException x) {
                    throw new UncheckedIOException(x);
                } catch (InterruptedException x) {
                    throw new UncheckedIOException(new InterruptedIOException());
                }
            }, executor);
        }
        CompletableFuture.allOf(futures).join();
    } finally {
        server.stop();
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Server(org.eclipse.jetty.server.Server) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) SSLContext(javax.net.ssl.SSLContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) CompletableFuture(java.util.concurrent.CompletableFuture) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ExecutorService(java.util.concurrent.ExecutorService) File(java.io.File) Test(org.junit.Test)

Example 22 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class Http2ClientTest method testClientRequestWriteability.

@Test
public void testClientRequestWriteability() throws Exception {
    Buffer content = Buffer.buffer();
    Buffer expected = Buffer.buffer();
    String chunk = TestUtils.randomAlphaString(100);
    CompletableFuture<Void> done = new CompletableFuture<>();
    AtomicBoolean paused = new AtomicBoolean();
    AtomicInteger numPause = new AtomicInteger();
    server.requestHandler(req -> {
        Context ctx = vertx.getOrCreateContext();
        done.thenAccept(v1 -> {
            paused.set(false);
            ctx.runOnContext(v2 -> {
                req.resume();
            });
        });
        numPause.incrementAndGet();
        req.pause();
        paused.set(true);
        req.handler(content::appendBuffer);
        req.endHandler(v -> {
            assertEquals(expected, content);
            req.response().end();
        });
    });
    startServer();
    HttpClientRequest req = client.post(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
        testComplete();
    }).setChunked(true).exceptionHandler(err -> {
        fail();
    });
    AtomicInteger sent = new AtomicInteger();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger drained = new AtomicInteger();
    vertx.setPeriodic(1, timerID -> {
        Context ctx = vertx.getOrCreateContext();
        if (req.writeQueueFull()) {
            assertTrue(paused.get());
            assertEquals(1, numPause.get());
            req.drainHandler(v -> {
                assertOnIOContext(ctx);
                assertEquals(0, drained.getAndIncrement());
                assertEquals(1, numPause.get());
                assertFalse(paused.get());
                req.end();
            });
            vertx.cancelTimer(timerID);
            done.complete(null);
        } else {
            count.incrementAndGet();
            expected.appendString(chunk);
            req.write(chunk);
            sent.addAndGet(chunk.length());
        }
    });
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientRequest(io.vertx.core.http.HttpClientRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsciiString(io.netty.util.AsciiString) Test(org.junit.Test)

Example 23 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class Http1xTest method testInvalidHttpResponse.

@Test
public void testInvalidHttpResponse() {
    waitFor(2);
    AtomicInteger count = new AtomicInteger(0);
    CompletableFuture<Void> sendResp = new CompletableFuture<>();
    NetServer server = vertx.createNetServer();
    String match = "GET /somepath HTTP/1.1\r\nHost: localhost:8080\r\n\r\n";
    server.connectHandler(so -> {
        StringBuilder content = new StringBuilder();
        so.handler(buff -> {
            content.append(buff);
            while (content.toString().startsWith(match)) {
                content.delete(0, match.length());
                switch(count.getAndIncrement()) {
                    case 0:
                        sendResp.thenAccept(v -> {
                        });
                        break;
                    case 1:
                        Buffer resp1 = Buffer.buffer(TestUtils.randomAlphaString(40) + "\r\n");
                        Buffer resp2 = Buffer.buffer("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
                        so.write(Buffer.buffer().appendBuffer(resp1).appendBuffer(resp2));
                        break;
                    default:
                        fail();
                        break;
                }
            }
        });
    }).listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, onSuccess(s -> {
        client = vertx.createHttpClient(new HttpClientOptions().setKeepAlive(true).setPipelining(true).setMaxPoolSize(1));
        AtomicBoolean fail1 = new AtomicBoolean();
        HttpClientRequest req1 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
            fail();
        }).exceptionHandler(err -> {
            if (fail1.compareAndSet(false, true)) {
                assertEquals(IllegalArgumentException.class, err.getClass());
                complete();
            }
        });
        AtomicBoolean fail2 = new AtomicBoolean();
        HttpClientRequest req2 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
            resp.bodyHandler(buff -> {
                assertEquals("okusa", buff.toString());
                testComplete();
            });
        }).exceptionHandler(err -> {
            if (fail2.compareAndSet(false, true)) {
                assertEquals(VertxException.class, err.getClass());
                complete();
            }
        });
        req1.end();
        req2.end();
    }));
    await();
}
Also used : IntStream(java.util.stream.IntStream) java.util(java.util) io.vertx.core(io.vertx.core) io.vertx.core.impl(io.vertx.core.impl) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) io.vertx.core.net(io.vertx.core.net) AtomicReference(java.util.concurrent.atomic.AtomicReference) io.vertx.core.http(io.vertx.core.http) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientRequestImpl(io.vertx.core.http.impl.HttpClientRequestImpl) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) RecordParser(io.vertx.core.parsetools.RecordParser) Pump(io.vertx.core.streams.Pump) JsonObject(io.vertx.core.json.JsonObject) Buffer(io.vertx.core.buffer.Buffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 24 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class Http2Test method testServerStreamPausedWhenConnectionIsPaused.

@Test
public void testServerStreamPausedWhenConnectionIsPaused() throws Exception {
    CountDownLatch fullLatch = new CountDownLatch(1);
    CompletableFuture<Void> resumeLatch = new CompletableFuture<>();
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        switch(req.path()) {
            case "/0":
                {
                    vertx.setPeriodic(1, timerID -> {
                        if (resp.writeQueueFull()) {
                            vertx.cancelTimer(timerID);
                            fullLatch.countDown();
                        } else {
                            resp.write(Buffer.buffer(TestUtils.randomAlphaString(512)));
                        }
                    });
                    break;
                }
            case "/1":
                {
                    assertTrue(resp.writeQueueFull());
                    resp.drainHandler(v -> {
                        resp.end();
                    });
                    resumeLatch.complete(null);
                    break;
                }
        }
    });
    startServer();
    client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/0", resp -> {
        resp.pause();
        Context ctx = vertx.getOrCreateContext();
        resumeLatch.thenAccept(v1 -> {
            ctx.runOnContext(v2 -> {
                resp.endHandler(v -> {
                    testComplete();
                });
                resp.resume();
            });
        });
    });
    awaitLatch(fullLatch);
    client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/1", resp -> {
        resp.endHandler(v -> {
            complete();
        });
    });
    // Make sure it completes
    resumeLatch.get(20, TimeUnit.SECONDS);
    await();
}
Also used : Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Http2Settings(io.vertx.core.http.Http2Settings) Cert(io.vertx.test.core.tls.Cert) Context(io.vertx.core.Context) TimeUnit(java.util.concurrent.TimeUnit) HttpClientRequest(io.vertx.core.http.HttpClientRequest) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServerResponse(io.vertx.core.http.HttpServerResponse) PemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) StreamResetException(io.vertx.core.http.StreamResetException) Context(io.vertx.core.Context) CompletableFuture(java.util.concurrent.CompletableFuture) HttpServerResponse(io.vertx.core.http.HttpServerResponse) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 25 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project vert.x by eclipse.

the class Http2Test method testClientStreamPausedWhenConnectionIsPaused.

@Test
public void testClientStreamPausedWhenConnectionIsPaused() throws Exception {
    waitFor(2);
    Buffer buffer = TestUtils.randomBuffer(512);
    CompletableFuture<Void> resumeLatch = new CompletableFuture<>();
    server.requestHandler(req -> {
        switch(req.path()) {
            case "/0":
                {
                    req.pause();
                    resumeLatch.thenAccept(v -> {
                        req.resume();
                    });
                    req.endHandler(v -> {
                        req.response().end();
                    });
                    break;
                }
            case "/1":
                {
                    req.bodyHandler(v -> {
                        assertEquals(v, buffer);
                        req.response().end();
                    });
                    break;
                }
        }
    });
    startServer();
    HttpClientRequest req1 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/0", resp -> {
        complete();
    }).setChunked(true);
    while (!req1.writeQueueFull()) {
        req1.write(Buffer.buffer(TestUtils.randomAlphaString(512)));
        Thread.sleep(1);
    }
    HttpClientRequest req2 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/1", resp -> {
        complete();
    }).setChunked(true);
    assertFalse(req2.writeQueueFull());
    req2.sendHead(v -> {
        assertTrue(req2.writeQueueFull());
        resumeLatch.complete(null);
    });
    resumeLatch.get(20, TimeUnit.SECONDS);
    waitUntil(() -> !req2.writeQueueFull());
    req1.end();
    req2.end(buffer);
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Http2Settings(io.vertx.core.http.Http2Settings) Cert(io.vertx.test.core.tls.Cert) Context(io.vertx.core.Context) TimeUnit(java.util.concurrent.TimeUnit) HttpClientRequest(io.vertx.core.http.HttpClientRequest) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServerResponse(io.vertx.core.http.HttpServerResponse) PemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) StreamResetException(io.vertx.core.http.StreamResetException) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Test(org.junit.Test)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)301 Test (org.junit.Test)64 IOException (java.io.IOException)38 List (java.util.List)34 Test (org.testng.annotations.Test)33 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)28 DestinationName (com.yahoo.pulsar.common.naming.DestinationName)26 Logger (org.slf4j.Logger)26 Map (java.util.Map)25 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)25 LoggerFactory (org.slf4j.LoggerFactory)25 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)24 ArrayList (java.util.ArrayList)24 ExecutionException (java.util.concurrent.ExecutionException)24 TimeUnit (java.util.concurrent.TimeUnit)24 ByteBuf (io.netty.buffer.ByteBuf)23 CountDownLatch (java.util.concurrent.CountDownLatch)21 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)20 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 Consumer (com.yahoo.pulsar.client.api.Consumer)19