Search in sources :

Example 21 with HttpClientRequest

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

the class HttpMetricsTest method testHttpClientLifecycle.

private void testHttpClientLifecycle(HttpVersion protocol) throws Exception {
    HttpServer server = vertx.createHttpServer();
    CountDownLatch requestBeginLatch = new CountDownLatch(1);
    CountDownLatch requestBodyLatch = new CountDownLatch(1);
    CountDownLatch requestEndLatch = new CountDownLatch(1);
    CompletableFuture<Void> beginResponse = new CompletableFuture<>();
    CompletableFuture<Void> endResponse = new CompletableFuture<>();
    server.requestHandler(req -> {
        assertEquals(protocol, req.version());
        requestBeginLatch.countDown();
        req.handler(buff -> {
            requestBodyLatch.countDown();
        });
        req.endHandler(v -> {
            requestEndLatch.countDown();
        });
        Context ctx = vertx.getOrCreateContext();
        beginResponse.thenAccept(v1 -> {
            ctx.runOnContext(v2 -> {
                req.response().setChunked(true).write(TestUtils.randomAlphaString(1024));
            });
        });
        endResponse.thenAccept(v1 -> {
            ctx.runOnContext(v2 -> {
                req.response().end();
            });
        });
    });
    CountDownLatch listenLatch = new CountDownLatch(1);
    server.listen(8080, "localhost", onSuccess(s -> {
        listenLatch.countDown();
    }));
    awaitLatch(listenLatch);
    HttpClient client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(protocol));
    FakeHttpClientMetrics clientMetrics = FakeMetricsBase.getMetrics(client);
    CountDownLatch responseBeginLatch = new CountDownLatch(1);
    CountDownLatch responseEndLatch = new CountDownLatch(1);
    HttpClientRequest req = client.post(8080, "localhost", "/somepath", resp -> {
        responseBeginLatch.countDown();
        resp.endHandler(v -> {
            responseEndLatch.countDown();
        });
    }).setChunked(true);
    req.sendHead();
    awaitLatch(requestBeginLatch);
    HttpClientMetric reqMetric = clientMetrics.getMetric(req);
    assertEquals(0, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    req.write(TestUtils.randomAlphaString(1024));
    awaitLatch(requestBodyLatch);
    assertEquals(0, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    req.end();
    awaitLatch(requestEndLatch);
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(0, reqMetric.responseBegin.get());
    beginResponse.complete(null);
    awaitLatch(responseBeginLatch);
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(1, reqMetric.responseBegin.get());
    endResponse.complete(null);
    awaitLatch(responseEndLatch);
    assertNull(clientMetrics.getMetric(req));
    assertEquals(1, reqMetric.requestEnded.get());
    assertEquals(1, reqMetric.responseBegin.get());
}
Also used : Context(io.vertx.core.Context) FakeMetricsBase(io.vertx.test.fakemetrics.FakeMetricsBase) FakeMetricsFactory(io.vertx.test.fakemetrics.FakeMetricsFactory) HttpServerMetric(io.vertx.test.fakemetrics.HttpServerMetric) HttpServer(io.vertx.core.http.HttpServer) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpClientRequest(io.vertx.core.http.HttpClientRequest) FakeHttpServerMetrics(io.vertx.test.fakemetrics.FakeHttpServerMetrics) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric) HttpClient(io.vertx.core.http.HttpClient) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) HttpServer(io.vertx.core.http.HttpServer) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric)

Example 22 with HttpClientRequest

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

the class HttpMetricsTest method testClientConnectionClosed.

private void testClientConnectionClosed(HttpVersion protocol) throws Exception {
    server.requestHandler(req -> {
        req.response().setChunked(true).write(Buffer.buffer("some-data"));
    });
    startServer();
    client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(protocol).setIdleTimeout(2));
    FakeHttpClientMetrics metrics = FakeMetricsBase.getMetrics(client);
    HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
    req.handler(resp -> {
        HttpClientMetric metric = metrics.getMetric(req);
        assertNotNull(metric);
        assertFalse(metric.failed.get());
        resp.exceptionHandler(err -> {
            assertNull(metrics.getMetric(req));
            assertTrue(metric.failed.get());
            testComplete();
        });
    });
    req.end();
    await();
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric)

Example 23 with HttpClientRequest

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

the class HttpProxy method start.

/**
   * Start the server.
   * 
   * @param vertx
   *          Vertx instance to use for creating the server and client
   * @param finishedHandler
   *          will be called when the server has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    HttpServerOptions options = new HttpServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createHttpServer(options);
    server.requestHandler(request -> {
        HttpMethod method = request.method();
        String uri = request.uri();
        if (username != null) {
            String auth = request.getHeader("Proxy-Authorization");
            String expected = "Basic " + Base64.getEncoder().encodeToString((username + ":" + username).getBytes());
            if (auth == null || !auth.equals(expected)) {
                request.response().setStatusCode(407).end("proxy authentication failed");
                return;
            }
        }
        lastRequestHeaders = MultiMap.caseInsensitiveMultiMap().addAll(request.headers());
        if (error != 0) {
            request.response().setStatusCode(error).end("proxy request failed");
        } else if (method == HttpMethod.CONNECT) {
            if (!uri.contains(":")) {
                request.response().setStatusCode(403).end("invalid request");
            } else {
                lastUri = uri;
                if (forceUri != null) {
                    uri = forceUri;
                }
                String[] split = uri.split(":");
                String host = split[0];
                int port;
                try {
                    port = Integer.parseInt(split[1]);
                } catch (NumberFormatException ex) {
                    port = 443;
                }
                if (port == 8080 || port < 1024 && port != 443) {
                    request.response().setStatusCode(403).end("access to port denied");
                    return;
                }
                NetSocket serverSocket = request.netSocket();
                NetClientOptions netOptions = new NetClientOptions();
                NetClient netClient = vertx.createNetClient(netOptions);
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        NetSocket clientSocket = result.result();
                        serverSocket.write("HTTP/1.0 200 Connection established\n\n");
                        serverSocket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> serverSocket.close());
                        Pump.pump(serverSocket, clientSocket).start();
                        Pump.pump(clientSocket, serverSocket).start();
                    } else {
                        request.response().setStatusCode(403).end("request failed");
                    }
                });
            }
        } else if (method == HttpMethod.GET) {
            lastUri = request.uri();
            HttpClient client = vertx.createHttpClient();
            HttpClientRequest clientRequest = client.getAbs(request.uri(), resp -> {
                for (String name : resp.headers().names()) {
                    request.response().putHeader(name, resp.headers().getAll(name));
                }
                resp.bodyHandler(body -> {
                    request.response().end(body);
                });
            });
            for (String name : request.headers().names()) {
                if (!name.equals("Proxy-Authorization")) {
                    clientRequest.putHeader(name, request.headers().getAll(name));
                }
            }
            clientRequest.exceptionHandler(e -> {
                log.debug("exception", e);
                int status;
                if (e instanceof UnknownHostException) {
                    status = 504;
                } else {
                    status = 400;
                }
                request.response().setStatusCode(status).end(e.toString() + " on client request");
            });
            clientRequest.end();
        } else {
            request.response().setStatusCode(405).end("method not supported");
        }
    });
    server.listen(server -> {
        finishedHandler.handle(null);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Vertx(io.vertx.core.Vertx) UnknownHostException(java.net.UnknownHostException) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Base64(java.util.Base64) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) NetClient(io.vertx.core.net.NetClient) UnknownHostException(java.net.UnknownHostException) HttpClient(io.vertx.core.http.HttpClient) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpMethod(io.vertx.core.http.HttpMethod)

Example 24 with HttpClientRequest

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

the class HttpTest method testResponseDataTimeout.

@Test
public void testResponseDataTimeout() {
    Buffer expected = TestUtils.randomBuffer(1000);
    server.requestHandler(req -> {
        req.response().setChunked(true).write(expected);
    });
    server.listen(onSuccess(s -> {
        HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI);
        Buffer received = Buffer.buffer();
        req.handler(resp -> {
            req.setTimeout(500);
            resp.handler(received::appendBuffer);
        });
        AtomicInteger count = new AtomicInteger();
        req.exceptionHandler(t -> {
            if (count.getAndIncrement() == 0) {
                assertTrue(t instanceof TimeoutException);
                assertEquals(expected, received);
                testComplete();
            }
        });
        req.sendHead();
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) VertxException(io.vertx.core.VertxException) MultiMap(io.vertx.core.MultiMap) TimeoutException(java.util.concurrent.TimeoutException) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) Nullable(io.vertx.codegen.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) WorkerContext(io.vertx.core.impl.WorkerContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) IntStream(java.util.stream.IntStream) HeadersAdaptor(io.vertx.core.http.impl.HeadersAdaptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) BufferedWriter(java.io.BufferedWriter) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) URLEncoder(java.net.URLEncoder) Rule(org.junit.Rule) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) TemporaryFolder(org.junit.rules.TemporaryFolder) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) HttpClientRequest(io.vertx.core.http.HttpClientRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 25 with HttpClientRequest

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

the class HttpTest method testFormUploadFile.

private void testFormUploadFile(String contentStr, boolean streamToDisk) throws Exception {
    Buffer content = Buffer.buffer(contentStr);
    AtomicInteger attributeCount = new AtomicInteger();
    server.requestHandler(req -> {
        if (req.method() == HttpMethod.POST) {
            assertEquals(req.path(), "/form");
            req.response().setChunked(true);
            req.setExpectMultipart(true);
            assertTrue(req.isExpectMultipart());
            req.setExpectMultipart(true);
            assertTrue(req.isExpectMultipart());
            req.uploadHandler(upload -> {
                Buffer tot = Buffer.buffer();
                assertEquals("file", upload.name());
                assertEquals("tmp-0.txt", upload.filename());
                assertEquals("image/gif", upload.contentType());
                String uploadedFileName;
                if (!streamToDisk) {
                    upload.handler(buffer -> tot.appendBuffer(buffer));
                    uploadedFileName = null;
                } else {
                    uploadedFileName = new File(testDir, UUID.randomUUID().toString()).getPath();
                    upload.streamToFileSystem(uploadedFileName);
                }
                upload.endHandler(v -> {
                    if (streamToDisk) {
                        Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName);
                        assertEquals(content, uploaded);
                    } else {
                        assertEquals(content, tot);
                    }
                    assertTrue(upload.isSizeAvailable());
                    assertEquals(content.length(), upload.size());
                });
            });
            req.endHandler(v -> {
                MultiMap attrs = req.formAttributes();
                attributeCount.set(attrs.size());
                req.response().end();
            });
        }
    });
    server.listen(onSuccess(s -> {
        HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> {
            assertEquals(200, resp.statusCode());
            resp.bodyHandler(body -> {
                assertEquals(0, body.length());
            });
            assertEquals(0, attributeCount.get());
            testComplete();
        });
        String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
        Buffer buffer = Buffer.buffer();
        String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + contentStr + "\r\n" + "--" + boundary + "--\r\n";
        buffer.appendString(body);
        req.headers().set("content-length", String.valueOf(buffer.length()));
        req.headers().set("content-type", "multipart/form-data; boundary=" + boundary);
        req.write(buffer).end();
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) VertxException(io.vertx.core.VertxException) MultiMap(io.vertx.core.MultiMap) TimeoutException(java.util.concurrent.TimeoutException) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) Nullable(io.vertx.codegen.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) WorkerContext(io.vertx.core.impl.WorkerContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) IntStream(java.util.stream.IntStream) HeadersAdaptor(io.vertx.core.http.impl.HeadersAdaptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) BufferedWriter(java.io.BufferedWriter) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) URLEncoder(java.net.URLEncoder) Rule(org.junit.Rule) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) TemporaryFolder(org.junit.rules.TemporaryFolder) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) MultiMap(io.vertx.core.MultiMap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File)

Aggregations

HttpClientRequest (io.vertx.core.http.HttpClientRequest)73 Test (org.junit.Test)59 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)42 Buffer (io.vertx.core.buffer.Buffer)39 HttpServerResponse (io.vertx.core.http.HttpServerResponse)36 HttpClientOptions (io.vertx.core.http.HttpClientOptions)34 HttpMethod (io.vertx.core.http.HttpMethod)32 CountDownLatch (java.util.concurrent.CountDownLatch)32 HttpServerOptions (io.vertx.core.http.HttpServerOptions)31 CompletableFuture (java.util.concurrent.CompletableFuture)31 AtomicReference (java.util.concurrent.atomic.AtomicReference)31 HttpVersion (io.vertx.core.http.HttpVersion)29 HttpConnection (io.vertx.core.http.HttpConnection)28 TestUtils.assertIllegalStateException (io.vertx.test.core.TestUtils.assertIllegalStateException)28 TimeUnit (java.util.concurrent.TimeUnit)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)28 HttpClient (io.vertx.core.http.HttpClient)27 NetSocket (io.vertx.core.net.NetSocket)27 ArrayList (java.util.ArrayList)26 Collections (java.util.Collections)26