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

项目:rest.vertx    文件:HttpResponseWriter.java   
default void addResponseHeaders(RouteDefinition definition, HttpServerResponse response) {

        if (!response.ended() &&
            !response.headers().contains(HttpHeaders.CONTENT_TYPE)) {

            if (definition != null &&
                definition.getProduces() != null) {
                for (MediaType produces : definition.getProduces()) {
                    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaTypeHelper.toString(produces));
                }
            }
            else {
                response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD);
            }
        }
    }
项目:incubator-servicecomb-java-chassis    文件:ResponseHeaderElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String headerValue = "headerValue";

  param.setRoutingContext(mockContext);
  headers.add(IDENTIFIER, headerValue);

  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals(headerValue, result);
  assertEquals(ELEMENT.getIdentifier(), IDENTIFIER);
}
项目:incubator-servicecomb-java-chassis    文件:ResponseHeaderElementTest.java   
@Test
public void getFormattedElementOnNotFound() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String headerValue = "headerValue";

  param.setRoutingContext(mockContext);
  headers.add("anotherHeader", headerValue);

  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
项目:DMS    文件:APIKeyManageRouter.java   
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    if (userManager.isLogined(ctx)) {
        try {
            String uid = userManager.getUid(userManager.getIdFromSession(ctx));
            JobResult result = requestManager.getApiKeys(uid);
            if (result.isSuccess()) {
                SafeResultSet rs = (SafeResultSet) result.getArgs()[0];
                while (rs.next()) {
                    //
                    //
                    //
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatusCode(500);
        }
    } else {
        response.setStatusCode(400);
    }
    response.end();
    response.close();
}
项目:dragoman    文件:DatasetResource.java   
private void writeDatasetContents(
    RoutingContext routingContext, Observable<DataEnvelope> datasetContents) {
  HttpServerResponse httpServerResponse =
      jsonContentType(routingContext.response()).setChunked(true);

  final AtomicBoolean isFirst = new AtomicBoolean(true);
  datasetContents.subscribe(
      (DataEnvelope dataEnvelope) -> {
        if (!isFirst.get()) {
          httpServerResponse.write(",");
        } else {
          isFirst.set(false);
          httpServerResponse.write("[");
        }
        httpServerResponse.write(new JsonObject(dataEnvelope.getPayload()).encodePrettily());
      },
      throwable -> GlobalExceptionHandler.error(routingContext, throwable),
      () -> httpServerResponse.end("]"));
}
项目:dragoman    文件:DatasetResource.java   
private void writeDatasets(RoutingContext routingContext, Observable<Dataset> datasets) {
  HttpServerResponse httpServerResponse =
      jsonContentType(routingContext.response()).setChunked(true);

  final AtomicBoolean isFirst = new AtomicBoolean(true);
  datasets.subscribe(
      dataset -> {
        if (!isFirst.get()) {
          httpServerResponse.write(",");
        } else {
          isFirst.set(false);
          httpServerResponse.write("[");
        }
        httpServerResponse.write(viewTransformer.transform(dataset));
      },
      throwable -> GlobalExceptionHandler.error(routingContext, throwable),
      () -> httpServerResponse.end("]"));
}
项目:AlipayWechatPlatform    文件:WechatOauthSubRouter.java   
/**
 * 申请微信授权
 * /awp/wxOauth/apply/{body}
 * web服务需要授权时,向用户发送重定向,重定向到当前接口
 * 参数只有一个,内容为JSON,请用http://localhost:8083/awp/base64.html进行加密
 * {
 * "eid":web项目使用的公众号在本项目中的用户ID
 * "type":0=静默授权,只能获取OpenID,1=正常授权,会弹出授权确认页面,可以获取到用户信息
 * "callback":授权成功后调用的web项目回调接口地址,请使用完整地址,
 * 回调时会使用GET方法,加上rs参数,
 * 如果静默授权,rs参数内容就是openid
 * 如果正常授权,rs参数内容是turingBase64加密的授权结果(JSON)
 * }
 *
 * @param rc Vertx的RoutingContext对象
 * @author Leibniz.Hu
 */
private void applyForOauth(RoutingContext rc) {
    HttpServerResponse resp = rc.response();
    String decodedBody = TuringBase64Util.decode(rc.request().getParam("body"));
    JsonObject reqJson = new JsonObject(decodedBody);
    Integer eid = reqJson.getInteger("eid");
    int type = reqJson.getInteger("type");
    String callback = TuringBase64Util.encode(reqJson.getString("callback"));//授权后回调方法
    vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
        if (ar.succeeded()) {
            JsonObject account = ar.result().body();
            String redirectAfterUrl = PROJ_URL + "oauth/wx/" + (type == 0 ? "baseCb" : "infoCb") + "?eid=" + eid + "&visitUrl=" + callback;
            String returnUrl = null;
            try {
                returnUrl = String.format((type == 0 ? OAUTH_BASE_API : OAUTH_INFO_API)
                        , account.getString(WXAPPID), URLEncoder.encode(redirectAfterUrl, "UTF-8"));
            } catch (UnsupportedEncodingException ignored) { //不可能出现的
            }
            resp.setStatusCode(302).putHeader("Location", returnUrl).end();
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            resp.setStatusCode(500).end("EventBus error!");
        }
    });
}
项目:AlipayWechatPlatform    文件:AlipayOauthSubRouter.java   
/**
 * 申请支付宝授权
 * /awp/wxOauth/apply/{body}
 * web服务需要授权时,向用户发送重定向,重定向到当前接口
 * 参数只有一个,内容为JSON,请用http://localhost:8083/awp/base64.html进行加密
 * {
 * "eid":web项目使用的公众号在本项目中的用户ID
 * "type":0=静默授权,只能获取OpenID,1=正常授权,会弹出授权确认页面,可以获取到用户信息
 * "callback":授权成功后调用的web项目回调接口地址,请使用完整地址,
 * 回调时会使用GET方法,加上rs参数,
 * 如果静默授权,rs参数内容就是openid
 * 如果正常授权,rs参数内容是turingBase64加密的授权结果(JSON)
 * }
 *
 * @param rc Vertx的RoutingContext对象
 * @author Leibniz.Hu
 */
private void applyForOauth(RoutingContext rc) {
    HttpServerResponse resp = rc.response();
    String decodedBody = TuringBase64Util.decode(rc.request().getParam("body"));
    JsonObject reqJson = new JsonObject(decodedBody);
    Integer eid = reqJson.getInteger("eid");
    int type = reqJson.getInteger("type");
    String callback = TuringBase64Util.encode(reqJson.getString("callback"));//授权后回调方法
    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 redirectAfterUrl = PROJ_URL + "oauth/zfb/" + (type == 0 ? "baseCb" : "infoCb") + "?eid=" + eid + "&visitUrl=" + callback;
            AliAccountInfo aliAcc = new AliAccountInfo(acc.getString(ZFBAPPID), acc.getString(ZFBPRIVKEY), acc.getString(ZFBPUBKEY), null, null, redirectAfterUrl);
            AliPayApi.auth(aliAcc, resp, type == 1);
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            resp.setStatusCode(500).end("EventBus error!");
        }
    });
}
项目: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    文件: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    文件:AliPayApi.java   
/**
 * 该方法实现了支付宝手机网页的支付功能;
 * 方法将调用支付宝支付页面需要用到的数据拼接和设置好,然后,写到响应中,前台会自动弹出支付宝支付页面;
 * 其中,支付金额要求大于0.01,并且小于100000000,需要调用者自己检查该值再传进来,否则页面会报获取不到订单信息错误;
 *
 * @param aliAccountInfo 保存了支付宝账户的信息,包括appId、用户私钥、支付宝公钥和回调地址等,具体参考AliAccountInfo类的属性说明
 * @param payBizContent 保存了订单信息,包括本地订单号、金额等,具体参考BizContent类的属性说明
 * Create by quandong
 */
public static void wapPay(AliAccountInfo aliAccountInfo, PayBizContent payBizContent, HttpServerResponse httpResponse) throws IOException {
    AlipayClient alipayClient = AliPayCliFactory.getAlipayClient(aliAccountInfo); // 从客户端工厂中获取AlipayClient
    AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); // 创建API对应的request
    String form = "";

    alipayRequest.setReturnUrl(aliAccountInfo.getReturnUrl()); // 设置回跳地址
    alipayRequest.setNotifyUrl(aliAccountInfo.getNotifyUrl()); // 设置通知地址
    alipayRequest.setBizContent(payBizContent.toString()); // 填充业务参数

    try {
        form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }

    httpResponse.putHeader("Content-Type", "text/html;charset=" + AlipayConstants.CHARSET_UTF8); // 设置文本类型及编码
    httpResponse.end(form); // 直接将完整的表单html输出到页面
}
项目: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!");
        }
    });
}
项目:chlorophytum-semantics    文件:GetMessageHandler.java   
@Override
public void handle(RoutingContext routingContext) {
    String id = routingContext.request().getParam(MESSAGE_ID);

    redisClient.hget(MESSAGES, id, result -> {
        HttpServerResponse response = routingContext.response();

        if (result == null) {
            response.setStatusCode(404);
            response.end();
        } else {
            response.setStatusCode(200);
            response.putHeader("content-type", "application/json; charset=utf-8");
            response.end(result.result());
        }
    });
}
项目:vertx-zero    文件:Answer.java   
public static void reply(
        final RoutingContext context,
        final Envelop envelop,
        final Event event
) {
    // 1. Get response reference
    final HttpServerResponse response
            = context.response();

    // 2. Set response status
    final HttpStatusCode code = envelop.status();
    response.setStatusCode(code.code());
    response.setStatusMessage(code.message());
    // 3. Media processing
    Normalizer.out(response, envelop, event);
    // 4. Store Session
    storeSession(context, envelop.data(), event.getAction());
    // 5. Response process
    if (!response.ended()) {
        response.end(envelop.response());
    }
    response.close();
}
项目: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));
}
项目:rest.vertx    文件:RestRouter.java   
@SuppressWarnings("unchecked")
private static void produceResponse(Object result, RoutingContext context, RouteDefinition definition, HttpResponseWriter writer) {

    HttpServerResponse response = context.response();
    HttpServerRequest request = context.request();

    // add default response headers per definition
    writer.addResponseHeaders(definition, response);

    // write response and override headers if necessary
    writer.write(result, request, response);

    // finish if not finished by writer
    if (!response.ended()) {
        response.end();
    }
}
项目:DMS    文件:APIKeyCreateRequestRouter.java   
public void handle(RoutingContext ctx)
{
    HttpServerResponse response = ctx.response();
    if(userManager.isLogined(ctx)){
        try {
            String uid = userManager.getUid(userManager.getIdFromSession(ctx));
            String result = requestManager.createApiKey(uid);
            if(result != null){
                response.setStatusCode(200);
                response.setStatusMessage(result);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatusCode(500);
        }
    }else{
        response.setStatusCode(400);
    }
    response.end();
    response.close();
}
项目:app-ms    文件:VertxTest.java   
@Test
public void testManifestRoute(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));
    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));
}
项目:kiqr    文件:RestKiqrServerVerticle.java   
private void addRouteForSessionQueries(Router router) {
    router.route(RestKiqrServerVerticle.BASE_ROUTE_SESSION + "/: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.SESSION_QUERY_FACADE_ADDRESS, query, new DeliveryOptions().setSendTimeout(TIMEOUT), reply -> {
                if (reply.succeeded()) {
                    SessionQueryResponse body = (SessionQueryResponse) reply.result().body();

                    HttpServerResponse response = routingContext.response();
                    response
                            .putHeader("content-type", "application/json")
                            .end(Json.encode(body));


                } else {
                    forwardErrorCode(routingContext, reply);
                }
            });
        }

    });
}
项目:rest.vertx    文件:WriterFactory.java   
@Override
protected void init() {

    classTypes.put(Response.class, JaxResponseWriter.class);
    classTypes.put(HttpServerResponse.class, VertxResponseWriter.class);

    mediaTypes.put(MediaType.APPLICATION_JSON, JsonResponseWriter.class);
    mediaTypes.put(MediaType.TEXT_PLAIN, GenericResponseWriter.class);
}
项目:incubator-servicecomb-java-chassis    文件:AbstractEdgeDispatcher.java   
protected void onFailure(RoutingContext context) {
  LOGGER.error("edge server failed.", context.failure());
  HttpServerResponse response = context.response();
  response.setStatusCode(Status.BAD_GATEWAY.getStatusCode());
  response.setStatusMessage(Status.BAD_GATEWAY.getReasonPhrase());
  response.end();
}
项目:DocBleach    文件:Main.java   
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
    HttpServerResponse response = routingContext.response();
    response.putHeader("Content-Description", "File Transfer");
    response.putHeader("Content-Type", "application/octet-stream");
    response.putHeader("Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
    response.putHeader("Content-Transfer-Encoding", "binary");
    response.putHeader("Expires", "0");
    response.putHeader("Pragma", "Public");
    response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.putHeader("Content-Length", "" + saneFile.length());

    response.sendFile(saneFile.getAbsolutePath());
}
项目:incubator-servicecomb-java-chassis    文件:BytesWrittenV1Element.java   
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerResponse response = accessLogParam.getRoutingContext().response();
  if (null == response) {
    return ZERO_BYTES;
  }

  long bytesWritten = response.bytesWritten();

  return String.valueOf(bytesWritten);
}
项目:incubator-servicecomb-java-chassis    文件:BytesWrittenV2Element.java   
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerResponse response = accessLogParam.getRoutingContext().response();
  if (null == response) {
    return ZERO_BYTES;
  }

  long bytesWritten = response.bytesWritten();
  if (0 == bytesWritten) {
    return ZERO_BYTES;
  }

  return String.valueOf(bytesWritten);
}
项目:incubator-servicecomb-java-chassis    文件:StatusElement.java   
@Override
public String getFormattedElement(AccessLogParam accessLogParam) {
  HttpServerResponse response = accessLogParam.getRoutingContext().response();
  if (null == response) {
    return EMPTY_RESULT;
  }

  return String.valueOf(response.getStatusCode());
}
项目:incubator-servicecomb-java-chassis    文件:BytesWrittenV2ElementTest.java   
@Test
public void getFormattedElementOnBytesWrittenIsZero() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  long bytesWritten = 0l;

  param.setRoutingContext(mockContext);
  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.bytesWritten()).thenReturn(bytesWritten);

  String result = ELEMENT.getFormattedElement(param);
  assertEquals("-", result);
}
项目:incubator-servicecomb-java-chassis    文件:BytesWrittenV1ElementTest.java   
@Test
public void getFormattedElement() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  long bytesWritten = 16l;

  param.setRoutingContext(mockContext);
  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.bytesWritten()).thenReturn(bytesWritten);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals(String.valueOf(bytesWritten), result);
}
项目:incubator-servicecomb-java-chassis    文件:BytesWrittenV1ElementTest.java   
@Test
public void getFormattedElementOnBytesWrittenIsZero() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  long bytesWritten = 0l;

  param.setRoutingContext(mockContext);
  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.bytesWritten()).thenReturn(bytesWritten);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("0", result);
}
项目:irked    文件:Request.java   
/**
 * Helper method to generate response with the specified HTTP status
 * @param status HTTP status code and text to set on the response
 * @return HTTP response created using {@link RoutingContext#response()}
 */
public HttpServerResponse response(HttpError status) {
    HttpServerResponse res = response();
    for (Entry<String, String> h : status.getHeaders())
        res.putHeader(h.getKey(), h.getValue());
    return res.setStatusCode(status.getStatusCode()).setStatusMessage(status.getStatusText());
}
项目:AlipayWechatPlatform    文件:AlipayOauthSubRouter.java   
/**
 * 支付宝静默授权的回调方法
 * 由支付宝服务器调用
 *
 * @param rc Vertx的RoutingContext对象
 * @author Leibniz.Hu
 */
private void oauthBaseCallback(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    Integer eid = Integer.parseInt(req.getParam("eid"));
    getAccountAndExecute(resp, eid, aliAcc -> {
        AlipaySystemOauthTokenResponse oauthRes = AliPayApi.getUserId(aliAcc, req);
        oauthSuccessProcess(req, resp, oauthRes, url -> log.info("授权成功,OpenID={},{},准备跳转到{}", oauthRes.getUserId(), oauthRes.getAlipayUserId(), url));
    });
}
项目:AlipayWechatPlatform    文件:AlipayOauthSubRouter.java   
/**
 * 解析授权前访问的地址,解析所需的json并编码,最后重定向
 *
 * @param req      HTTP请求对象
 * @param resp     HTTP响应对象
 * @param res      ALipay接口返回的响应
 * @param callback 解析地址后的处理方法
 * @author Leibniz.Hu
 */
private void oauthSuccessProcess(HttpServerRequest req, HttpServerResponse resp, AlipayResponse res, Handler<String> callback) {
    if (res != null) {
        String visitUrl = req.getParam("visitUrl");//getRedirectAddress(request, REMOVE_PARAMS);
        if (visitUrl.length() > 0) {
            visitUrl = TuringBase64Util.decode(visitUrl).replaceAll("[\\s*\t\n\r]", "");
            callback.handle(visitUrl);
            resp.setStatusCode(302).putHeader("Location", visitUrl + (visitUrl.contains("?") ? "&rs=" : "?rs=") + TuringBase64Util.encode(getClearJson(res).toString())).end();
        } else {
            log.error("没有找到授权后回调地址" + req.absoluteURI());
            resp.end("未设置授权后回调地址");
        }
    }
}
项目:rest.vertx    文件:JsonExceptionHandler.java   
@Override
public void write(Throwable exception, HttpServerRequest request, HttpServerResponse response) {

    response.setStatusCode(406);

    ErrorJSON error = new ErrorJSON();
    error.code = response.getStatusCode();
    error.message = exception.getMessage();

    response.end(JsonUtils.toJson(error));
}
项目:kiqr    文件:RestKiqrServerVerticle.java   
private void addRouteForWindowQueries(Router router) {
    router.route(RestKiqrServerVerticle.BASE_ROUTE_WINDOW + "/: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"));
        String from = request.getParam("from");
        String to = request.getParam("to");

        if (keySerde == null || valueSerde == null) {
            routingContext.fail(400);
        } else if (from == null || to == null) {
            routingContext.fail(400);
        } else {
            WindowedQuery query = new WindowedQuery(store, keySerde, key, valueSerde, Long.valueOf(from), Long.valueOf(to));


            vertx.eventBus().send(Config.WINDOWED_QUERY_FACADE_ADDRESS, query, new DeliveryOptions().setSendTimeout(TIMEOUT), reply -> {
                if (reply.succeeded()) {
                    WindowedQueryResponse body = (WindowedQueryResponse) reply.result().body();

                    HttpServerResponse response = routingContext.response();
                    response
                            .putHeader("content-type", "application/json")
                            .end(Json.encode(body));


                } else {
                    forwardErrorCode(routingContext, reply);
                }
            });
        }

    });
}
项目:rest.vertx    文件:NotFoundResponseWriter.java   
@Override
public void write(Void result, HttpServerRequest request, HttpServerResponse response) {

    // pre-fill 404 for convenience
    response.setStatusCode(Response.Status.NOT_FOUND.getStatusCode());

    // wrapped call to simplify implementation
    write(request, response);
}
项目:AlipayWechatPlatform    文件:AliPayApi.java   
/**
 * 该方法对向支付宝发送请求唤醒授权页面进行了封装;
 * 方法先根据调用者传来的参数拼接好发送给支付宝服务器的Url;
 * 然后利用响应体的重定向方法发送请求;
 *
 * @param aliAccountInfo 封装了发送给支付宝数据的对象
 * @param response http响应体
 * Create by quandong
 */
public static void auth(AliAccountInfo aliAccountInfo, HttpServerResponse response, boolean needDetail) {
    String authReqUrl = null; // 将参数拼接到发送给支付宝的的链接上
    try {
        authReqUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + aliAccountInfo.getAppId() + "&scope=" + (needDetail?"auth_user,auth_base":"auth_base") + "&redirect_uri=" + URLEncoder.encode(aliAccountInfo.getRedirectUrl(), AlipayConstants.CHARSET_UTF8);
    } catch (UnsupportedEncodingException ignore) {
    }
    response.setStatusCode(302)
            .putHeader("Location", authReqUrl) // 通过响应体的重定向方法,向支付宝发送请求,页面上会弹出支付宝授权页面
            .end();
}
项目:AlipayWechatPlatform    文件:AlipayPayService.java   
/**
 * 支付宝下单
 *
 * @param product  产品名
 * @param price    价格(单位:分)
 * @param orderId  本地订单ID
 * @param acc      企业用户账户对象
 * @param response HTTP响应
 * @author Leibniz
 */
public void alipayOrder(String product, int price, String orderId, JsonObject acc, String successUrl, HttpServerResponse response) {
    try {
        String notifyUrl = zfbPayNotifyUrl; // 服务器后台回调通知的url
        AliAccountInfo aliAccountInfo = new AliAccountInfo(acc.getString(ZFBAPPID), acc.getString(ZFBPRIVKEY), acc.getString(ZFBPUBKEY), successUrl, notifyUrl, null); // 该对象保存了支付宝账号的相关信息,以及请求回调地址
        PayBizContent payBizContent = new PayBizContent(orderId, price + "", product, null); // 订单的信息
        AliPayApi.wapPay(aliAccountInfo, payBizContent, response); // 调用支付宝API的方法请求支付宝支付接口
    } catch (IOException e) {
        log.error(orderId + "下单失败,请查看开发配置是否正确", e);
        response.setStatusCode(500).end("Alipay Order error!");
    }
}
项目:vertx_spring    文件:AbstractRequestHandler.java   
private Handler<AsyncResult<Message<JsonObject>>> replyHandler(HttpServerResponse response) {
    return ar -> {
        if (ar.succeeded()) {
            // manage successful reply
            Message<JsonObject> msg = ar.result();
            response.setStatusCode(200).end(msg.body().encode());
        } else {
            // manage failure reply
            logger.error("Error invoking " + getMethod() + ":" + getPath(), ar.cause());
            response.setStatusCode(500)
                    .end(new JsonObject().put("type", "error").put("message", ar.cause().getMessage()).encode());
        }
    };
}
项目:AlipayWechatPlatform    文件:AlipayMessageSubRouter.java   
/**
 * 发送客服消息
 */
private void sendCustomerServiceMessage(RoutingContext rc) {
    if (refuseNonLanAccess(rc)) return;
    JsonObject params = rc.getBodyAsJson();
    String openId = params.getString("openId");
    String content = params.getString("content");
    int eid = params.getInteger("eid");
    vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
        HttpServerResponse response = rc.response();
        if (ar.succeeded()) {
            JsonObject acc = ar.result().body();
            vertx.executeBlocking(future -> {
                future.complete(null);//TODO 支付宝客服消息的实现
            }, res -> {
                if (res.succeeded()) {
                    response.putHeader("content-type", "application/json;charset=UTF-8").end(res.result().toString());
                } else {
                    log.error("向公众号" + acc.getString(NAME) + "的粉丝" + openId + "发送客服消息时抛出异常", res.cause());
                    response.setStatusCode(500).end(res.cause().getMessage());
                }
            });
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            response.setStatusCode(500).end("EventBus error!");
        }
    });
}
项目:app-ms    文件:SpringJaxRsHandlerTest.java   
@Test
public void test500(final TestContext testContext) throws Exception {

    final Router router = Router.router(rule.vertx());
    final JaxRsRouter jaxRsRouter = new JaxRsRouter();
    final SpringJaxRsHandler handler = new SpringJaxRsHandler(MyApp.class);
    jaxRsRouter.register(MyApp.class, router, handler, handler);

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenReturn("http://test.trajano.net/api/hello/cough");
    when(serverRequest.path()).thenReturn("/api/hello/cough");
    when(serverRequest.uri()).thenReturn("/api/hello/cough");
    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.write(Matchers.any(Buffer.class))).thenReturn(response);

    doAnswer(i -> {
        async.complete();
        return null;
    }).when(response).end();

    when(serverRequest.response()).thenReturn(response);

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

    final ArgumentCaptor<Buffer> captor = ArgumentCaptor.forClass(Buffer.class);
    verify(response, times(1)).setStatusCode(500);
    verify(response, atLeastOnce()).write(captor.capture());
    final String errorMessage = String.join("", captor.getAllValues().stream().map(Buffer::toString).collect(Collectors.toList()));
    assertTrue(errorMessage.contains("server_error"));
}
项目:rest.vertx    文件:GenericResponseWriter.java   
@Override
public void write(T result, HttpServerRequest request, HttpServerResponse response) {

    String mediaType = response.headers().get(HttpHeaders.CONTENT_TYPE);

    HttpResponseWriter writer;
    try {
        writer = RestRouter.getWriters().get(mediaType);
    }
    catch (ClassFactoryException e) {
        // writer = RestRouter.getWriters().get(result);
        writer = null;
    }

    if (writer != null && !(writer instanceof GenericResponseWriter)) {
        writer.write(result, request, response);
    }
    else {

        log.warn("No writer associated with: '" + mediaType + "', defaulting to toString() as output!");
        if (result != null) {
            response.end(result.toString());
        }
        else {
            response.end();
        }
    }
}