Search in sources :

Example 1 with Context

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

the class Http2ConnectionBase method updateSettings.

protected synchronized void updateSettings(Http2Settings settingsUpdate, Handler<AsyncResult<Void>> completionHandler) {
    Context completionContext = completionHandler != null ? context.owner().getOrCreateContext() : null;
    Http2Settings current = handler.decoder().localSettings();
    for (Map.Entry<Character, Long> entry : current.entrySet()) {
        Character key = entry.getKey();
        if (Objects.equals(settingsUpdate.get(key), entry.getValue())) {
            settingsUpdate.remove(key);
        }
    }
    handler.writeSettings(settingsUpdate).addListener(fut -> {
        if (fut.isSuccess()) {
            synchronized (Http2ConnectionBase.this) {
                updateSettingsHandlers.add(() -> {
                    serverSettings.putAll(settingsUpdate);
                    if (completionHandler != null) {
                        completionContext.runOnContext(v -> {
                            completionHandler.handle(Future.succeededFuture());
                        });
                    }
                });
            }
        } else {
            if (completionHandler != null) {
                completionContext.runOnContext(v -> {
                    completionHandler.handle(Future.failedFuture(fut.cause()));
                });
            }
        }
    });
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2Settings(io.netty.handler.codec.http2.Http2Settings) IntObjectMap(io.netty.util.collection.IntObjectMap) Map(java.util.Map) IntObjectHashMap(io.netty.util.collection.IntObjectHashMap)

Example 2 with Context

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

the class Http2ServerResponseImpl method sendFile.

@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        checkEnded();
        Context resultCtx = resultHandler != null ? stream.vertx.getOrCreateContext() : null;
        File file = stream.vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
                log.error("File not found: " + filename);
            }
            return this;
        }
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (IOException e) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
                log.error("Failed to send file", e);
            }
            return this;
        }
        long contentLength = Math.min(length, file.length() - offset);
        if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
            putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
        }
        if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
            String contentType = MimeMapping.getMimeTypeForFilename(filename);
            if (contentType != null) {
                putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
        checkSendHeaders(false);
        FileStreamChannel fileChannel = new FileStreamChannel(ar -> {
            if (ar.succeeded()) {
                bytesWritten += ar.result();
                end();
            }
            if (resultHandler != null) {
                resultCtx.runOnContext(v -> {
                    resultHandler.handle(Future.succeededFuture());
                });
            }
        }, stream, offset, contentLength);
        drainHandler(fileChannel.drainHandler);
        ctx.channel().eventLoop().register(fileChannel);
        fileChannel.pipeline().fireUserEventTriggered(raf);
    }
    return this;
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RandomAccessFile(java.io.RandomAccessFile) MultiMap(io.vertx.core.MultiMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) Context(io.vertx.core.Context) Future(io.vertx.core.Future) LoggerFactory(io.vertx.core.logging.LoggerFactory) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) Nullable(io.vertx.codegen.annotations.Nullable) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) StreamResetException(io.vertx.core.http.StreamResetException) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 3 with Context

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

the class EventBusTestBase method testNoHandlersCallbackContext.

@Test
public void testNoHandlersCallbackContext() {
    startNodes(2);
    waitFor(4);
    // On an "external" thread
    vertices[0].eventBus().send("blah", "blah", ar -> {
        assertTrue(ar.failed());
        if (ar.cause() instanceof ReplyException) {
            ReplyException cause = (ReplyException) ar.cause();
            assertSame(ReplyFailure.NO_HANDLERS, cause.failureType());
        } else {
            fail(ar.cause());
        }
        assertTrue("Not an EL thread", Context.isOnEventLoopThread());
        complete();
    });
    // On a EL context
    vertices[0].runOnContext(v -> {
        Context ctx = vertices[0].getOrCreateContext();
        vertices[0].eventBus().send("blah", "blah", ar -> {
            assertTrue(ar.failed());
            if (ar.cause() instanceof ReplyException) {
                ReplyException cause = (ReplyException) ar.cause();
                assertSame(ReplyFailure.NO_HANDLERS, cause.failureType());
            } else {
                fail(ar.cause());
            }
            assertSame(ctx, vertices[0].getOrCreateContext());
            complete();
        });
    });
    // On a Worker context
    vertices[0].deployVerticle(new AbstractVerticle() {

        @Override
        public void start() throws Exception {
            Context ctx = getVertx().getOrCreateContext();
            vertices[0].eventBus().send("blah", "blah", ar -> {
                assertTrue(ar.failed());
                if (ar.cause() instanceof ReplyException) {
                    ReplyException cause = (ReplyException) ar.cause();
                    assertSame(ReplyFailure.NO_HANDLERS, cause.failureType());
                } else {
                    fail(ar.cause());
                }
                assertSame(ctx, getVertx().getOrCreateContext());
                complete();
            });
        }
    }, new DeploymentOptions().setWorker(true));
    // Inside executeBlocking
    vertices[0].executeBlocking(fut -> {
        vertices[0].eventBus().send("blah", "blah", ar -> {
            assertTrue(ar.failed());
            if (ar.cause() instanceof ReplyException) {
                ReplyException cause = (ReplyException) ar.cause();
                assertSame(ReplyFailure.NO_HANDLERS, cause.failureType());
            } else {
                fail(ar.cause());
            }
            assertTrue("Not an EL thread", Context.isOnEventLoopThread());
            complete();
        });
        fut.complete();
    }, false, null);
    await();
}
Also used : Context(io.vertx.core.Context) CoreMatchers(org.hamcrest.CoreMatchers) DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Verticle(io.vertx.core.Verticle) Context(io.vertx.core.Context) Future(io.vertx.core.Future) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) EventBus(io.vertx.core.eventbus.EventBus) MessageCodec(io.vertx.core.eventbus.MessageCodec) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) CharsetUtil(io.netty.util.CharsetUtil) ReplyFailure(io.vertx.core.eventbus.ReplyFailure) JsonObject(io.vertx.core.json.JsonObject) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) ReplyException(io.vertx.core.eventbus.ReplyException) DeploymentOptions(io.vertx.core.DeploymentOptions) ReplyException(io.vertx.core.eventbus.ReplyException) AbstractVerticle(io.vertx.core.AbstractVerticle) ReplyException(io.vertx.core.eventbus.ReplyException) Test(org.junit.Test)

Example 4 with Context

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

the class ExecuteBlockingTest method testExecuteBlockingParallel.

@Test
public void testExecuteBlockingParallel() throws Exception {
    long start = System.currentTimeMillis();
    int numExecBlocking = 10;
    long pause = 1000;
    CountDownLatch latch = new CountDownLatch(numExecBlocking);
    vertx.runOnContext(v -> {
        Context ctx = vertx.getOrCreateContext();
        assertTrue(ctx.isEventLoopContext());
        for (int i = 0; i < numExecBlocking; i++) {
            vertx.executeBlocking(future -> {
                assertSame(ctx, vertx.getOrCreateContext());
                assertTrue(Thread.currentThread().getName().startsWith("vert.x-worker-thread"));
                assertTrue(Context.isOnWorkerThread());
                assertFalse(Context.isOnEventLoopThread());
                try {
                    Thread.sleep(pause);
                } catch (Exception ignore) {
                }
                future.complete("done!");
            }, false, onSuccess(res -> {
                assertSame(ctx, vertx.getOrCreateContext());
                assertTrue(Thread.currentThread().getName().startsWith("vert.x-eventloop-thread"));
                assertFalse(Context.isOnWorkerThread());
                assertTrue(Context.isOnEventLoopThread());
                assertEquals("done!", res);
                latch.countDown();
            }));
        }
    });
    awaitLatch(latch);
    long now = System.currentTimeMillis();
    long leeway = 1000;
    assertTrue(now - start < pause + leeway);
}
Also used : Context(io.vertx.core.Context) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 5 with Context

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

the class ExecuteBlockingTest method testExecuteBlockingContext.

@Test
public void testExecuteBlockingContext() {
    vertx.runOnContext(v -> {
        Context ctx = vertx.getOrCreateContext();
        assertTrue(ctx.isEventLoopContext());
        vertx.executeBlocking(future -> {
            assertSame(ctx, vertx.getOrCreateContext());
            assertTrue(Thread.currentThread().getName().startsWith("vert.x-worker-thread"));
            assertTrue(Context.isOnWorkerThread());
            assertFalse(Context.isOnEventLoopThread());
            try {
                Thread.sleep(1000);
            } catch (Exception ignore) {
            }
            vertx.runOnContext(v2 -> {
                assertSame(ctx, vertx.getOrCreateContext());
                assertTrue(Thread.currentThread().getName().startsWith("vert.x-eventloop-thread"));
                assertFalse(Context.isOnWorkerThread());
                assertTrue(Context.isOnEventLoopThread());
                future.complete("done!");
            });
        }, onSuccess(res -> {
            assertSame(ctx, vertx.getOrCreateContext());
            assertTrue(Thread.currentThread().getName().startsWith("vert.x-eventloop-thread"));
            assertFalse(Context.isOnWorkerThread());
            assertTrue(Context.isOnEventLoopThread());
            assertEquals("done!", res);
            testComplete();
        }));
    });
    await();
}
Also used : Context(io.vertx.core.Context) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Aggregations

Context (io.vertx.core.Context)65 Test (org.junit.Test)46 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)26 ChannelFuture (io.netty.channel.ChannelFuture)24 Buffer (io.vertx.core.buffer.Buffer)24 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 HttpServerResponse (io.vertx.core.http.HttpServerResponse)20 Future (io.vertx.core.Future)19 Handler (io.vertx.core.Handler)19 Http2ConnectionEncoder (io.netty.handler.codec.http2.Http2ConnectionEncoder)18 Vertx (io.vertx.core.Vertx)18 HttpClientOptions (io.vertx.core.http.HttpClientOptions)18 HttpClientRequest (io.vertx.core.http.HttpClientRequest)18 HttpServerOptions (io.vertx.core.http.HttpServerOptions)18 AsyncResult (io.vertx.core.AsyncResult)17 MultiMap (io.vertx.core.MultiMap)17 HttpClient (io.vertx.core.http.HttpClient)17 HttpMethod (io.vertx.core.http.HttpMethod)17 NetSocket (io.vertx.core.net.NetSocket)17