RequestImpl implements Request { @Override public <T> T bean(Class<T> beanClass) { try { if (method == HTTPMethod.GET || method == HTTPMethod.DELETE) { return reader.fromParams(beanClass, queryParams); } else if (method == HTTPMethod.POST || method == HTTPMethod.PUT || method == HTTPMethod.PATCH) { if (!formParams.isEmpty()) { return reader.fromParams(beanClass, formParams); } else if (body != null && contentType != null && ContentType.APPLICATION_JSON.mediaType.equals(contentType.mediaType)) { return reader.fromJSON(beanClass, body); } throw new BadRequestException(format("body is missing or unsupported content type, method={}, contentType={}", method, contentType), "INVALID_HTTP_REQUEST"); } else { throw new Error("not supported method, method=" + method); } } catch (ValidationException e) { throw new BadRequestException(e.getMessage(), e.errorCode(), e); } catch (IOException e) { throw new BadRequestException("failed to deserialize request, beanClass=" + beanClass.getCanonicalName(), "INVALID_HTTP_REQUEST", e); } } RequestImpl(HttpServerExchange exchange, RequestBeanReader reader); @Override String requestURL(); @Override String scheme(); @Override String hostName(); @Override String path(); @Override String clientIP(); @Override Optional<String> cookie(CookieSpec spec); @Override Session session(); @Override HTTPMethod method(); @Override Optional<String> header(String name); @Override String pathParam(String name); @Override Map<String, String> queryParams(); @Override Map<String, String> formParams(); @Override Map<String, MultipartFile> files(); @Override Optional<byte[]> body(); @Override T bean(Class<T> beanClass); final PathParams pathParams; public Session session; }
@Test void beanWithGet() { request.method = HTTPMethod.GET; request.queryParams.put("int_field", "1"); TestQueryParamBean bean = request.bean(TestQueryParamBean.class); assertThat(bean.intField).isEqualTo(1); }
@Test void beanWithJSONPost() { request.method = HTTPMethod.POST; request.contentType = ContentType.APPLICATION_JSON; request.body = Strings.bytes("{\"big_decimal_field\": 1, \"int_field\": 3}"); TestBean bean = request.bean(TestBean.class); assertThat(bean.bigDecimalField).isEqualTo("1"); }
@Test void beanWithFormPost() { request.method = HTTPMethod.POST; request.formParams.put("long_field", "1"); TestQueryParamBean bean = request.bean(TestQueryParamBean.class); assertThat(bean.longField).isEqualTo(1); }
@Test void beanWithValidationError() { request.method = HTTPMethod.POST; request.contentType = ContentType.APPLICATION_JSON; request.body = Strings.bytes("{\"big_decimal_field\": 1}"); assertThatThrownBy(() -> request.bean(TestBean.class)) .isInstanceOf(BadRequestException.class) .satisfies(exception -> assertThat(((BadRequestException) exception).errorCode()).isEqualTo("VALIDATION_ERROR")); }