Search in sources :

Example 61 with HttpClientRequest

use of io.vertx.core.http.HttpClientRequest in project okapi by folio-org.

the class OkapiPerformance method useItWithPost.

public void useItWithPost(TestContext context) {
    Buffer body = Buffer.buffer();
    HttpClientRequest req = httpClient.post(port, "localhost", "/testb", response -> {
        context.assertEquals(200, response.statusCode());
        String headers = response.headers().entries().toString();
        response.handler(x -> {
            body.appendBuffer(x);
        });
        response.endHandler(x -> {
            context.assertEquals("Hello  (XML) Okapi", body.toString());
            declareSample2(context);
        });
    });
    req.headers().add("X-Okapi-Token", okapiToken);
    req.putHeader("X-Okapi-Tenant", okapiTenant);
    req.putHeader("Content-Type", "text/xml");
    req.end("Okapi");
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest)

Example 62 with HttpClientRequest

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

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

the class HttpModuleClient2 method request.

private void request(HttpMethod method, Buffer data, String endpoint, Map<String, String> headers, boolean cache, Handler<HttpClientResponse> responseHandler, CompletableFuture<Response> cf2) {
    try {
        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);
        if (data != null) {
            request.end(data);
        } else {
            request.end();
        }
    } catch (Exception e) {
        Response r = new Response();
        r.populateError(endpoint, -1, e.getMessage());
        r.exception = e;
        cf2.complete(r);
    }
}
Also used : LoadingCache(com.google.common.cache.LoadingCache) MultiMap(io.vertx.core.MultiMap) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) VertxUtils(org.folio.rest.tools.utils.VertxUtils) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Matcher(java.util.regex.Matcher) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) HttpClientOptions(io.vertx.core.http.HttpClientOptions) PopulateTemplateException(org.folio.rest.tools.client.exceptions.PopulateTemplateException) Logger(io.vertx.core.logging.Logger) PreviousRequestException(org.folio.rest.tools.client.exceptions.PreviousRequestException) Vertx(io.vertx.core.Vertx) JsonPathParser(org.folio.rest.tools.parser.JsonPathParser) PostgresClient(org.folio.rest.persist.PostgresClient) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CacheLoader(com.google.common.cache.CacheLoader) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) HttpClientInterface(org.folio.rest.tools.client.interfaces.HttpClientInterface) HttpMethod(io.vertx.core.http.HttpMethod) Pattern(java.util.regex.Pattern) CacheBuilder(com.google.common.cache.CacheBuilder) Handler(io.vertx.core.Handler) CacheStats(com.google.common.cache.CacheStats) HttpClient(io.vertx.core.http.HttpClient) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClientRequest(io.vertx.core.http.HttpClientRequest) PopulateTemplateException(org.folio.rest.tools.client.exceptions.PopulateTemplateException) PreviousRequestException(org.folio.rest.tools.client.exceptions.PreviousRequestException)

Example 64 with HttpClientRequest

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

use of io.vertx.core.http.HttpClientRequest 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

HttpClientRequest (io.vertx.core.http.HttpClientRequest)159 Test (org.junit.Test)82 Buffer (io.vertx.core.buffer.Buffer)73 HttpClient (io.vertx.core.http.HttpClient)56 HttpMethod (io.vertx.core.http.HttpMethod)51 HttpClientOptions (io.vertx.core.http.HttpClientOptions)50 HttpClientResponse (io.vertx.core.http.HttpClientResponse)42 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)42 Handler (io.vertx.core.Handler)40 HttpServerResponse (io.vertx.core.http.HttpServerResponse)40 CompletableFuture (java.util.concurrent.CompletableFuture)38 CountDownLatch (java.util.concurrent.CountDownLatch)36 TimeUnit (java.util.concurrent.TimeUnit)36 Vertx (io.vertx.core.Vertx)35 HttpServerOptions (io.vertx.core.http.HttpServerOptions)35 ArrayList (java.util.ArrayList)35 List (java.util.List)35 AtomicReference (java.util.concurrent.atomic.AtomicReference)34 MultiMap (io.vertx.core.MultiMap)33 HttpVersion (io.vertx.core.http.HttpVersion)31