Search in sources :

Example 56 with HttpClientRequest

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

the class WebTestBase method testRequestBuffer.

protected void testRequestBuffer(HttpClient client, HttpMethod method, int port, String path, Consumer<HttpClientRequest> requestAction, Consumer<HttpClientResponse> responseAction, int statusCode, String statusMessage, Buffer responseBodyBuffer, boolean normalizeLineEndings) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    HttpClientRequest req = client.request(method, port, "localhost", path, resp -> {
        assertEquals(statusCode, resp.statusCode());
        assertEquals(statusMessage, resp.statusMessage());
        if (responseAction != null) {
            responseAction.accept(resp);
        }
        if (responseBodyBuffer == null) {
            latch.countDown();
        } else {
            resp.bodyHandler(buff -> {
                if (normalizeLineEndings) {
                    buff = normalizeLineEndingsFor(buff);
                }
                assertEquals(responseBodyBuffer, buff);
                latch.countDown();
            });
        }
    });
    if (requestAction != null) {
        requestAction.accept(req);
    }
    req.end();
    awaitLatch(latch);
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 57 with HttpClientRequest

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

use of io.vertx.core.http.HttpClientRequest in project VX-API-Gateway by EliMirren.

the class VxApiRouteHandlerHttpServiceImpl method handle.

@Override
public void handle(RoutingContext rct) {
    // 看有没有可用的服务连接
    if (policy.isHaveService()) {
        // 有可用连接
        // 后台服务连接信息
        VxApiServerURLInfo urlInfo;
        if (serOptions.getBalanceType() == LoadBalanceEnum.IP_HASH) {
            String ip = rct.request().remoteAddress().host();
            urlInfo = policy.getUrl(ip);
        } else {
            urlInfo = policy.getUrl();
        }
        // 执行监控
        VxApiTrackInfos trackInfo = new VxApiTrackInfos(appName, api.getApiName());
        // 统计请求内容长度
        String resLen = rct.request().getHeader("Content-Length");
        trackInfo.setRequestBufferLen(resLen == null ? 0 : StrUtil.getintTry(resLen));
        // 获得请求连接与进行请求
        String requestPath = urlInfo.getUrl();
        MultiMap headers = new CaseInsensitiveHeaders();
        if (serOptions.getParams() != null) {
            // 路径参数
            QueryStringEncoder queryParam = new QueryStringEncoder("");
            for (VxApiParamOptions p : serOptions.getParams()) {
                String param = null;
                if (p.getType() == 0 || p.getType() == 2) {
                    if (p.getApiParamPosition() == ParamPositionEnum.HEADER) {
                        param = rct.request().getHeader(p.getApiParamName());
                    } else {
                        param = rct.request().getParam(p.getApiParamName());
                    }
                } else if (p.getType() == 1) {
                    if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_HOST) {
                        param = rct.request().remoteAddress().host();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_PORT) {
                        param = Integer.toString(rct.request().remoteAddress().port());
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_PATH) {
                        param = rct.request().path() == null ? "" : rct.request().path();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_SESSION_ID) {
                        param = rct.session().id();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_ABSOLUTE_URI) {
                        param = rct.request().absoluteURI();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_REQUEST_SCHEMA) {
                        param = rct.request().scheme();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_API_NAME) {
                        param = api.getApiName();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_UNIX_TIME) {
                        param = Long.toString(System.currentTimeMillis());
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_USER_AGENT) {
                        param = VxApiGatewayAttribute.VX_API_USER_AGENT;
                    }
                } else if (p.getType() == 9) {
                    param = p.getParamValue().toString();
                } else {
                    continue;
                }
                if (p.getSerParamPosition() == ParamPositionEnum.HEADER) {
                    headers.add(p.getSerParamName(), param);
                } else if (p.getSerParamPosition() == ParamPositionEnum.PATH) {
                    requestPath = requestPath.replace(":" + p.getSerParamName(), param);
                } else {
                    queryParam.addParam(p.getSerParamName(), param);
                }
            }
            requestPath += queryParam.toString();
        }
        HttpClientRequest request = httpClient.requestAbs(serOptions.getMethod(), requestPath).setTimeout(serOptions.getTimeOut());
        request.handler(resp -> {
            // 设置请求响应时间
            trackInfo.setResponseTime(Instant.now());
            HttpServerResponse response = rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setChunked(true);
            Pump.pump(resp, response).start();
            resp.endHandler(end -> {
                // 透传header
                Set<String> tranHeaders = api.getResult().getTranHeaders();
                if (tranHeaders != null && tranHeaders.size() > 0) {
                    tranHeaders.forEach(h -> {
                        rct.response().putHeader(h, resp.getHeader(h) == null ? "" : resp.getHeader(h));
                    });
                }
                if (isNext) {
                    // 告诉后置处理器当前操作成功执行
                    rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));
                    rct.next();
                } else {
                    rct.response().end();
                }
                // 统计响应长度
                String repLen = resp.getHeader("Content-Length");
                trackInfo.setResponseBufferLen(repLen == null ? 0 : StrUtil.getintTry(repLen));
                trackInfo.setEndTime(Instant.now());
                rct.vertx().eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_TRACK_INFO, trackInfo.toJson());
            });
        });
        // 异常处理
        request.exceptionHandler(e -> {
            if (isNext) {
                // 告诉后置处理器当前操作成功执行
                rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(e));
                rct.next();
            } else {
                HttpServerResponse response = rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType());
                // 如果是连接异常返回无法连接的错误信息,其他异常返回相应的异常
                if (e instanceof ConnectException || e instanceof TimeoutException) {
                    response.setStatusCode(api.getResult().getCantConnServerStatus()).end(api.getResult().getCantConnServerExample());
                } else {
                    response.setStatusCode(api.getResult().getFailureStatus()).end(api.getResult().getFailureExample());
                }
            }
            // 提交连接请求失败
            policy.reportBadService(urlInfo.getIndex());
            trackInfo.setEndTime(Instant.now());
            // 记录与后台交互发生错误
            trackInfo.setSuccessful(false);
            trackInfo.setErrMsg(e.getMessage());
            trackInfo.setErrStackTrace(e.getStackTrace());
            rct.vertx().eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_TRACK_INFO, trackInfo.toJson());
        });
        // 设置请求时间
        trackInfo.setRequestTime(Instant.now());
        if (headers != null && headers.size() > 0) {
            request.headers().addAll(headers);
        }
        // 设置User-Agent
        String agnet = request.headers().get("User-Agent");
        if (agnet == null) {
            agnet = VxApiGatewayAttribute.VX_API_USER_AGENT;
        } else {
            agnet += " " + VxApiGatewayAttribute.VX_API_USER_AGENT;
        }
        request.putHeader("User-Agent", agnet);
        request.end();
        // 判断是否有坏的连接
        if (policy.isHaveBadService()) {
            if (!policy.isCheckWaiting()) {
                if (webClient == null) {
                    WebClient.create(rct.vertx());
                }
                policy.setCheckWaiting(true);
                rct.vertx().setTimer(serOptions.getRetryTime(), testConn -> {
                    List<VxApiServerURLInfo> service = policy.getBadService();
                    for (VxApiServerURLInfo urlinfo : service) {
                        webClient.requestAbs(serOptions.getMethod(), urlinfo.getUrl()).timeout(serOptions.getTimeOut()).send(res -> {
                            if (res.succeeded()) {
                                policy.reportGreatService(urlinfo.getIndex());
                            }
                        });
                    }
                    policy.setCheckWaiting(false);
                });
            }
        }
    } else {
        // 无可用连接时,结束当前处理器并尝试重新尝试连接是否可用
        if (isNext) {
            // 告诉后置处理器当前操作执行结果
            rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(new ConnectException("无法连接上后台交互的服务器")));
            rct.next();
        } else {
            rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setStatusCode(api.getResult().getCantConnServerStatus()).end(api.getResult().getCantConnServerExample());
        }
        if (!policy.isCheckWaiting()) {
            policy.setCheckWaiting(true);
            rct.vertx().setTimer(serOptions.getRetryTime(), testConn -> {
                List<VxApiServerURLInfo> service = policy.getBadService();
                for (VxApiServerURLInfo urlinfo : service) {
                    webClient.requestAbs(serOptions.getMethod(), urlinfo.getUrl()).timeout(serOptions.getTimeOut()).send(res -> {
                        if (res.succeeded()) {
                            policy.reportGreatService(urlinfo.getIndex());
                        }
                    });
                }
                policy.setCheckWaiting(false);
            });
        }
    }
}
Also used : VxApiTrackInfos(com.szmirren.vxApi.core.entity.VxApiTrackInfos) VxApiParamOptions(com.szmirren.vxApi.core.options.VxApiParamOptions) MultiMap(io.vertx.core.MultiMap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) VxApiServerURLInfo(com.szmirren.vxApi.core.entity.VxApiServerURLInfo) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException)

Example 59 with HttpClientRequest

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

the class OkapiPerformance method useItWithGet.

public void useItWithGet(TestContext context) {
    HttpClientRequest req = httpClient.get(port, "localhost", "/testb", response -> {
        context.assertEquals(200, response.statusCode());
        String headers = response.headers().entries().toString();
        response.handler(x -> {
            context.assertEquals("It works", x.toString());
        });
        response.endHandler(x -> {
            useItWithPost(context);
        });
    });
    req.headers().add("X-Okapi-Token", okapiToken);
    req.putHeader("X-Okapi-Tenant", okapiTenant);
    req.end();
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest)

Example 60 with HttpClientRequest

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

the class OkapiPerformance method repeatPostRun.

public void repeatPostRun(TestContext context, int cnt, int max, int parallels) {
    final String msg = "Okapi" + cnt;
    if (cnt == max) {
        if (--repeatPostRunning == 0) {
            long timeDiff = (System.nanoTime() - startTime) / 1000000;
            logger.info("repeatPost " + timeDiff + " elapsed ms. " + 1000 * max * parallels / timeDiff + " req/sec");
            vertx.setTimer(1, x -> deleteTenant(context));
        }
        return;
    } else if (cnt == 0) {
        if (repeatPostRunning == 0) {
            startTime = System.nanoTime();
        }
        repeatPostRunning++;
        logger.debug("repeatPost " + max + " iterations");
    }
    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 Hello " + msg, body.toString());
            repeatPostRun(context, cnt + 1, max, parallels);
        });
        response.exceptionHandler(e -> {
            context.fail(e);
        });
    });
    req.headers().add("X-Okapi-Token", okapiToken);
    req.putHeader("X-Okapi-Tenant", okapiTenant);
    req.end(msg);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest)

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