Search in sources :

Example 36 with CaseInsensitiveHeaders

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

the class CaseInsensitiveHeadersTest method testSize.

@Test
public void testSize() throws Exception {
    MultiMap mmap = new CaseInsensitiveHeaders();
    assertEquals(0, mmap.size());
    mmap.add("header", "value");
    assertEquals(1, mmap.size());
    mmap.add("header2", "value2");
    assertEquals(2, mmap.size());
    mmap.add("header", "value3");
    assertEquals(2, mmap.size());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) Test(org.junit.Test)

Example 37 with CaseInsensitiveHeaders

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

the class CaseInsensitiveHeadersTest method testIsEmptyTest2.

@Test
public void testIsEmptyTest2() throws Exception {
    MultiMap mmap = new CaseInsensitiveHeaders();
    mmap.add("a", "b");
    assertFalse(mmap.isEmpty());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) Test(org.junit.Test)

Example 38 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project incubator-servicecomb-java-chassis by apache.

the class TestDefaultHttpClientFilter method testAfterReceiveResponseNormal.

@Test
public void testAfterReceiveResponseNormal(@Mocked Invocation invocation, @Mocked HttpServletResponseEx responseEx, @Mocked Buffer bodyBuffer, @Mocked OperationMeta operationMeta, @Mocked ResponseMeta responseMeta, @Mocked RestOperationMeta swaggerRestOperation, @Mocked ProduceProcessor produceProcessor) throws Exception {
    MultiMap responseHeader = new CaseInsensitiveHeaders();
    responseHeader.add("b", "bValue");
    Object decodedResult = new Object();
    new Expectations() {

        {
            responseEx.getHeader(HttpHeaders.CONTENT_TYPE);
            result = "json";
            responseEx.getHeaderNames();
            result = Arrays.asList("a", "b");
            responseEx.getHeaders("b");
            result = responseHeader.getAll("b");
            swaggerRestOperation.findProduceProcessor("json");
            result = produceProcessor;
            produceProcessor.decodeResponse(bodyBuffer, responseMeta.getJavaType());
            result = decodedResult;
            invocation.getOperationMeta();
            result = operationMeta;
            operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
            result = swaggerRestOperation;
            responseEx.getStatusType();
            result = Status.OK;
        }
    };
    Response response = filter.afterReceiveResponse(invocation, responseEx);
    Assert.assertSame(decodedResult, response.getResult());
    Assert.assertEquals(1, response.getHeaders().getHeaderMap().size());
    Assert.assertEquals(response.getHeaders().getHeader("b"), Arrays.asList("bValue"));
}
Also used : Expectations(mockit.Expectations) Response(org.apache.servicecomb.swagger.invocation.Response) MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) Test(org.junit.Test)

Example 39 with CaseInsensitiveHeaders

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

the class EventBusBridgeImpl method checkAndSend.

private void checkAndSend(boolean send, String address, Object body, JsonObject headers, SockJSSocket sock, String replyAddress, Message awaitingReply) {
    SockInfo info = sockInfos.get(sock);
    if (replyAddress != null && !checkMaxHandlers(sock, info)) {
        return;
    }
    Handler<AsyncResult<Message<Object>>> replyHandler;
    if (replyAddress != null) {
        replyHandler = result -> {
            if (result.succeeded()) {
                Message message = result.result();
                // Note we don't check outbound matches for replies
                // Replies are always let through if the original message
                // was approved
                // Now - the reply message might itself be waiting for a reply - which would be inbound -so we need
                // to add the message to the messages awaiting reply so it can be let through
                checkAddAccceptedReplyAddress(message);
                deliverMessage(sock, replyAddress, message);
            } else {
                ReplyException cause = (ReplyException) result.cause();
                JsonObject envelope = new JsonObject().put("type", "err").put("address", replyAddress).put("failureCode", cause.failureCode()).put("failureType", cause.failureType().name()).put("message", cause.getMessage());
                sock.write(buffer(envelope.encode()));
            }
            info.handlerCount--;
        };
    } else {
        replyHandler = null;
    }
    if (log.isDebugEnabled()) {
        log.debug("Forwarding message to address " + address + " on event bus");
    }
    MultiMap mHeaders;
    if (headers != null) {
        mHeaders = new CaseInsensitiveHeaders();
        headers.forEach(entry -> mHeaders.add(entry.getKey(), entry.getValue().toString()));
    } else {
        mHeaders = null;
    }
    if (send) {
        if (awaitingReply != null) {
            awaitingReply.reply(body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders), replyHandler);
        } else {
            eb.send(address, body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders), replyHandler);
        }
        if (replyAddress != null) {
            info.handlerCount++;
        }
    } else {
        eb.publish(address, body, new DeliveryOptions().setHeaders(mHeaders));
    }
}
Also used : CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject)

Example 40 with CaseInsensitiveHeaders

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

the class SessionTokenGrantAuthHandler 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(api.getAppName(), api.getApiName());
        trackInfo.setRequestBufferLen(rct.getBody() == null ? 0 : rct.getBody().length());
        String requestPath = urlInfo.getUrl();
        MultiMap headers = new CaseInsensitiveHeaders();
        MultiMap queryParams = new CaseInsensitiveHeaders();
        if (serOptions.getParams() != null) {
            for (VxApiParamOptions p : serOptions.getParams()) {
                String param = "";
                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.replace(":" + p.getSerParamName(), param);
                } else {
                    queryParams.add(p.getSerParamName(), param);
                }
            }
        }
        HttpRequest<Buffer> request = webClient.requestAbs(serOptions.getMethod(), requestPath).timeout(serOptions.getTimeOut());
        headers.forEach(va -> request.putHeader(va.getKey(), va.getValue()));
        queryParams.forEach(va -> request.addQueryParam(va.getKey(), va.getValue()));
        trackInfo.setRequestTime(Instant.now());
        request.send(res -> {
            trackInfo.setResponseTime(Instant.now());
            if (res.succeeded()) {
                HttpResponse<Buffer> result = res.result();
                Set<String> tranHeaders = api.getResult().getTranHeaders();
                if (tranHeaders != null && tranHeaders.size() > 0) {
                    tranHeaders.forEach(h -> {
                        rct.response().putHeader(h, result.getHeader(h) == null ? "" : result.getHeader(h));
                    });
                }
                HttpServerResponse response = rct.response();
                // 得到后台服务传过来的token
                String token = res.result().getHeader(getTokenName);
                if (token != null && !"".equals(token)) {
                    rct.session().put(saveTokenName, token);
                }
                response.putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE, api.getContentType()).setChunked(true).write(result.body());
                if (isNext) {
                    // 告诉后置处理器当前操作成功执行
                    rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));
                    rct.next();
                } else {
                    response.end();
                }
                trackInfo.setResponseBufferLen(result.body() == null ? 0 : result.body().length());
                trackInfo.setEndTime(Instant.now());
            } else {
                if (isNext) {
                    // 告诉后置处理器当前操作成功执行
                    rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(res.cause()));
                    rct.next();
                } else {
                    HttpServerResponse response = rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE, api.getContentType());
                    // 如果是连接异常返回无法连接的错误信息,其他异常返回相应的异常
                    if (res.cause() instanceof ConnectException || res.cause() 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(res.cause().getMessage());
                trackInfo.setErrStackTrace(res.cause().getStackTrace());
            }
            rct.vertx().eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_TRACK_INFO, trackInfo.toJson());
        });
        // 判断是否有坏的连接
        if (policy.isHaveBadService()) {
            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);
                });
            }
        }
    } else {
        // 无可用连接时,结束当前处理器并尝试重新尝试连接是否可用
        if (isNext) {
            // 告诉后置处理器当前操作执行结果
            rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(new ConnectException("无法连接上后台交互的服务器")));
            rct.next();
        } else {
            rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.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) Buffer(io.vertx.core.buffer.Buffer) VxApiParamOptions(com.szmirren.vxApi.core.options.VxApiParamOptions) MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) VxApiServerURLInfo(com.szmirren.vxApi.core.entity.VxApiServerURLInfo) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

CaseInsensitiveHeaders (io.vertx.core.http.CaseInsensitiveHeaders)69 MultiMap (io.vertx.core.MultiMap)65 Test (org.junit.Test)64 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10 Buffer (io.vertx.core.buffer.Buffer)3 VxApiServerURLInfo (com.szmirren.vxApi.core.entity.VxApiServerURLInfo)2 VxApiTrackInfos (com.szmirren.vxApi.core.entity.VxApiTrackInfos)2 VxApiParamOptions (com.szmirren.vxApi.core.options.VxApiParamOptions)2 HttpClientRequest (io.vertx.core.http.HttpClientRequest)2 HttpServerResponse (io.vertx.core.http.HttpServerResponse)2 JsonObject (io.vertx.core.json.JsonObject)2 ConnectException (java.net.ConnectException)2 Map (java.util.Map)2 TimeoutException (java.util.concurrent.TimeoutException)2 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)1 QueryStringEncoder (io.netty.handler.codec.http.QueryStringEncoder)1 WebSocket (io.vertx.core.http.WebSocket)1 WebSocketFrame (io.vertx.core.http.WebSocketFrame)1 FrameType (io.vertx.core.http.impl.FrameType)1