Java Code Examples for io.vertx.core.http.HttpServerRequest#getParam()

The following examples show how to use io.vertx.core.http.HttpServerRequest#getParam() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EncryptEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<String> queryUserId(HttpServerRequest httpServerRequest) {
  String serviceToken = httpServerRequest.getParam("serviceToken");
  if (serviceToken == null) {
    // no need to query userId
    return CompletableFuture.completedFuture(null);
  }

  CompletableFuture<String> future = new CompletableFuture<>();
  encrypt.queryUserId(serviceToken).whenComplete((userId, e) -> {
    if (e != null) {
      // treat as success, just userId is null
      LOGGER.error("Failed to query userId, serviceToken={}.", serviceToken, e);
    }

    future.complete(userId);
  });

  return future;
}
 
Example 2
Source File: AdminHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final HttpServerRequest request = context.request();

    final BiConsumer<Logger, String> loggingLevelModifier;
    final int records;

    final String loggingLevel = request.getParam(LOGGING_PARAM);
    final String recordsAsString = request.getParam(RECORDS_PARAM);

    try {
        loggingLevelModifier = loggingLevel(loggingLevel);
        records = records(recordsAsString);
    } catch (IllegalArgumentException e) {
        context.response()
                .setStatusCode(HttpResponseStatus.BAD_REQUEST.code())
                .end(e.getMessage());
        return;
    }

    adminManager.setupByCounter(AdminManager.COUNTER_KEY, records, loggingLevelModifier, onFinish());

    context.response()
            .end(String.format("Logging level was changed to %s, for %s requests", loggingLevel, recordsAsString));
}
 
Example 3
Source File: ArgumentProvider.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Parse param from path
 * @param mountPoint prefix
 * @param request http request
 * @param index param index
 * @return found param or null if none found
 */
private static String getParam(String mountPoint, HttpServerRequest request, int index) {

	String param = request.getParam("param" + index); // default mount of params without name param0, param1 ...
	if (param == null) { // failed to get directly ... try from request path

		String path = removeMountPoint(mountPoint, request.path());

		String[] items = path.split("/");
		if (index >= 0 && index < items.length) { // simplistic way to find param value from path by index
			return items[index];
		}
	}

	return null;
}
 
Example 4
Source File: PaginationContext.java    From nubes with Apache License 2.0 6 votes vote down vote up
/**
 * The preferred way to create a PaginationContext
 *
 */
public static PaginationContext fromContext(RoutingContext context) {
  HttpServerRequest request = context.request();
  String pageStr = request.getParam(PaginationContext.CURRENT_PAGE_QUERY_PARAM);
  String perPageStr = request.getParam(PaginationContext.PER_PAGE_QUERY_PARAM);
  Integer page = null;
  Integer perPage = null;
  try {
    if (pageStr != null) {
      page = Integer.parseInt(pageStr);
    }
    if (perPageStr != null) {
      perPage = Integer.parseInt(perPageStr);
    }
  } catch (NumberFormatException e) {
    DefaultErrorHandler.badRequest(context, "Invalid pagination parameters : expecting integers");
  }
  if (perPage != null && perPage > PaginationContext.MAX_PER_PAGE) {
    DefaultErrorHandler.badRequest(context, "Invalid " + PaginationContext.PER_PAGE_QUERY_PARAM + " parameter, max is " + PaginationContext.MAX_PER_PAGE);
  }
  return new PaginationContext(page, perPage);
}
 
Example 5
Source File: OfficialAccountSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 更新公众号配置
 * 请求方法: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!");
        }
    });
}
 
Example 6
Source File: CheckTokenHandler.java    From nubes with Apache License 2.0 6 votes vote down vote up
private String parseApiToken(HttpServerRequest request) throws BadRequestException {
  String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);
  if (authorization != null) {
    String[] parts = authorization.split(" ");
    String sscheme = parts[0];
    if (!"token".equals(sscheme)) {
      throw new BadRequestException();
    }
    if (parts.length < 2) {
      throw new BadRequestException();
    }
    return parts[1];
  } else {
    return request.getParam("access_token");
  }

}
 
Example 7
Source File: PaySettingSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 8
Source File: Helper.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the value of the "queries" getRequest parameter, which is an integer
 * bound between 1 and 500 with a default value of 1.
 *
 * @param request the current HTTP request
 * @return the value of the "queries" parameter
 */
static int getQueries(HttpServerRequest request) {
  String param = request.getParam("queries");

  if (param == null) {
    return 1;
  }
  try {
    int parsedValue = Integer.parseInt(param);
    return Math.min(500, Math.max(1, parsedValue));
  } catch (NumberFormatException e) {
    return 1;
  }
}
 
Example 9
Source File: ModuleUtil.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Lookup boolean query parameter in HTTP request.
 * @param req HTTP server request
 * @param name name of query parameter
 * @param defValue default value if omitted
 * @return boolean value
 */
public static boolean getParamBoolean(HttpServerRequest req, String name, boolean defValue) {
  String v = req.getParam(name);
  if (v == null) {
    return defValue;
  } else if ("true".equals(v)) {
    return true;
  } else if ("false".equals(v)) {
    return false;
  }
  throw new DecodeException("Bad boolean for parameter " + name + ": " + v);
}
 
Example 10
Source File: ProbeHandlers.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
static int getPageSize(HttpServerRequest req) {
    String pageSizeParam = req.getParam(PAGE_SIZE);
    if (pageSizeParam == null) {
        return 50;
    } else {
        try {
            int result = Integer.valueOf(pageSizeParam);
            return result > 0 ? result : 0;
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}
 
Example 11
Source File: ImplicitParametersExtractor.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Determines Referer by checking 'url_override' request parameter, or if it's empty 'Referer' header. Then if
 * result is not blank and missing 'http://' prefix appends it.
 */
public String refererFrom(HttpServerRequest request) {
    final String urlOverride = request.getParam("url_override");
    final String url = StringUtils.isNotBlank(urlOverride) ? urlOverride
            : StringUtils.trimToNull(request.headers().get(HttpUtil.REFERER_HEADER));

    return StringUtils.isNotBlank(url) && !StringUtils.startsWith(url, "http")
            ? String.format("http://%s", url)
            : url;
}
 
Example 12
Source File: AmpRequestFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates formats from request parameters to override origin amp banner formats.
 */
private static List<Format> createOverrideBannerFormats(HttpServerRequest request, List<Format> formats) {
    final int overrideWidth = parseIntParamOrZero(request, OW_REQUEST_PARAM);
    final int width = parseIntParamOrZero(request, W_REQUEST_PARAM);
    final int overrideHeight = parseIntParamOrZero(request, OH_REQUEST_PARAM);
    final int height = parseIntParamOrZero(request, H_REQUEST_PARAM);
    final String multiSizeParam = request.getParam(MS_REQUEST_PARAM);

    final List<Format> paramsFormats = createFormatsFromParams(overrideWidth, width, overrideHeight, height,
            multiSizeParam);

    return CollectionUtils.isNotEmpty(paramsFormats)
            ? paramsFormats
            : updateFormatsFromParams(formats, width, height);
}
 
Example 13
Source File: AmpRequestFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private static Imp overrideImp(Imp imp, HttpServerRequest request) {
    final String tagId = request.getParam(SLOT_REQUEST_PARAM);
    final Banner banner = imp.getBanner();
    final List<Format> overwrittenFormats = banner != null
            ? createOverrideBannerFormats(request, banner.getFormat())
            : null;
    if (StringUtils.isNotBlank(tagId) || CollectionUtils.isNotEmpty(overwrittenFormats)) {
        return imp.toBuilder()
                .tagid(StringUtils.isNotBlank(tagId) ? tagId : imp.getTagid())
                .banner(overrideBanner(imp.getBanner(), overwrittenFormats))
                .build();
    }
    return null;
}
 
Example 14
Source File: ProbeHandlers.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
static int getPage(HttpServerRequest req) {
    String pageParam = req.getParam(PAGE);
    if (pageParam == null) {
        return 1;
    }
    try {
        return Integer.valueOf(pageParam);
    } catch (NumberFormatException e) {
        return 1;
    }
}
 
Example 15
Source File: AccountCacheInvalidationHandler.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final HttpServerRequest request = context.request();
    final String accountId = request.getParam(ACCOUNT_ID_PARAM);

    if (StringUtils.isBlank(accountId)) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Account id is not defined");
    } else {
        cachingApplicationSettings.invalidateAccountCache(accountId);
        HttpUtil.respondWith(context, HttpResponseStatus.OK, null);
    }
}
 
Example 16
Source File: TestRestfulController.java    From festival with Apache License 2.0 4 votes vote down vote up
@Produces("application/json")
@GetMapping("/hello3")
public String hello3(HttpServerRequest request) {
    return "id: " + request.getParam("id");
}
 
Example 17
Source File: LoginSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void register(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    String email = req.getParam("email");
    String name = req.getParam("name");
    String password = req.getParam("password");
    String rePassword = req.getParam("repassword");

    //参数判定
    if (email == null || email.trim().length() == 0) {
        log.error("输入的邮箱为空");
        resp.setStatusCode(500).end("EMPTY_EMAIL");
        return;
    }
    if (name == null || name.trim().length() == 0) {
        log.error("输入的用户名为空");
        resp.setStatusCode(500).end("EMPTY_NAME");
        return;
    }
    if (password == null || password.trim().length() == 0) {
        log.error("输入的密码为空");
        resp.setStatusCode(500).end("EMPTY_PSWD");
        return;
    }
    if (rePassword == null || rePassword.trim().length() == 0) {
        log.error("输入的重复密码为空");
        resp.setStatusCode(500).end("EMPTY_REPEAT_PSWD");
        return;
    }
    if (!password.trim().equals(rePassword.trim())) {
        log.error("输入的新密码({})与重复密码不一致({})", password, rePassword);
        resp.setStatusCode(500).end("PSWD_NOT_EQUAL");
        return;
    }

    //注册处理
    log.debug("有用户注册请求,email={}登录密码MD5={}。", email, password);
    vertx.eventBus().<Integer>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_REGISTER, email, password, name),
            ar -> {
                if (ar.succeeded()) {
                    JsonObject result = new JsonObject();
                    Integer id = ar.result().body();
                    if(id == -1){
                        resp.setStatusCode(500).end("DUPLICATE_EMAIL");
                        return;
                    }
                    //jwt保存
                    String token = provider.generateToken(new JsonObject().put("id", id).put("role", 1), JWT_OPTIONS);
                    log.info("用户({},{})注册成功,ID={},角色=普通用户,token={}", name, email, id, token);
                    result.put("result", "success").put("token", token).put("name", name).put("role", 1)
                            .put("id", id).put("email", email);
                    resp.end(result.toString());
                } else {
                    log.error("EventBus消息响应错误", ar.cause());
                    resp.setStatusCode(500).end("EventBus error!");
                }
            });
}
 
Example 18
Source File: PaySettingSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void updateWechatPaySetting(RoutingContext rc) {
    if (forbidAccess(rc, "uid", true)) {
        return;
    }
    Set<FileUpload> uploads = rc.fileUploads();
    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 mchId = req.getParam("mchId");
    String payKey = req.getParam("payKey");

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

    // 异步保存证书文件
    if (uploads != null && !uploads.isEmpty()) {
        for (FileUpload next : uploads) {
            if (paySwitch == 1 && "cert".equals(next.name()) && next.size() > 0) {
                String filePath = Constants.CERT_DIR + uid + "_wxPay.p12";
                FileSystem fs = this.vertx.fileSystem();
                fs.exists(filePath, ex -> {
                    if(ex.succeeded()){
                        Future<Void> delFuture = Future.future();
                        Future<Void> copyFuture = Future.future();
                        fs.delete(filePath, delFuture.completer());
                        fs.copy(next.uploadedFileName(), filePath, copyFuture.completer());
                        if(ex.result()){
                            delFuture.compose(res -> {}, copyFuture);
                        }
                        copyFuture.setHandler(res -> {
                            if (res.succeeded()) {
                                log.info("复制文件{}到{}成功!", next.uploadedFileName(), filePath);
                            } else {
                                log.error("复制文件" + next.uploadedFileName() + "到" + filePath + "失败!", res.cause());
                            }
                        });
                    } else {
                        log.error("判断文件" + filePath + "是否存在时抛出异常!", ex.cause());
                    }
                });
                break;
            }
        }
    }

    //保存支付参数
    JsonObject acc = new JsonObject().put(ID, uid).put(MCHID, mchId).put(MCHKEY, payKey).put(WXPAYON, paySwitch);
    updatePaySetting(resp, acc, COMMAND_UPDATE_WECHATPAY);
}
 
Example 19
Source File: EncryptEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<Hcr> queryHcr(HttpServerRequest httpServerRequest) {
  String hcrId = httpServerRequest.getParam("hcrId");
  return encrypt.queryHcr(hcrId);
}
 
Example 20
Source File: TestRestfulController.java    From festival with Apache License 2.0 4 votes vote down vote up
@Produces("application/json")
@GetMapping("/hello3")
public String hello3(HttpServerRequest request) {
    return "id: " + request.getParam("id");
}