Search in sources :

Example 21 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-web by vert-x3.

the class RoutingContextNullCurrentRouteTest method test.

@Test
public void test(TestContext testContext) {
    HttpClient client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(10000));
    Async async = testContext.async();
    HttpClientRequest httpClientRequest = client.get(PORT, "127.0.0.1", "/test", httpClientResponse -> {
        testContext.assertEquals(HttpURLConnection.HTTP_NO_CONTENT, httpClientResponse.statusCode());
        async.complete();
    }).exceptionHandler(testContext::fail);
    httpClientRequest.end();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) HttpURLConnection(java.net.HttpURLConnection) Async(io.vertx.ext.unit.Async) Vertx(io.vertx.core.Vertx) RunWith(org.junit.runner.RunWith) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) After(org.junit.After) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClient(io.vertx.core.http.HttpClient) Before(org.junit.Before) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Test(org.junit.Test)

Example 22 with HttpClient

use of io.vertx.core.http.HttpClient in project gravitee-management-rest-api by gravitee-io.

the class WebhookNotifierServiceImpl method trigger.

@Override
public void trigger(final Hook hook, GenericNotificationConfig genericNotificationConfig, final Map<String, Object> params) {
    if (genericNotificationConfig.getConfig() == null || genericNotificationConfig.getConfig().isEmpty()) {
        LOGGER.error("Webhook Notifier configuration is empty");
        return;
    }
    URI requestUri = URI.create(genericNotificationConfig.getConfig());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());
    final HttpClientOptions options = new HttpClientOptions().setSsl(ssl).setTrustAll(true).setMaxPoolSize(1).setKeepAlive(false).setTcpKeepAlive(false).setConnectTimeout(GLOBAL_TIMEOUT);
    final HttpClient httpClient = vertx.createHttpClient(options);
    final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);
    HttpClientRequest request = httpClient.post(port, requestUri.getHost(), requestUri.toString(), response -> LOGGER.debug("Webhook response status code : {}", response.statusCode()));
    request.setTimeout(GLOBAL_TIMEOUT);
    // body
    String body = toJson(hook, params);
    // headers
    request.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    request.putHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(body.length()));
    request.putHeader("X-Gravitee-Event", hook.name());
    request.putHeader("X-Gravitee-Event-Scope", hook.getScope().name());
    request.putHeader("X-Gravitee-Request-Id", UUID.toString(UUID.random()));
    request.write(body);
    request.end();
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) URI(java.net.URI) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Example 23 with HttpClient

use of io.vertx.core.http.HttpClient in project raml-module-builder by folio-org.

the class HttpModuleClient method request.

private void request(HttpMethod method, String endpoint, Map<String, String> headers, boolean cache, Handler<HttpClientResponse> responseHandler, CompletableFuture<Response> cf2) {
    if (responseHandler == null) {
        CompletableFuture<Response> cf = new CompletableFuture<>();
        responseHandler = new HTTPJsonResponseHandler(endpoint, cf);
    }
    httpClient = vertx.createHttpClient(options);
    HttpClientRequest request = null;
    if (absoluteHostAddr) {
        request = httpClient.requestAbs(method, options.getDefaultHost() + endpoint);
    } else {
        request = httpClient.request(method, endpoint);
    }
    request.exceptionHandler(error -> {
        Response r = new Response();
        r.populateError(endpoint, -1, error.getMessage());
        cf2.complete(r);
    }).handler(responseHandler);
    if (headers != null) {
        this.headers.putAll(headers);
    }
    request.headers().setAll(this.headers);
    request.end();
}
Also used : HttpClientResponse(io.vertx.core.http.HttpClientResponse) LoadingCache(com.google.common.cache.LoadingCache) Vertx(io.vertx.core.Vertx) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) VertxUtils(org.folio.rest.tools.utils.VertxUtils) LoggerFactory(io.vertx.core.logging.LoggerFactory) TimeUnit(java.util.concurrent.TimeUnit) CacheLoader(com.google.common.cache.CacheLoader) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) JsonArray(io.vertx.core.json.JsonArray) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) CacheBuilder(com.google.common.cache.CacheBuilder) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) CacheStats(com.google.common.cache.CacheStats) HttpClient(io.vertx.core.http.HttpClient) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClientRequest(io.vertx.core.http.HttpClientRequest)

Example 24 with HttpClient

use of io.vertx.core.http.HttpClient in project raml-module-builder by folio-org.

the class DemoRamlRestTest method postData.

/**
 * for POST
 */
private void postData(TestContext context, String url, Buffer buffer, int errorCode, int mode, String contenttype, String tenant, boolean userIdHeader) {
    // save stacktrace for async handler
    Exception stacktrace = new RuntimeException();
    Async async = context.async();
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest request = null;
    if (mode == 0) {
        request = client.putAbs(url);
    } else if (mode == 1) {
        request = client.postAbs(url);
    } else {
        request = client.deleteAbs(url);
    }
    request.exceptionHandler(error -> {
        async.complete();
        context.fail(new RuntimeException(error.getMessage(), stacktrace));
    }).handler(response -> {
        int statusCode = response.statusCode();
        // is it 2XX
        log.info(statusCode + ", " + errorCode + " expected status at " + System.currentTimeMillis() + " mode " + mode + " for " + url);
        if (statusCode == errorCode) {
            if (statusCode == 422) {
                String str = response.getHeader("Content-type");
                if (str != null && str.contains("application/json")) {
                    context.assertTrue(true);
                } else {
                    context.fail(new RuntimeException("422 response code should contain a content type header of application/json", stacktrace));
                }
            } else if (statusCode == 201) {
                response.bodyHandler(responseData -> {
                    String date = (String) new JsonPathParser(responseData.toJsonObject()).getValueAt("metadata.createdDate");
                    if (date == null && userIdHeader) {
                        context.fail(new RuntimeException("metaData schema createdDate missing from returned json", stacktrace));
                    }
                });
            }
            context.assertTrue(true);
        } else {
            response.bodyHandler(responseData -> {
                context.fail(new RuntimeException("got unexpected response code, expected: " + errorCode + ", received code: " + statusCode + " mode " + mode + " for url " + url + "\ndata:" + responseData.toString(), stacktrace));
            });
        }
        if (!async.isCompleted()) {
            async.complete();
        }
    });
    request.setChunked(true);
    request.putHeader("X-Okapi-Request-Id", "999999999999");
    if (tenant != null) {
        request.putHeader("x-okapi-tenant", tenant);
    }
    request.putHeader("Accept", "application/json,text/plain");
    if (userIdHeader) {
        request.putHeader("X-Okapi-User-Id", "af23adf0-61ba-4887-bf82-956c4aae2260");
    }
    if (contenttype != null) {
        request.putHeader("Content-type", contenttype);
    } else {
        if (mode == 0 || mode == 2) {
            request.putHeader("Content-type", "application/json");
        } else {
            request.putHeader("Content-type", "multipart/form-data; boundary=MyBoundary");
        }
    }
    if (buffer != null) {
        request.write(buffer);
    }
    request.end();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) RestVerticle(org.folio.rest.RestVerticle) BeforeClass(org.junit.BeforeClass) AES(org.folio.rest.security.AES) Date(java.util.Date) MimeBodyPart(javax.mail.internet.MimeBodyPart) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) VertxUtils(org.folio.rest.tools.utils.VertxUtils) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) BodyPart(javax.mail.BodyPart) BigDecimal(java.math.BigDecimal) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Locale(java.util.Locale) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) JsonObject(io.vertx.core.json.JsonObject) Datetime(org.folio.rest.jaxrs.model.Datetime) Metadata(org.folio.rest.jaxrs.model.Metadata) Logger(io.vertx.core.logging.Logger) MimeMultipart(javax.mail.internet.MimeMultipart) AfterClass(org.junit.AfterClass) RmbtestsClient(org.folio.rest.client.RmbtestsClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Test(org.junit.Test) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) Data(org.folio.rest.jaxrs.model.Data) File(java.io.File) NetworkUtils(org.folio.rest.tools.utils.NetworkUtils) Book(org.folio.rest.jaxrs.model.Book) IOUtils(org.apache.commons.io.IOUtils) Messages(org.folio.rest.tools.messages.Messages) List(java.util.List) InternetHeaders(javax.mail.internet.InternetHeaders) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AdminClient(org.folio.rest.client.AdminClient) HttpMethod(io.vertx.core.http.HttpMethod) SecretKey(javax.crypto.SecretKey) PersistMethod(org.folio.rest.jaxrs.resource.AdminResource.PersistMethod) Handler(io.vertx.core.Handler) HttpClient(io.vertx.core.http.HttpClient) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 25 with HttpClient

use of io.vertx.core.http.HttpClient in project raml-module-builder by folio-org.

the class DemoRamlRestTest method jobsTest.

/**
 * @param context
 */
private void jobsTest(TestContext context) {
    String url = "/jobs/jobconfs";
    Async async = context.async();
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest request = null;
    request = client.postAbs("http://localhost:" + port + url);
    request.exceptionHandler(error -> {
        async.complete();
        context.fail(error.getMessage());
    }).handler(response -> {
        int statusCode = response.statusCode();
        String location = response.getHeader("Location");
        // is it 2XX
        log.info(statusCode + " status at " + System.currentTimeMillis() + " for " + "http://localhost:" + port + url);
        if (statusCode == 201) {
            checkURLs(context, "http://localhost:" + port + url, 200);
            try {
                postData(context, "http://localhost:" + port + url + "/" + location + "/jobs", Buffer.buffer(getFile("job.json")), 201, 1, "application/json", TENANT, false);
                postData(context, "http://localhost:" + port + url + "/" + location, Buffer.buffer(getFile("job_conf_post.json")), 204, 0, null, TENANT, false);
                postData(context, "http://localhost:" + port + url + "/12345", Buffer.buffer(getFile("job_conf_post.json")), 404, 2, null, TENANT, false);
                postData(context, "http://localhost:" + port + url + "/" + location + "/jobs/12345", Buffer.buffer(getFile("job_conf_post.json")), 404, 2, null, TENANT, false);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                context.fail();
            }
        } else {
            context.fail("got incorrect response code");
        }
        if (!async.isCompleted()) {
            async.complete();
        }
    });
    request.setChunked(true);
    request.putHeader("Accept", "application/json,text/plain");
    request.putHeader("Content-type", "application/json");
    try {
        request.write(getFile("job_conf_post.json"));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        context.fail("unable to read file");
    }
    request.end();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) RestVerticle(org.folio.rest.RestVerticle) BeforeClass(org.junit.BeforeClass) AES(org.folio.rest.security.AES) Date(java.util.Date) MimeBodyPart(javax.mail.internet.MimeBodyPart) RunWith(org.junit.runner.RunWith) SimpleDateFormat(java.text.SimpleDateFormat) VertxUtils(org.folio.rest.tools.utils.VertxUtils) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) BodyPart(javax.mail.BodyPart) BigDecimal(java.math.BigDecimal) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Locale(java.util.Locale) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) JsonObject(io.vertx.core.json.JsonObject) Datetime(org.folio.rest.jaxrs.model.Datetime) Metadata(org.folio.rest.jaxrs.model.Metadata) Logger(io.vertx.core.logging.Logger) MimeMultipart(javax.mail.internet.MimeMultipart) AfterClass(org.junit.AfterClass) RmbtestsClient(org.folio.rest.client.RmbtestsClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Test(org.junit.Test) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) Data(org.folio.rest.jaxrs.model.Data) File(java.io.File) NetworkUtils(org.folio.rest.tools.utils.NetworkUtils) Book(org.folio.rest.jaxrs.model.Book) IOUtils(org.apache.commons.io.IOUtils) Messages(org.folio.rest.tools.messages.Messages) List(java.util.List) InternetHeaders(javax.mail.internet.InternetHeaders) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AdminClient(org.folio.rest.client.AdminClient) HttpMethod(io.vertx.core.http.HttpMethod) SecretKey(javax.crypto.SecretKey) PersistMethod(org.folio.rest.jaxrs.resource.AdminResource.PersistMethod) Handler(io.vertx.core.Handler) HttpClient(io.vertx.core.http.HttpClient) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) IOException(java.io.IOException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

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