Search in sources :

Example 51 with HttpClientRequest

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

the class PullManager method getList.

private void getList(String urlBase, Handler<ExtendedAsyncResult<ModuleDescriptor[]>> fut) {
    String url = urlBase;
    if (!url.endsWith("/")) {
        url += "/";
    }
    url += "_/proxy/modules";
    final Buffer body = Buffer.buffer();
    HttpClientRequest req = httpClient.getAbs(url, res -> {
        res.handler(body::appendBuffer);
        res.endHandler(x -> {
            if (res.statusCode() != 200) {
                fut.handle(new Failure<>(ErrorType.USER, body.toString()));
            } else {
                ModuleDescriptor[] ml = Json.decodeValue(body.toString(), ModuleDescriptor[].class);
                fut.handle(new Success<>(ml));
            }
        });
        res.exceptionHandler(x -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage())));
    });
    req.exceptionHandler(x -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage())));
    req.end();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ModuleDescriptor(org.folio.okapi.bean.ModuleDescriptor) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Failure(org.folio.okapi.common.Failure)

Example 52 with HttpClientRequest

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

the class PullManager method getFullReq.

private void getFullReq(String url, Handler<ExtendedAsyncResult<List<ModuleDescriptor>>> fut, List<ModuleDescriptor> ml, String urlBase, Iterator<ModuleDescriptor> it) {
    final Buffer body = Buffer.buffer();
    HttpClientRequest req = httpClient.getAbs(url, res -> {
        res.handler(body::appendBuffer);
        res.endHandler(x -> {
            if (concurrentRuns > 0) {
                concurrentRuns--;
            }
            if (res.statusCode() != 200) {
                if (!concurrentComplete) {
                    concurrentComplete = true;
                    fut.handle(new Failure<>(ErrorType.USER, body.toString()));
                }
            } else {
                ModuleDescriptor md = Json.decodeValue(body.toString(), ModuleDescriptor.class);
                ml.add(md);
                getFull(urlBase, it, ml, fut);
            }
        });
        res.exceptionHandler(x -> {
            if (concurrentRuns > 0) {
                concurrentRuns--;
            }
            if (!concurrentComplete) {
                concurrentComplete = true;
                fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage()));
            }
        });
    });
    req.exceptionHandler(x -> {
        if (concurrentRuns > 0) {
            concurrentRuns--;
        }
        if (!concurrentComplete) {
            concurrentComplete = true;
            fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage()));
        }
    });
    req.end();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ModuleDescriptor(org.folio.okapi.bean.ModuleDescriptor) HttpClientRequest(io.vertx.core.http.HttpClientRequest)

Example 53 with HttpClientRequest

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

the class DockerModuleHandle method getContainerLog.

private void getContainerLog(Handler<AsyncResult<Void>> future) {
    final String url = dockerUrl + "/containers/" + containerId + "/logs?stderr=1&stdout=1&follow=1";
    HttpClientRequest req = client.getAbs(url, res -> {
        if (res.statusCode() == 200) {
            // stream OK. Continue other work but keep fetching!
            // remove 8 bytes of binary data and final newline
            res.handler(d -> logger.info(d.getString(8, d.length() - 1)));
            future.handle(Future.succeededFuture());
        } else {
            String m = "getContainerLog HTTP error " + Integer.toString(res.statusCode());
            logger.error(m);
            future.handle(Future.failedFuture(m));
        }
    });
    req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause())));
    req.end();
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest)

Example 54 with HttpClientRequest

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

the class HttpContext method sendRequest.

private void sendRequest() {
    Future<HttpClientResponse> responseFuture = Future.<HttpClientResponse>future().setHandler(ar -> {
        Context context = Vertx.currentContext();
        if (ar.succeeded()) {
            HttpClientResponse resp = ar.result();
            Future<HttpResponse<Object>> fut = Future.future();
            fut.setHandler(r -> {
                // We are running on a context (the HTTP client mandates it)
                context.runOnContext(v -> currentResponseHandler.handle(r));
            });
            resp.exceptionHandler(err -> {
                if (!fut.isComplete()) {
                    fut.fail(err);
                }
            });
            resp.pause();
            ((BodyCodec<Object>) request.codec).create(ar2 -> {
                resp.resume();
                if (ar2.succeeded()) {
                    BodyStream<Object> stream = ar2.result();
                    stream.exceptionHandler(err -> {
                        if (!fut.isComplete()) {
                            fut.fail(err);
                        }
                    });
                    resp.endHandler(v -> {
                        if (!fut.isComplete()) {
                            stream.end();
                            if (stream.result().succeeded()) {
                                fut.complete(new HttpResponseImpl<>(resp, null, stream.result().result()));
                            } else {
                                fut.fail(stream.result().cause());
                            }
                        }
                    });
                    Pump responsePump = Pump.pump(resp, stream);
                    responsePump.start();
                } else {
                    currentResponseHandler.handle(Future.failedFuture(ar2.cause()));
                }
            });
        } else {
            currentResponseHandler.handle(Future.failedFuture(ar.cause()));
        }
    });
    HttpClientRequest req;
    String requestURI;
    if (request.queryParams() != null && request.queryParams().size() > 0) {
        QueryStringEncoder enc = new QueryStringEncoder(request.uri);
        request.queryParams().forEach(param -> enc.addParam(param.getKey(), param.getValue()));
        requestURI = enc.toString();
    } else {
        requestURI = request.uri;
    }
    int port = request.port;
    String host = request.host;
    if (request.ssl != request.options.isSsl()) {
        req = request.client.client.request(request.method, new RequestOptions().setSsl(request.ssl).setHost(host).setPort(port).setURI(requestURI));
    } else {
        if (request.protocol != null && !request.protocol.equals("http") && !request.protocol.equals("https")) {
            // we have to create an abs url again to parse it in HttpClient
            try {
                URI uri = new URI(request.protocol, null, host, port, requestURI, null, null);
                req = request.client.client.requestAbs(request.method, uri.toString());
            } catch (URISyntaxException ex) {
                currentResponseHandler.handle(Future.failedFuture(ex));
                return;
            }
        } else {
            req = request.client.client.request(request.method, port, host, requestURI);
        }
    }
    if (request.virtualHost != null) {
        String virtalHost = request.virtualHost;
        if (port != 80) {
            virtalHost += ":" + port;
        }
        req.setHost(virtalHost);
    }
    req.setFollowRedirects(request.followRedirects);
    if (request.headers != null) {
        req.headers().addAll(request.headers);
    }
    req.handler(responseFuture::tryComplete);
    if (request.timeout > 0) {
        req.setTimeout(request.timeout);
    }
    if (body != null) {
        if (contentType != null) {
            String prev = req.headers().get(HttpHeaders.CONTENT_TYPE);
            if (prev == null) {
                req.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
            } else {
                contentType = prev;
            }
        }
        if (body instanceof ReadStream<?>) {
            ReadStream<Buffer> stream = (ReadStream<Buffer>) body;
            if (request.headers == null || !request.headers.contains(HttpHeaders.CONTENT_LENGTH)) {
                req.setChunked(true);
            }
            Pump pump = Pump.pump(stream, req);
            req.exceptionHandler(err -> {
                pump.stop();
                stream.endHandler(null);
                stream.resume();
                responseFuture.tryFail(err);
            });
            stream.exceptionHandler(err -> {
                req.reset();
                responseFuture.tryFail(err);
            });
            stream.endHandler(v -> {
                req.exceptionHandler(responseFuture::tryFail);
                req.end();
                pump.stop();
            });
            pump.start();
        } else {
            Buffer buffer;
            if (body instanceof Buffer) {
                buffer = (Buffer) body;
            } else if (body instanceof MultiMap) {
                try {
                    MultiMap attributes = (MultiMap) body;
                    boolean multipart = "multipart/form-data".equals(contentType);
                    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.POST, "/");
                    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, multipart);
                    for (Map.Entry<String, String> attribute : attributes) {
                        encoder.addBodyAttribute(attribute.getKey(), attribute.getValue());
                    }
                    encoder.finalizeRequest();
                    for (String headerName : request.headers().names()) {
                        req.putHeader(headerName, request.headers().get(headerName));
                    }
                    if (encoder.isChunked()) {
                        buffer = Buffer.buffer();
                        while (true) {
                            HttpContent chunk = encoder.readChunk(new UnpooledByteBufAllocator(false));
                            ByteBuf content = chunk.content();
                            if (content.readableBytes() == 0) {
                                break;
                            }
                            buffer.appendBuffer(Buffer.buffer(content));
                        }
                    } else {
                        ByteBuf content = request.content();
                        buffer = Buffer.buffer(content);
                    }
                } catch (Exception e) {
                    throw new VertxException(e);
                }
            } else if (body instanceof JsonObject) {
                buffer = Buffer.buffer(((JsonObject) body).encode());
            } else {
                buffer = Buffer.buffer(Json.encode(body));
            }
            req.exceptionHandler(responseFuture::tryFail);
            req.end(buffer);
        }
    } else {
        req.exceptionHandler(responseFuture::tryFail);
        req.end();
    }
}
Also used : RequestOptions(io.vertx.core.http.RequestOptions) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) JsonObject(io.vertx.core.json.JsonObject) URISyntaxException(java.net.URISyntaxException) ByteBuf(io.netty.buffer.ByteBuf) URI(java.net.URI) MultiMap(io.vertx.core.MultiMap) UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) VertxException(io.vertx.core.VertxException) HttpClientResponse(io.vertx.core.http.HttpClientResponse) ReadStream(io.vertx.core.streams.ReadStream) Context(io.vertx.core.Context) BodyCodec(io.vertx.ext.web.codec.BodyCodec) Buffer(io.vertx.core.buffer.Buffer) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponse(io.vertx.ext.web.client.HttpResponse) Pump(io.vertx.core.streams.Pump) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) HttpClientRequest(io.vertx.core.http.HttpClientRequest) JsonObject(io.vertx.core.json.JsonObject) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 55 with HttpClientRequest

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

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