Search in sources :

Example 61 with Future

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

the class WebSocketTest method testServerWebSocketPingPongCheck.

private void testServerWebSocketPingPongCheck(int maxFrameSize, Function<ServerWebSocket, Future<Void>> check) {
    Pattern pattern = Pattern.compile("^P[io]ng cannot exceed maxWebSocketFrameSize or 125 bytes$");
    server = vertx.createHttpServer(new HttpServerOptions().setIdleTimeout(1).setPort(DEFAULT_HTTP_PORT).setHost(HttpTestBase.DEFAULT_HTTP_HOST).setMaxWebSocketFrameSize(maxFrameSize));
    server.webSocketHandler(ws -> {
        ws.pongHandler(buff -> fail());
        check.apply(ws).onComplete(onFailure(err -> {
            Matcher matcher = pattern.matcher(err.getMessage());
            if (matcher.matches()) {
                ws.close();
            } else {
                fail("Unexpected error message" + err.getMessage());
            }
        }));
    }).listen(onSuccess(v -> {
        client = vertx.createHttpClient();
        client.webSocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", onSuccess(ws -> {
            ws.closeHandler(v2 -> {
                testComplete();
            });
        }));
    }));
    await();
}
Also used : WebSocketInternal(io.vertx.core.http.impl.WebSocketInternal) MultiMap(io.vertx.core.MultiMap) Context(io.vertx.core.Context) Matcher(java.util.regex.Matcher) PlatformDependent(io.netty.util.internal.PlatformDependent) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT_HTTP_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_HOST) ReadStream(io.vertx.core.streams.ReadStream) HAProxy(io.vertx.test.proxy.HAProxy) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) CheckingSender(io.vertx.test.core.CheckingSender) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Trust(io.vertx.test.tls.Trust) BlockingQueue(java.util.concurrent.BlockingQueue) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Certificate(java.security.cert.Certificate) Buffer(io.vertx.core.buffer.Buffer) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cert(io.vertx.test.tls.Cert) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) NetSocket(io.vertx.core.net.NetSocket) java.util(java.util) MessageDigest(java.security.MessageDigest) DEFAULT_HTTP_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_PORT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) DEFAULT_HTTPS_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_HOST) BiConsumer(java.util.function.BiConsumer) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocket13FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) DEFAULT_TEST_URI(io.vertx.core.http.HttpTestBase.DEFAULT_TEST_URI) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) Promise(io.vertx.core.Promise) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) IOException(java.io.IOException) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WebSocket13FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) DEFAULT_HTTPS_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_PORT) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Http1xClientConnection(io.vertx.core.http.impl.Http1xClientConnection) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher)

Example 62 with Future

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

the class Http2Test method testConnectionCloseEvictsConnectionFromThePoolBeforeStreamsAreClosed.

/**
 * Test that socket close (without an HTTP/2 go away frame) removes the connection from the pool
 * before the streams are notified. Otherwise a notified stream might reuse a stale connection from
 * the pool.
 */
@Test
public void testConnectionCloseEvictsConnectionFromThePoolBeforeStreamsAreClosed() throws Exception {
    Set<HttpConnection> serverConnections = new HashSet<>();
    server.requestHandler(req -> {
        serverConnections.add(req.connection());
        switch(req.path()) {
            case "/1":
                req.response().end();
                break;
            case "/2":
                assertEquals(1, serverConnections.size());
                // Socket close without HTTP/2 go away
                Channel ch = ((ConnectionBase) req.connection()).channel();
                ChannelPromise promise = ch.newPromise();
                ch.unsafe().close(promise);
                break;
            case "/3":
                assertEquals(2, serverConnections.size());
                req.response().end();
                break;
        }
    });
    startServer(testAddress);
    Future<Buffer> f1 = client.request(new RequestOptions(requestOptions).setURI("/1")).compose(req -> req.send().compose(HttpClientResponse::body));
    f1.onComplete(onSuccess(v -> {
        Future<Buffer> f2 = client.request(new RequestOptions(requestOptions).setURI("/2")).compose(req -> {
            System.out.println(req.connection());
            return req.send().compose(HttpClientResponse::body);
        });
        f2.onComplete(onFailure(v2 -> {
            Future<Buffer> f3 = client.request(new RequestOptions(requestOptions).setURI("/3")).compose(req -> {
                System.out.println(req.connection());
                return req.send().compose(HttpClientResponse::body);
            });
            f3.onComplete(onSuccess(vvv -> {
                testComplete();
            }));
        }));
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) java.util(java.util) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Context(io.vertx.core.Context) PfxOptions(io.vertx.core.net.PfxOptions) BooleanSupplier(java.util.function.BooleanSupplier) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) ChannelPromise(io.netty.channel.ChannelPromise) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DuplexChannel(io.netty.channel.socket.DuplexChannel) Http2ServerConnection(io.vertx.core.http.impl.Http2ServerConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Promise(io.vertx.core.Promise) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Test(org.junit.Test) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Repeat(io.vertx.test.core.Repeat) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) Ignore(org.junit.Ignore) AsyncTestBase(io.vertx.test.core.AsyncTestBase) Cert(io.vertx.test.tls.Cert) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) DuplexChannel(io.netty.channel.socket.DuplexChannel) Channel(io.netty.channel.Channel) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.vertx.core.Future) ChannelPromise(io.netty.channel.ChannelPromise) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Test(org.junit.Test)

Example 63 with Future

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

the class DatagramSocketImpl method listen.

private Future<DatagramSocket> listen(SocketAddress local) {
    AddressResolver resolver = context.owner().addressResolver();
    PromiseInternal<Void> promise = context.promise();
    io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), local.host());
    f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
        if (res1.isSuccess()) {
            ChannelFuture f2 = channel.bind(new InetSocketAddress(res1.getNow().getAddress(), local.port()));
            if (metrics != null) {
                f2.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Void>>) res2 -> {
                    if (res2.isSuccess()) {
                        metrics.listening(local.host(), localAddress());
                    }
                });
            }
            f2.addListener(promise);
        } else {
            promise.fail(res1.cause());
        }
    });
    return promise.future().map(this);
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) DatagramSocket(io.vertx.core.datagram.DatagramSocket) Arguments(io.vertx.core.impl.Arguments) ContextInternal(io.vertx.core.impl.ContextInternal) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) DatagramPacket(io.netty.channel.socket.DatagramPacket) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) AsyncResult(io.vertx.core.AsyncResult) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) MaxMessagesRecvByteBufAllocator(io.netty.channel.MaxMessagesRecvByteBufAllocator) SocketAddress(io.vertx.core.net.SocketAddress) VertxHandler(io.vertx.core.net.impl.VertxHandler) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Transport(io.vertx.core.net.impl.transport.Transport) AddressResolver(io.vertx.core.impl.AddressResolver) NetworkInterface(java.net.NetworkInterface) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) io.vertx.core.spi.metrics(io.vertx.core.spi.metrics) Handler(io.vertx.core.Handler) ChannelFuture(io.netty.channel.ChannelFuture) AddressResolver(io.vertx.core.impl.AddressResolver) InetSocketAddress(java.net.InetSocketAddress) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Example 64 with Future

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

the class SharedDataImpl method getLocalAsyncMap.

@SuppressWarnings("unchecked")
@Override
public <K, V> Future<AsyncMap<K, V>> getLocalAsyncMap(String name) {
    LocalAsyncMapImpl<K, V> asyncMap = (LocalAsyncMapImpl<K, V>) localAsyncMaps.computeIfAbsent(name, n -> new LocalAsyncMapImpl<>(vertx));
    ContextInternal context = vertx.getOrCreateContext();
    return context.succeededFuture(new WrappedAsyncMap<>(asyncMap));
}
Also used : io.vertx.core.shareddata(io.vertx.core.shareddata) VertxInternal(io.vertx.core.impl.VertxInternal) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) Promise(io.vertx.core.Promise) Arguments(io.vertx.core.impl.Arguments) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ContextInternal(io.vertx.core.impl.ContextInternal) Set(java.util.Set) Future(io.vertx.core.Future) Serializable(java.io.Serializable) ConcurrentMap(java.util.concurrent.ConcurrentMap) Objects(java.util.Objects) List(java.util.List) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ContextInternal(io.vertx.core.impl.ContextInternal)

Example 65 with Future

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

the class Http1xTest method testPipelinedPostRequestStartedByResponseSent.

@Test
public void testPipelinedPostRequestStartedByResponseSent() throws Exception {
    String chunk1 = TestUtils.randomAlphaString(1024);
    String chunk2 = TestUtils.randomAlphaString(1024);
    Promise<Void> latch2 = Promise.promise();
    AtomicInteger count = new AtomicInteger();
    server.requestHandler(req -> {
        switch(count.getAndIncrement()) {
            case 0:
                req.pause();
                vertx.setTimer(500, id -> {
                    req.resume();
                });
                req.endHandler(v -> {
                    req.response().end();
                });
                break;
            case 1:
                latch2.complete();
                req.bodyHandler(body -> {
                    assertEquals(chunk1 + chunk2, body.toString());
                    req.response().end();
                });
                break;
        }
    });
    startServer(testAddress);
    client.close();
    client = vertx.createHttpClient(new HttpClientOptions().setPipelining(true).setMaxPoolSize(1).setKeepAlive(true));
    CountDownLatch latch1 = new CountDownLatch(1);
    client.request(new RequestOptions(requestOptions).setMethod(PUT)).onComplete(onSuccess(req -> {
        req.end(TestUtils.randomAlphaString(1024), onSuccess(v -> {
            latch1.countDown();
        }));
    }));
    awaitLatch(latch1);
    client.request(new RequestOptions(requestOptions).setMethod(PUT)).onComplete(onSuccess(req -> {
        req.response(resp -> {
            testComplete();
        }).setChunked(true);
        req.write(chunk1);
        latch2.future().onComplete(onSuccess(v -> {
            req.end(chunk2);
        }));
    }));
    await();
}
Also used : HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) IntStream(java.util.stream.IntStream) java.util(java.util) io.vertx.core(io.vertx.core) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) SimpleServer(io.vertx.test.verticles.SimpleServer) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) BiConsumer(java.util.function.BiConsumer) RecordParser(io.vertx.core.parsetools.RecordParser) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) CheckingSender(io.vertx.test.core.CheckingSender) VertxInternal(io.vertx.core.impl.VertxInternal) Http1xUpgradeToH2CHandler(io.vertx.core.http.impl.Http1xUpgradeToH2CHandler) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Test(org.junit.Test) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) io.vertx.core.net(io.vertx.core.net) Collectors(java.util.stream.Collectors) File(java.io.File) LongConsumer(java.util.function.LongConsumer) Channel(io.netty.channel.Channel) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) JsonArray(io.vertx.core.json.JsonArray) Repeat(io.vertx.test.core.Repeat) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) HttpUtils(io.vertx.core.http.impl.HttpUtils) Cert(io.vertx.test.tls.Cert) ChannelHandler(io.netty.channel.ChannelHandler) PUT(io.vertx.core.http.HttpMethod.PUT) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

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