Java 类io.vertx.core.http.HttpServerRequest 实例源码

项目:incubator-servicecomb-java-chassis    文件:RequestHeaderElementTest.java   
@Test
public void getFormattedElement() {
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  AccessLogParam param = new AccessLogParam().setRoutingContext(mockContext);
  HttpServerRequest mockRequest = Mockito.mock(HttpServerRequest.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String testValue = "testValue";
  headers.add(HEADER_IDENTIFIER, testValue);

  Mockito.when(mockContext.request()).thenReturn(mockRequest);
  Mockito.when(mockRequest.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals(testValue, result);
  assertEquals(ELEMENT.getIdentifier(), HEADER_IDENTIFIER);
}
项目:incubator-servicecomb-java-chassis    文件:TestVertxServerRequestToHttpServletRequest.java   
@Test
public void setBodyBuffer() {
  Holder<Buffer> bodyHolder = new Holder<>();
  context = new MockUp<RoutingContext>() {
    @Mock
    HttpServerRequest request() {
      return vertxRequest;
    }

    @Mock
    void setBody(Buffer body) {
      bodyHolder.value = body;
    }
  }.getMockInstance();
  request = new VertxServerRequestToHttpServletRequest(context);

  Buffer bodyBuffer = Buffer.buffer();
  request.setBodyBuffer(bodyBuffer);

  Assert.assertSame(bodyBuffer, bodyHolder.value);
  Assert.assertSame(bodyBuffer, request.getBodyBuffer());
}
项目:etagate    文件:DevModeSupport.java   
public Node getDevNode(App app,HttpServerRequest clientRequest){
    String hostport = clientRequest.getParam(app.name);
    String remoteip = clientRequest.remoteAddress().host();
    if(S.isNotBlank(hostport)){
        if("clear".equals(hostport)){
            devMode.remove(remoteip);
            log.debug("clear node of remote ip:"+remoteip);
            return null;
        }else{
            String[] ipp = hostport.split(":");
            Node n = app.createDevNode(ipp[0], Integer.parseInt(ipp[1]),1);
            devMode.put(remoteip, n);
            log.debug("remote ip visit setting:"+remoteip+" ["+app.name+"->"+hostport+"]");
            return n;
        }
    }else{
        return devMode.get(remoteip);
    }
}
项目:incubator-servicecomb-java-chassis    文件:LocalHostElement.java   
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerRequest request = accessLogParam.getRoutingContext().request();
  if (null == request) {
    return EMPTY_RESULT;
  }

  SocketAddress localAddress = request.localAddress();
  if (null == localAddress) {
    return EMPTY_RESULT;
  }

  String localHost = localAddress.host();
  if (StringUtils.isEmpty(localHost)) {
    return EMPTY_RESULT;
  }
  return localHost;
}
项目:etagate    文件:RoundNodeStrategy.java   
@Override
public Node getNode(Optional<HttpServerRequest> clientRequest){
    if(size==1)
        return node.get(0);

    int times = 0;
    while(times<size){
        int idx = last.getAndIncrement();   
        Node n = null;
        if(idx>=size){
            last.set(1);
            n = node.get(0);
        }else
            n = node.get(idx);

        if(n.canTake())
            return n;   
        else
            times++;
    }   
    return null;

}
项目:incubator-servicecomb-java-chassis    文件:RestBodyHandler.java   
@Override
public void handle(RoutingContext context) {
  HttpServerRequest request = context.request();
  // we need to keep state since we can be called again on reroute
  Boolean handled = context.get(BODY_HANDLED);
  if (handled == null || !handled) {
    BHandler handler = new BHandler(context);
    request.handler(handler);
    request.endHandler(v -> handler.end());
    context.put(BODY_HANDLED, true);
  } else {
    // on reroute we need to re-merge the form params if that was desired
    if (mergeFormAttributes && request.isExpectMultipart()) {
      request.params().addAll(request.formAttributes());
    }

    context.next();
  }
}
项目:incubator-servicecomb-java-chassis    文件:RestBodyHandler.java   
void doEnd() {
  if (deleteUploadedFilesOnEnd) {
    if (failed) {
      deleteFileUploads();
    } else {
      context.addBodyEndHandler(x -> deleteFileUploads());
    }
  }

  if (failed) {
    return;
  }

  HttpServerRequest req = context.request();
  if (mergeFormAttributes && req.isExpectMultipart()) {
    req.params().addAll(req.formAttributes());
  }
  context.setBody(body);
  context.next();
}
项目:incubator-servicecomb-java-chassis    文件:RequestHeaderElementTest.java   
@Test
public void getFormattedElementIfNotFound() {
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  AccessLogParam param = new AccessLogParam().setRoutingContext(mockContext);
  HttpServerRequest mockRequest = Mockito.mock(HttpServerRequest.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String testValue = "testValue";
  headers.add("anotherHeader", testValue);

  Mockito.when(mockContext.request()).thenReturn(mockRequest);
  Mockito.when(mockRequest.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:etagate    文件:App.java   
public String getDependAppAddr(final HttpServerRequest request){
    if(this.depends==null || this.appcontain ==null )
        return null;

    StringBuilder sb = new StringBuilder();

    for(String d : this.depends){
        App a = this.appcontain.getAppInfo(d);
        if(a!=null){
            String v = a.retrievOneNodeHostPort(request);
            if(S.isNotBlank(v)){
                if(sb.length()>0)
                    sb.append(",");
                sb.append(d).append("=").append(v);
            }
        }
    }

    return sb.toString();       

}
项目:incubator-servicecomb-java-chassis    文件:LocalPortElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  SocketAddress localAddress = Mockito.mock(SocketAddress.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.localAddress()).thenReturn(localAddress);
  Mockito.when(localAddress.port()).thenReturn(8080);

  String result = new LocalPortElement().getFormattedElement(param);

  assertEquals("8080", result);
}
项目:incubator-servicecomb-java-chassis    文件:FirstLineOfRequestElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  String uri = "/test/uri";

  param.setRoutingContext(mockContext);
  Mockito.when(mockContext.request()).thenReturn(request);
  Mockito.when(request.method()).thenReturn(HttpMethod.DELETE);
  Mockito.when(request.path()).thenReturn(uri);
  Mockito.when(request.version()).thenReturn(HttpVersion.HTTP_1_1);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("\"DELETE " + uri + " HTTP/1.1\"", result);
}
项目:nexus-proxy    文件:NexusHttpProxy.java   
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
项目:incubator-servicecomb-java-chassis    文件:LocalHostElementTest.java   
@Test
public void getFormattedElementIsEmpty() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  SocketAddress localAddress = Mockito.mock(SocketAddress.class);
  String localHost = "";

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.localAddress()).thenReturn(localAddress);
  Mockito.when(localAddress.host()).thenReturn(localHost);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:RemoteHostElementTest.java   
@Test
public void getFormattedElementOnHostIsEmpty() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  SocketAddress address = Mockito.mock(SocketAddress.class);
  String remoteHost = "";

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.remoteAddress()).thenReturn(address);
  Mockito.when(address.host()).thenReturn(remoteHost);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:AccessLogHandlerTest.java   
@Test
public void testLog() {
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  long startMillisecond = 1416863450581L;
  AccessLogParam accessLogParam = new AccessLogParam().setStartMillisecond(startMillisecond)
      .setRoutingContext(context);
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DatetimeConfigurableElement.DEFAULT_DATETIME_PATTERN,
      DatetimeConfigurableElement.DEFAULT_LOCALE);
  simpleDateFormat.setTimeZone(TimeZone.getDefault());

  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.method()).thenReturn(HttpMethod.DELETE);

  Deencapsulation.invoke(ACCESS_LOG_HANDLER, "log", accessLogParam);

  Mockito.verify(logger).info("DELETE" + " - " + simpleDateFormat.format(startMillisecond));
}
项目:AlipayWechatPlatform    文件:PaySettingSubRouter.java   
private void updateAlipayPaySetting(RoutingContext rc) {
    if (forbidAccess(rc, "uid", true)) {
        return;
    }
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response().putHeader("content-type", "application/json; charset=utf-8");
    //解析参数
    Long uid = Long.parseLong(req.getParam("uid"));
    Integer paySwitch = Integer.parseInt(req.getParam("paySwitch"));
    String appId = req.getParam("appId");
    String appPrivKey = req.getParam("appPrivKey");
    String zfbPubKey = req.getParam("zfbPubKey");

    //参数检查
    if (paySwitch == 1 && !CommonUtils.notEmptyString(appId, appPrivKey, zfbPubKey)) {
        resp.end(new JsonObject().put("status", "invalid").toString());
        return;
    }

    //保存支付参数
    JsonObject acc = new JsonObject().put(ID, uid).put(ZFBAPPID, appId).put(ZFBPRIVKEY, appPrivKey).put(ZFBPUBKEY, zfbPubKey).put(ZFBPAYON, paySwitch);
    updatePaySetting(resp, acc, COMMAND_UPDATE_ALIPAY);
}
项目:AlipayWechatPlatform    文件:OfficialAccountSubRouter.java   
/**
 * 更新公众号配置
 * 请求方法:PUT
 * 请求参数:id,name邮箱,appid,appsecret,verify
 * 响应:success或fail
 */
private void updateOfficialAccount(RoutingContext rc) {
    if (forbidAccess(rc, "id", true)) {
        return;
    }
    HttpServerRequest req = rc.request();
    Long id = Long.valueOf(req.getParam("id"));
    String name = req.getParam("name");
    String appid = req.getParam("appid");
    String appsecret = req.getParam("appsecret");
    String verify = req.getParam("verify");
    JsonObject updateAcc = new JsonObject().put(ID, id).put(NAME, name).put(WXAPPID, appid).put(WXAPPSECRET, appsecret).put(VERIFY, verify);
    log.debug("更新公众号配置:{}", updateAcc);
    vertx.eventBus().<Integer>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_UPDATE_NORMAL, updateAcc), ar -> {
        HttpServerResponse response = rc.response();
        if(ar.succeeded()){
            Integer rows = ar.result().body();
            response.putHeader("content-type", "application/json; charset=utf-8").end(rows > 0 ? "success" : "fail");
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            response.setStatusCode(500).end("EventBus error!");
        }
    });
}
项目:AlipayWechatPlatform    文件:LanAccessSubRouter.java   
/**
 * 判断当前请求是否允许,如果不允许,则将状态码设为403并结束响应
 * 
 * @return true:禁止访问 false=允许访问
 * @author Leibniz.Hu
 */
protected boolean refuseNonLanAccess(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    String realIp = req.getHeader("X-Real-IP");
    String xforward = req.getHeader("X-Forwarded-For");
    //禁止外网访问
    if (realIp != null && !isLanIP(realIp)) {
        log.warn("检测到非法访问,来自X-Real-IP={}", realIp);
        resp.setStatusCode(403).end();
        return true;
    }
    if (xforward != null && !isLanIP(xforward)) {
        log.warn("检测到非法访问,来自X-Forwarded-For={}", xforward);
        resp.setStatusCode(403).end();
        return true;
    }
    return false;
}
项目:AlipayWechatPlatform    文件:WechatPaySubRouter.java   
/**
 * 微信支付的预处理,js的wx.config需要用
 *
 * 异步返回 wx.config需要用的数据
 *
 * @author Leibniz
 */
private void wechatPreHandle(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse response = rc.response();
    int eid = Integer.parseInt(req.getParam("eid"));
    vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
        if (ar.succeeded()) {
            JsonObject acc = ar.result().body();
            String curUrl = null;
            try {
                curUrl = URLDecoder.decode(req.getParam("url"), "UTF-8");
            } catch (UnsupportedEncodingException ignore) {
            }
            //调用微信jdk类
            Map<String, String> jdkMap = new WechatJdk(req, acc, curUrl).getMap();
            jdkMap.put("appId", acc.getString(WXAPPID));
            String jsonStr = JsonObject.mapFrom(jdkMap).toString();
            log.debug("接收到(ID={})微信JSSDK初始化请求,返回Json:{}", eid, jsonStr);
            response.putHeader("content-type", "application/json;charset=UTF-8").end(jsonStr);
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            response.setStatusCode(500).end("EventBus error!");
        }
    });
}
项目:app-ms    文件:VertxTest.java   
@Test
public void testManifestRouteText(final TestContext context) {

    final Router router = Router.router(rule.vertx());
    final ManifestHandler handler = ManifestHandler.registerToRouter(router);

    final RoutingContext routingContext = mock(RoutingContext.class);
    when(routingContext.currentRoute()).thenReturn(router.get("/.well-known/manifest"));
    when(routingContext.request()).thenReturn(mock(HttpServerRequest.class));
    when(routingContext.getAcceptableContentType()).thenReturn(MediaType.TEXT_PLAIN);
    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(routingContext.response()).thenReturn(response);

    handler.handle(routingContext);
    verify(response, times(1)).end(any(Buffer.class));
}
项目:incubator-servicecomb-java-chassis    文件:TestSimpleBodyHandler.java   
@Before
public void setUp() throws Exception {
  context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  Mockito.when(context.request()).thenReturn(request);
  HttpServerResponse response = Mockito.mock(HttpServerResponse.class);
  Mockito.when(response.setStatusCode(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode())).thenReturn(response);
  Mockito.when(context.response()).thenReturn(response);
}
项目:incubator-servicecomb-java-chassis    文件:TestHttpServerRequestUtils.java   
@Test
public void VertxServerRequestToHttpServletRequest(@Mocked RoutingContext context,
    @Mocked HttpServerRequest request) {
  HttpServerRequestWrapper wrapper = new HttpServerRequestWrapper(request);
  new Expectations() {
    {
      context.request();
      result = wrapper;
    }
  };

  VertxServerRequestToHttpServletRequest reqEx = new VertxServerRequestToHttpServletRequest(context, "abc");
  Assert.assertEquals("abc", reqEx.getRequestURI());
}
项目:incubator-servicecomb-java-chassis    文件:UriPathOnlyElement.java   
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerRequest request = accessLogParam.getRoutingContext().request();

  if (null == request) {
    return EMPTY_RESULT;
  }

  String uri = request.path();
  if (null == uri) {
    return EMPTY_RESULT;
  }

  return uri;
}
项目:vertx-zero    文件:CommonArithmetic.java   
@Override
public Record search(final List<Record> records,
                     final RoutingContext context) {
    final HttpServerRequest request = context.request();
    // Input source
    final String uri = request.uri();
    final Optional<Record> hitted =
            records.stream()
                    .filter(record -> isMatch(uri, record))
                    .findAny();
    // Find valid;
    return hitted.orElse(null);
}
项目:incubator-servicecomb-java-chassis    文件:UriPathIncludeQueryElementTest.java   
@Test
public void getFormattedElementOnUriIsEmpty() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  String uri = "";

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.uri()).thenReturn(uri);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:LocalPortElementTest.java   
@Test
public void getFormattedElementOnLocalAddressIsNull() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.localAddress()).thenReturn(null);

  String result = new LocalPortElement().getFormattedElement(param);

  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:UriPathOnlyElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  String uri = "/uri/test";

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.path()).thenReturn(uri);

  String result = new UriPathOnlyElement().getFormattedElement(param);

  Assert.assertEquals(uri, result);
}
项目:incubator-servicecomb-java-chassis    文件:UriPathOnlyElementTest.java   
@Test
public void getFormattedElementOnMethodIsNull() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.path()).thenReturn(null);

  String result = new UriPathOnlyElement().getFormattedElement(param);

  Assert.assertEquals("-", result);
}
项目:app-ms    文件:ProtectedHandler.java   
/**
 * Obtains the access token from the request. It is expected to be the
 * Authorization with a bearer tag. The authentication code is expected to be a
 * given pattern.
 *
 * @param contextRequest
 *            request
 * @return access token
 */
private String getAccessToken(final HttpServerRequest contextRequest) {

    final String authorizationHeader = contextRequest.getHeader(AUTHORIZATION);
    if (authorizationHeader == null) {
        return null;
    }
    final Matcher m = Pattern.compile(BEARER_TOKEN_PATTERN).matcher(authorizationHeader);
    if (!m.matches()) {
        return null;
    } else {
        return m.group(1);
    }
}
项目:incubator-servicecomb-java-chassis    文件:VersionOrProtocolElementTest.java   
@Test
public void getFormattedElementOnVersionIsNull() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.version()).thenReturn(null);

  String result = new VersionOrProtocolElement().getFormattedElement(param);

  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:LocalHostElementTest.java   
@Test
public void getFormattedElementOnLocalAddressIsNull() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.localAddress()).thenReturn(null);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:etagate    文件:RequestHandler.java   
public void handle(HttpServerRequest clientRequest, HttpServerResponse clientResponse,
            HttpResponse<Buffer> appResponse) {

        int statusCode = appResponse.statusCode();
        clientResponse.setStatusCode(statusCode);
//      clientResponse.setStatusMessage(appResponse.statusMessage());
//      System.out.println(appResponse.statusMessage());

        MultiMap appHeaders = appResponse.headers();
        appHeaders.forEach(entry -> {
            String k = entry.getKey();
            String v = entry.getValue();
//          System.out.println("Header Response:[" + k + "]=" + v);
            if ("Location".equalsIgnoreCase(k) && S.isNotBlank(v)) {
                String schemal = clientRequest.scheme();
                String host = clientRequest.host();
                clientResponse.putHeader("Location", v.replaceAll(HTTP_SCHEMAL_HOST_REG, schemal + "://" + host + "/"));
            } else
                clientResponse.putHeader(k, v);
        });



        clientResponse.setChunked(true);

        Buffer buff = appResponse.bodyAsBuffer();
        if (buff != null && buff.length() > 0)
            clientResponse.write(buff);

    }
项目:incubator-servicecomb-java-chassis    文件:MethodElementTest.java   
@Test
public void getFormattedElementOnMethodIsNull() {
  RoutingContext routingContext = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  AccessLogParam param = new AccessLogParam().setRoutingContext(routingContext);

  Mockito.when(routingContext.request()).thenReturn(request);
  Mockito.when(request.method()).thenReturn(null);

  Assert.assertEquals("-", new MethodElement().getFormattedElement(param));
}
项目:incubator-servicecomb-java-chassis    文件:RemoteHostElementTest.java   
@Test
public void getFormattedElementOnRemoteAddressIsNull() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.remoteAddress()).thenReturn(null);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:app-ms    文件:SpringJaxRsHandlerTest.java   
@Test
public void testFailure(final TestContext testContext) throws Exception {

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenThrow(new RuntimeException("boom"));
    when(serverRequest.path()).thenReturn("/api/hello/400");
    when(serverRequest.uri()).thenReturn("/api/hello/400");
    when(serverRequest.isEnded()).thenReturn(true);
    when(serverRequest.method()).thenReturn(HttpMethod.GET);

    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(response.putHeader(any(AsciiString.class), anyString())).thenReturn(response);
    when(response.headers()).thenReturn(new VertxHttpHeaders());

    final Async async = testContext.async();
    when(response.setStatusCode(Matchers.any(Integer.class))).then(invocation -> {

        try {
            return response;
        } finally {
            async.complete();
        }
    });
    when(serverRequest.response()).thenReturn(response);

    router.accept(serverRequest);
    async.await();

    verify(response, times(1)).setStatusCode(500);
}
项目:incubator-servicecomb-java-chassis    文件:QueryOnlyElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext context = Mockito.mock(RoutingContext.class);
  HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
  String query = "?status=up";

  param.setRoutingContext(context);
  Mockito.when(context.request()).thenReturn(request);
  Mockito.when(request.query()).thenReturn(query);

  String result = new QueryOnlyElement().getFormattedElement(param);

  assertEquals(query, result);
}
项目:AlipayWechatPlatform    文件:AlipayOauthSubRouter.java   
/**
 * 支付宝普通授权(获取用户信息)的回调方法
 * 由支付宝服务器调用
 *
 * @param rc Vertx的RoutingContext对象
 * @author Leibniz.Hu
 */
private void oauthInfoCallback(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    Integer eid = Integer.parseInt(req.getParam("eid"));
    getAccountAndExecute(resp, eid, aliAcc -> {
        AlipayUserInfoShareResponse oauthRes = AliPayApi.getUserDetailInfo(aliAcc, req);
        oauthSuccessProcess(req, resp, oauthRes, url -> log.info("授权成功,OpenID={},准备跳转到{}", oauthRes.getUserId(), url));
    });
}
项目:kiqr    文件:RestKiqrServerVerticle.java   
private void addRouteForScalarKVQueries(Router router) {
    router.route(RestKiqrServerVerticle.BASE_ROUTE_KV + "/values/:key").handler(routingContext -> {


        HttpServerRequest request = routingContext.request();

        String keySerde = request.getParam("keySerde");
        String valueSerde = request.getParam("valueSerde");
        String store = request.getParam("store");
        byte[] key = Base64.getDecoder().decode(request.getParam("key"));

        if (keySerde == null || valueSerde == null) {
            routingContext.fail(400);
        } else {
            KeyBasedQuery query = new KeyBasedQuery(store, keySerde, key, valueSerde);


            vertx.eventBus().send(Config.KEY_VALUE_QUERY_FACADE_ADDRESS, query, new DeliveryOptions().setSendTimeout(TIMEOUT), reply -> {
                if (reply.succeeded()) {
                    ScalarKeyValueQueryResponse body = (ScalarKeyValueQueryResponse) reply.result().body();
                    HttpServerResponse response = routingContext.response();
                    System.out.println(reply.result().body());
                    response
                            .putHeader("content-type", "application/json")
                            .end(JsonObject.mapFrom(reply.result().body()).encode());


                } else {

                    reply.cause().printStackTrace();
                    forwardErrorCode(routingContext, reply);
                }
            });
        }


    });
}
项目:app-ms    文件:SpringJaxRsHandlerTest.java   
@Test
public void test400(final TestContext testContext) throws Exception {

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenReturn("http://test.trajano.net/api/hello/400");
    when(serverRequest.path()).thenReturn("/api/hello/400");
    when(serverRequest.uri()).thenReturn("/api/hello/400");
    when(serverRequest.isEnded()).thenReturn(true);
    when(serverRequest.method()).thenReturn(HttpMethod.GET);

    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(response.putHeader(any(AsciiString.class), anyString())).thenReturn(response);
    when(response.headers()).thenReturn(new VertxHttpHeaders());

    final Async async = testContext.async();
    when(response.setStatusCode(Matchers.any(Integer.class))).then(invocation -> {

        try {
            return response;
        } finally {
            async.complete();
        }
    });
    when(serverRequest.response()).thenReturn(response);

    router.accept(serverRequest);
    async.awaitSuccess();

    verify(response, times(1)).setStatusCode(400);
}
项目:nexus-proxy    文件:NexusHttpProxy.java   
private static final String getHeader(final HttpServerRequest req,
                                      final CharSequence name,
                                      final String defaultValue) {
    final String originalHeader = req.headers().get(name);

    if (originalHeader == null) {
        return defaultValue;
    } else {
        return originalHeader;
    }
}