Search in sources :

Example 1 with HttpClient

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

the class HostnameResolutionTest method testHttp.

@Test
public void testHttp() throws Exception {
    HttpClient client = vertx.createHttpClient();
    HttpServer server = vertx.createHttpServer().requestHandler(req -> {
        req.response().end("foo");
    });
    try {
        CountDownLatch listenLatch = new CountDownLatch(1);
        server.listen(8080, "vertx.io", onSuccess(s -> {
            listenLatch.countDown();
        }));
        awaitLatch(listenLatch);
        client.getNow(8080, "vertx.io", "/somepath", resp -> {
            Buffer buffer = Buffer.buffer();
            resp.handler(buffer::appendBuffer);
            resp.endHandler(v -> {
                assertEquals(Buffer.buffer("foo"), buffer);
                testComplete();
            });
        });
        await();
    } finally {
        client.close();
        server.close();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) VertxException(io.vertx.core.VertxException) Arrays(java.util.Arrays) HttpServer(io.vertx.core.http.HttpServer) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AddressResolverOptions(io.vertx.core.dns.AddressResolverOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Locale(java.util.Locale) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Collections(java.util.Collections) HttpClient(io.vertx.core.http.HttpClient) Buffer(io.vertx.core.buffer.Buffer) HttpClient(io.vertx.core.http.HttpClient) HttpServer(io.vertx.core.http.HttpServer) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 2 with HttpClient

use of io.vertx.core.http.HttpClient 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 3 with HttpClient

use of io.vertx.core.http.HttpClient 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 4 with HttpClient

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

the class HttpTest method testDumpManyRequestsOnQueue.

@Test
public void testDumpManyRequestsOnQueue() throws Exception {
    int sendRequests = 10000;
    AtomicInteger receivedRequests = new AtomicInteger();
    vertx.createHttpServer(createBaseServerOptions()).requestHandler(r -> {
        r.response().end();
        if (receivedRequests.incrementAndGet() == sendRequests) {
            testComplete();
        }
    }).listen(onSuccess(s -> {
        HttpClientOptions ops = createBaseClientOptions().setDefaultPort(DEFAULT_HTTP_PORT).setPipelining(true).setKeepAlive(true);
        HttpClient client = vertx.createHttpClient(ops);
        IntStream.range(0, sendRequests).forEach(x -> client.getNow("/", r -> {
        }));
    }));
    await();
}
Also used : 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpClient(io.vertx.core.http.HttpClient) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Test(org.junit.Test)

Example 5 with HttpClient

use of io.vertx.core.http.HttpClient in project java-chassis by ServiceComb.

the class TestVertxPutMethod method testVertxPutMethod.

@Test
public void testVertxPutMethod() {
    HttpClient client = Mockito.mock(HttpClient.class);
    Invocation invocation = Mockito.mock(Invocation.class);
    IpPort ipPort = Mockito.mock(IpPort.class);
    RestOperationMeta operation = Mockito.mock(RestOperationMeta.class);
    AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class);
    Mockito.when(ipPort.getHostOrIp()).thenReturn("test");
    assertNotNull("test", ipPort.getHostOrIp());
    Mockito.when(ipPort.getPort()).thenReturn(13);
    assertEquals(13, ipPort.getPort());
    HttpClientRequest obj = VertxPutMethod.INSTANCE.createRequest(client, invocation, ipPort, "testCall", operation, asyncResp);
    Assert.assertNull(obj);
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) Invocation(io.servicecomb.core.Invocation) RestOperationMeta(io.servicecomb.common.rest.definition.RestOperationMeta) HttpClient(io.vertx.core.http.HttpClient) IpPort(io.servicecomb.foundation.common.net.IpPort) AsyncResponse(io.servicecomb.core.AsyncResponse) Test(org.junit.Test)

Aggregations

HttpClient (io.vertx.core.http.HttpClient)77 Test (org.junit.Test)47 HttpClientRequest (io.vertx.core.http.HttpClientRequest)36 HttpClientOptions (io.vertx.core.http.HttpClientOptions)25 Vertx (io.vertx.core.Vertx)22 HttpMethod (io.vertx.core.http.HttpMethod)22 JsonObject (io.vertx.core.json.JsonObject)22 Handler (io.vertx.core.Handler)18 Buffer (io.vertx.core.buffer.Buffer)18 HttpClientResponse (io.vertx.core.http.HttpClientResponse)16 TimeUnit (java.util.concurrent.TimeUnit)16 HttpServer (io.vertx.core.http.HttpServer)15 Async (io.vertx.ext.unit.Async)15 Before (org.junit.Before)15 File (java.io.File)14 CountDownLatch (java.util.concurrent.CountDownLatch)14 URL (java.net.URL)12 HttpServerOptions (io.vertx.core.http.HttpServerOptions)11 IOException (java.io.IOException)10 List (java.util.List)10