Search in sources :

Example 46 with CompletableFuture

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

the class FlowControlStrategyTest method testServerFlowControlOneBigWrite.

@Test
public void testServerFlowControlOneBigWrite() throws Exception {
    final int windowSize = 1536;
    final int length = 5 * windowSize;
    final CountDownLatch settingsLatch = new CountDownLatch(1);
    start(new ServerSessionListener.Adapter() {

        @Override
        public void onSettings(Session session, SettingsFrame frame) {
            settingsLatch.countDown();
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame requestFrame) {
            MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            HeadersFrame responseFrame = new HeadersFrame(stream.getId(), metaData, null, false);
            CompletableFuture<Void> completable = new CompletableFuture<>();
            stream.headers(responseFrame, Callback.from(completable));
            completable.thenRun(() -> {
                DataFrame dataFrame = new DataFrame(stream.getId(), ByteBuffer.allocate(length), true);
                stream.data(dataFrame, Callback.NOOP);
            });
            return null;
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    Map<Integer, Integer> settings = new HashMap<>();
    settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, windowSize);
    session.settings(new SettingsFrame(settings, false), Callback.NOOP);
    Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
    final CountDownLatch dataLatch = new CountDownLatch(1);
    final Exchanger<Callback> exchanger = new Exchanger<>();
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, true);
    session.newStream(requestFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        private AtomicInteger dataFrames = new AtomicInteger();

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            try {
                int dataFrames = this.dataFrames.incrementAndGet();
                if (dataFrames == 1 || dataFrames == 2) {
                    // Do not consume the data frame.
                    // We should then be flow-control stalled.
                    exchanger.exchange(callback);
                } else if (dataFrames == 3 || dataFrames == 4 || dataFrames == 5) {
                    // Consume totally.
                    callback.succeeded();
                    if (frame.isEndStream())
                        dataLatch.countDown();
                } else {
                    Assert.fail();
                }
            } catch (InterruptedException x) {
                callback.failed(x);
            }
        }
    });
    Callback callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the first chunk.
    callback.succeeded();
    callback = exchanger.exchange(null, 5, TimeUnit.SECONDS);
    checkThatWeAreFlowControlStalled(exchanger);
    // Consume the second chunk.
    callback.succeeded();
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) Exchanger(java.util.concurrent.Exchanger) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) CompletableFuture(java.util.concurrent.CompletableFuture) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HTTP2Stream(org.eclipse.jetty.http2.HTTP2Stream) Stream(org.eclipse.jetty.http2.api.Stream) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FuturePromise(org.eclipse.jetty.util.FuturePromise) Promise(org.eclipse.jetty.util.Promise) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 47 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 48 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)

Example 49 with CompletableFuture

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

the class VertxTestBase method createWorker.

/**
   * Create a worker verticle for the current Vert.x and return its context.
   *
   * @return the context
   * @throws Exception anything preventing the creation of the worker
   */
protected Context createWorker() throws Exception {
    CompletableFuture<Context> fut = new CompletableFuture<>();
    vertx.deployVerticle(new AbstractVerticle() {

        @Override
        public void start() throws Exception {
            fut.complete(context);
        }
    }, new DeploymentOptions().setWorker(true), ar -> {
        if (ar.failed()) {
            fut.completeExceptionally(ar.cause());
        }
    });
    return fut.get();
}
Also used : Context(io.vertx.core.Context) CompletableFuture(java.util.concurrent.CompletableFuture) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle)

Example 50 with CompletableFuture

use of java.util.concurrent.CompletableFuture in project hbase by apache.

the class AsyncHBaseAdmin method closeRegion.

@Override
public CompletableFuture<Void> closeRegion(byte[] regionName, String serverName) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    getRegion(regionName).whenComplete((p, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }
        if (p == null || p.getFirst() == null) {
            future.completeExceptionally(new UnknownRegionException(Bytes.toStringBinary(regionName)));
            return;
        }
        if (serverName != null) {
            closeRegion(ServerName.valueOf(serverName), p.getFirst()).whenComplete((p2, err2) -> {
                if (err2 != null) {
                    future.completeExceptionally(err2);
                } else {
                    future.complete(null);
                }
            });
        } else {
            if (p.getSecond() == null) {
                future.completeExceptionally(new NotServingRegionException(regionName));
            } else {
                closeRegion(p.getSecond(), p.getFirst()).whenComplete((p2, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(null);
                    }
                });
            }
        }
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) NotServingRegionException(org.apache.hadoop.hbase.NotServingRegionException) UnknownRegionException(org.apache.hadoop.hbase.UnknownRegionException)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)490 Test (org.junit.Test)152 ArrayList (java.util.ArrayList)88 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)77 List (java.util.List)75 UUID (java.util.UUID)62 Futures (io.pravega.common.concurrent.Futures)60 Map (java.util.Map)59 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)57 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)53 HashMap (java.util.HashMap)52 TimeUnit (java.util.concurrent.TimeUnit)52 Cleanup (lombok.Cleanup)49 Exceptions (io.pravega.common.Exceptions)48 Collectors (java.util.stream.Collectors)48 lombok.val (lombok.val)47 IOException (java.io.IOException)46 Duration (java.time.Duration)46 Slf4j (lombok.extern.slf4j.Slf4j)46 AtomicReference (java.util.concurrent.atomic.AtomicReference)45