Search in sources :

Example 56 with Future

use of io.vertx.core.Future in project vertx-openshift-it by cescoffier.

the class HttpConfigDeployment method start.

@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);
    eventBus = vertx.eventBus();
    router.get("/conf").handler(this::config);
    router.get("/*").handler(StaticHandler.create());
    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx.createHttpServer().requestHandler(router::accept).listen(// Retrieve the port from the configuration, default to 8080.
    config().getInteger("http.port", 8080), ar -> {
        if (ar.succeeded()) {
            eventBus.consumer("event-bus-config", msg -> {
                eventbusContent.add(msg.body());
            }).completionHandler(res -> {
                if (res.succeeded()) {
                    System.out.println("Registration succeeded: event-bus-config");
                } else {
                    System.out.println("Registration failed: " + res.cause());
                }
            });
            System.out.println("Server starter on port " + ar.result().actualPort());
        } else {
            System.out.println("Unable to start server: " + ar.cause().getMessage());
        }
        future.handle(ar.mapEmpty());
    });
}
Also used : List(java.util.List) EventBus(io.vertx.core.eventbus.EventBus) StaticHandler(io.vertx.ext.web.handler.StaticHandler) CONTENT_TYPE(io.vertx.core.http.HttpHeaders.CONTENT_TYPE) AbstractVerticle(io.vertx.core.AbstractVerticle) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) RoutingContext(io.vertx.ext.web.RoutingContext) Future(io.vertx.core.Future) ArrayList(java.util.ArrayList) Router(io.vertx.ext.web.Router)

Example 57 with Future

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

the class Http2ConnectionBase method close.

@Override
public Future<Void> close() {
    PromiseInternal<Void> promise = context.promise();
    ChannelPromise pr = chctx.newPromise();
    ChannelPromise channelPromise = pr.addListener(promise);
    handlerContext.writeAndFlush(Unpooled.EMPTY_BUFFER, pr);
    channelPromise.addListener((ChannelFutureListener) future -> shutdown(0L));
    return promise.future();
}
Also used : VertxException(io.vertx.core.VertxException) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) ArrayList(java.util.ArrayList) VertxByteBufAllocator(io.vertx.core.buffer.impl.VertxByteBufAllocator) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) Http2Stream(io.netty.handler.codec.http2.Http2Stream) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Logger(io.vertx.core.impl.logging.Logger) io.netty.buffer(io.netty.buffer) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Http2Flags(io.netty.handler.codec.http2.Http2Flags) StreamPriority(io.vertx.core.http.StreamPriority) Promise(io.vertx.core.Promise) GoAway(io.vertx.core.http.GoAway) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) Http2Settings(io.netty.handler.codec.http2.Http2Settings) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) EventLoopContext(io.vertx.core.impl.EventLoopContext) Http2Connection(io.netty.handler.codec.http2.Http2Connection) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Handler(io.vertx.core.Handler) ArrayDeque(java.util.ArrayDeque) ChannelPromise(io.netty.channel.ChannelPromise)

Example 58 with Future

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

the class FaultToleranceVerticle method start.

@Override
public void start() throws Exception {
    JsonObject config = config();
    id = config.getInteger("id");
    numAddresses = config.getInteger("addressesCount");
    List<Future> registrationFutures = new ArrayList<>(numAddresses);
    for (int i = 0; i < numAddresses; i++) {
        Promise<Void> registrationFuture = Promise.promise();
        registrationFutures.add(registrationFuture.future());
        vertx.eventBus().consumer(createAddress(id, i), msg -> msg.reply("pong")).completionHandler(registrationFuture);
    }
    Promise<Void> registrationFuture = Promise.promise();
    registrationFutures.add(registrationFuture.future());
    vertx.eventBus().consumer("ping", this::ping).completionHandler(registrationFuture);
    CompositeFuture.all(registrationFutures).onSuccess(ar -> vertx.eventBus().send("control", "start"));
}
Also used : Logger(io.vertx.core.impl.logging.Logger) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) Promise(io.vertx.core.Promise) Message(io.vertx.core.eventbus.Message) Future(io.vertx.core.Future) ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) AbstractVerticle(io.vertx.core.AbstractVerticle) ReplyFailure(io.vertx.core.eventbus.ReplyFailure) JsonObject(io.vertx.core.json.JsonObject) ReplyException(io.vertx.core.eventbus.ReplyException) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture)

Example 59 with Future

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

the class Http2ServerTest method testUpgradeToClearText.

private void testUpgradeToClearText(HttpMethod method, Buffer expected, Handler<HttpServerOptions> optionsConfig) throws Exception {
    server.close();
    AtomicInteger serverConnectionCount = new AtomicInteger();
    optionsConfig.handle(serverOptions);
    server = vertx.createHttpServer(serverOptions.setHost(DEFAULT_HTTP_HOST).setPort(DEFAULT_HTTP_PORT).setUseAlpn(false).setSsl(false).setInitialSettings(new io.vertx.core.http.Http2Settings().setMaxConcurrentStreams(20000))).connectionHandler(conn -> serverConnectionCount.incrementAndGet());
    server.requestHandler(req -> {
        assertEquals("http", req.scheme());
        assertEquals(method, req.method());
        assertEquals(HttpVersion.HTTP_2, req.version());
        assertEquals(10000, req.connection().remoteSettings().getMaxConcurrentStreams());
        assertFalse(req.isSSL());
        req.bodyHandler(body -> {
            assertEquals(expected, body);
            vertx.setTimer(10, id -> {
                req.response().end();
            });
        });
    }).connectionHandler(conn -> {
        assertNotNull(conn);
        serverConnectionCount.incrementAndGet();
    });
    startServer(testAddress);
    AtomicInteger clientConnectionCount = new AtomicInteger();
    client = vertx.createHttpClient(clientOptions.setUseAlpn(false).setSsl(false).setInitialSettings(new io.vertx.core.http.Http2Settings().setMaxConcurrentStreams(10000)));
    Promise<HttpClientResponse> p1 = Promise.promise();
    p1.future().onComplete(onSuccess(resp -> {
        assertEquals(HttpVersion.HTTP_2, resp.version());
        // assertEquals(20000, req.connection().remoteSettings().getMaxConcurrentStreams());
        assertEquals(1, serverConnectionCount.get());
        assertEquals(1, clientConnectionCount.get());
        Promise<HttpClientResponse> p2 = Promise.promise();
        p2.future().onComplete(onSuccess(resp2 -> {
            testComplete();
        }));
        doRequest(method, expected, null, p2);
    }));
    doRequest(method, expected, conn -> clientConnectionCount.incrementAndGet(), p1);
    await();
}
Also used : Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) 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) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) 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) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) 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) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) 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) HttpUtils(io.vertx.core.http.impl.HttpUtils) 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) Promise(io.vertx.core.Promise) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Settings(io.netty.handler.codec.http2.Http2Settings)

Example 60 with Future

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

the class Http2ServerTest method testStreamPauseResume.

private void testStreamPauseResume(Function<HttpServerRequest, Future<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 -> {
        Future<ReadStream<Buffer>> fut = streamProvider.apply(req);
        fut.onComplete(onSuccess(stream -> {
            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();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) 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) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) 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) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) 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) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) 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) HttpUtils(io.vertx.core.http.impl.HttpUtils) 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) ChannelFuture(io.netty.channel.ChannelFuture) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ReadStream(io.vertx.core.streams.ReadStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream)

Aggregations

Future (io.vertx.core.Future)370 HttpURLConnection (java.net.HttpURLConnection)195 Handler (io.vertx.core.Handler)174 List (java.util.List)166 Objects (java.util.Objects)164 JsonObject (io.vertx.core.json.JsonObject)163 Promise (io.vertx.core.Promise)160 Vertx (io.vertx.core.Vertx)157 Buffer (io.vertx.core.buffer.Buffer)149 Optional (java.util.Optional)147 Logger (org.slf4j.Logger)136 LoggerFactory (org.slf4j.LoggerFactory)136 CompositeFuture (io.vertx.core.CompositeFuture)127 ClientErrorException (org.eclipse.hono.client.ClientErrorException)127 Map (java.util.Map)122 Span (io.opentracing.Span)117 AsyncResult (io.vertx.core.AsyncResult)112 TracingHelper (org.eclipse.hono.tracing.TracingHelper)98 Constants (org.eclipse.hono.util.Constants)97 ArrayList (java.util.ArrayList)94