org.springframework.web.server.ServerWebInputException Java Examples

The following examples show how to use org.springframework.web.server.ServerWebInputException. 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: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithObservable() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Observable.class, String.class);
	Observable<String> observable = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(observable))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Observable.class, String.class);
	observable = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(observable))
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #2
Source File: DefaultServerRequestTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyToMonoDecodingException() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("{\"invalid\":\"json\" ".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.APPLICATION_JSON);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.POST, "http://example.com/invalid")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders);

	Mono<Map<String, String>> resultMono = request.bodyToMono(
			new ParameterizedTypeReference<Map<String, String>>() {});
	StepVerifier.create(resultMono)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #3
Source File: RequestBodyMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithObservable() {
	MethodParameter param = this.testMethod.annot(requestBody()).arg(Observable.class, String.class);
	Observable<String> observable = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(observable))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Observable.class, String.class);
	observable = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(observable))
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #4
Source File: RequestBodyMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithMaybe() {
	MethodParameter param = this.testMethod.annot(requestBody()).arg(Maybe.class, String.class);
	Maybe<String> maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Maybe.class, String.class);
	maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #5
Source File: RequestBodyMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithSingle() {
	MethodParameter param = this.testMethod.annot(requestBody()).arg(Single.class, String.class);
	Single<String> single = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(single))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Single.class, String.class);
	single = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(single))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #6
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithMaybe() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Maybe.class, String.class);
	Maybe<String> maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Maybe.class, String.class);
	maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #7
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void emptyBodyWithMono() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Mono.class, String.class);
	StepVerifier.create((Mono<Void>) resolveValueWithEmptyBody(param))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Mono.class, String.class);
	StepVerifier.create((Mono<Void>) resolveValueWithEmptyBody(param))
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #8
Source File: DefaultServerRequestTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bodyToMonoDecodingException() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("{\"invalid\":\"json\" ".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.APPLICATION_JSON);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.POST, "https://example.com/invalid")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders);

	Mono<Map<String, String>> resultMono = request.bodyToMono(
			new ParameterizedTypeReference<Map<String, String>>() {});
	StepVerifier.create(resultMono)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #9
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void emptyBodyWithFlux() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Flux.class, String.class);
	StepVerifier.create((Flux<Void>) resolveValueWithEmptyBody(param))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Flux.class, String.class);
	StepVerifier.create((Flux<Void>) resolveValueWithEmptyBody(param))
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #10
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithSingle() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Single.class, String.class);
	Single<String> single = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(single))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Single.class, String.class);
	single = resolveValueWithEmptyBody(param);
	StepVerifier.create(RxReactiveStreams.toPublisher(single))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #11
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void partRequired() {
	MethodParameter param = this.testMethod.annot(requestPart()).arg(Part.class);
	ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
	Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);

	StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
 
Example #12
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-12854
public void getHandlerTestRequestParamMismatch() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/params"));
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);
	assertError(mono, ServerWebInputException.class, ex -> {
		assertThat(ex.getReason(), containsString("[foo=bar]"));
		assertThat(ex.getReason(), containsString("[bar=baz]"));
	});
}
 
Example #13
Source File: RequestHeaderMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void notFound() {
	Mono<Object> mono = resolver.resolveArgument(
			this.paramNamedValueStringArray, this.bindingContext,
			MockServerWebExchange.from(MockServerHttpRequest.get("/")));

	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #14
Source File: CookieValueMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void notFound() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	Mono<Object> mono = resolver.resolveArgument(this.cookieParameter, this.bindingContext, exchange);
	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #15
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .get(INT_QUERY_PARAM_REQUIRED_ENDPOINT)
            .then()
            .log().all()
            .extract();

    ApiError expectedApiError = new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        // We can't expect the bad_property_name=requiredQueryParamValue metadata like we do in Spring Web MVC,
        //      because Spring WebFlux doesn't add it to the TypeMismatchException cause.
        MapBuilder.builder("bad_property_value", (Object) "not-an-integer")
                  .put("required_type", "int")
                  .build()
    );

    verifyErrorReceived(response, expectedApiError);
    ServerWebInputException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ServerWebInputException.class, 400
    );
    TypeMismatchException tme = verifyExceptionHasCauseOfType(ex, TypeMismatchException.class);
    verifyHandlingResult(
        expectedApiError,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("method_parameter", ex.getMethodParameter().toString()),
        Pair.of("bad_property_name", tme.getPropertyName()),
        Pair.of("bad_property_value", tme.getValue().toString()),
        Pair.of("required_type", tme.getRequiredType().toString())
    );
}
 
Example #16
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void personRequired() {
	MethodParameter param = this.testMethod.annot(requestPart()).arg(Person.class);
	ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
	Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);

	StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
 
Example #17
Source File: DataHandler.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
public Mono<ServerResponse> get(ServerRequest request) {
    String count = request.queryParam("count")
        .orElseThrow(() -> new ServerWebInputException("Count is required"));
    String email = request.queryParam("email")
        .orElseThrow(() -> new ServerWebInputException("Email is required"));

    System.out.println(String.format("Request for %s entries", count));

    // Get data from httpbin
    Flux<String> chunks = client.get()
        .uri("/stream/{count}", count)
        .retrieve()
        .bodyToFlux(String.class)
        .log()
        // Delay to make a stream of data easily visible in the UI
        .delayElements(Duration.ofMillis(200))
        .publish()
        .refCount(2);

    // Send batches of 10 entries by email
    chunks.buffer(10)
        .flatMap(entries -> this.sendEmail(email, entries))
        .subscribe();

    // Return a stream of entries to the requester
    return ok()
        .contentType(APPLICATION_JSON)
        .body(chunks, String.class);
}
 
Example #18
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing_and_error_metadata_must_be_extracted_from_ex_reason() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(INT_QUERY_PARAM_REQUIRED_ENDPOINT)
            .then()
            .log().all()
            .extract();

    ApiError expectedApiError = new ApiErrorWithMetadata(
        SampleCoreApiError.MALFORMED_REQUEST,
        Pair.of("missing_param_type", "int"),
        Pair.of("missing_param_name", "requiredQueryParamValue")
    );

    verifyErrorReceived(response, expectedApiError);
    ServerWebInputException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ServerWebInputException.class, 400
    );
    verifyHandlingResult(
        expectedApiError,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("method_parameter", ex.getMethodParameter().toString())
    );
    // Verify no cause, leaving the exception `reason` as the only way we could have gotten the metadata.
    assertThat(ex).hasNoCause();
    assertThat(ex.getReason()).isEqualTo("Required int parameter 'requiredQueryParamValue' is not present");
}
 
Example #19
Source File: RequestAttributeMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolve() throws Exception {
	MethodParameter param = this.testMethod.annot(requestAttribute().noName()).arg(Foo.class);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	Foo foo = new Foo();
	this.exchange.getAttributes().put("foo", foo);
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}
 
Example #20
Source File: HttpEntityArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void emptyBodyWithSingle() throws Exception {
	ResolvableType type = httpEntityType(Single.class, String.class);
	HttpEntity<Single<String>> entity = resolveValueWithEmptyBody(type);

	StepVerifier.create(RxReactiveStreams.toPublisher(entity.getBody()))
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #21
Source File: ServerWebInputExceptionHandler.java    From staccato with Apache License 2.0 5 votes vote down vote up
@Override
protected String getMessage(ServerWebInputException ex) {

    Throwable t = ex.getCause();
    if (t != null && t.getCause() != null && t.getCause() instanceof UnrecognizedPropertyException) {
        String propertyName = ((UnrecognizedPropertyException) t.getCause()).getPropertyName();
        Collection knownFields = ((UnrecognizedPropertyException) t.getCause()).getKnownPropertyIds();
        return InvalidParameterException.buildMessage(propertyName, knownFields);
    }

    return ex.getMessage();
}
 
Example #22
Source File: RequestHeaderMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void notFound() throws Exception {
	Mono<Object> mono = resolver.resolveArgument(
			this.paramNamedValueStringArray, this.bindingContext,
			MockServerWebExchange.from(MockServerHttpRequest.get("/")));

	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #23
Source File: CookieValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void notFound() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	Mono<Object> mono = resolver.resolveArgument(this.cookieParameter, this.bindingContext, exchange);
	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #24
Source File: RequestPartMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void partRequired() {
	MethodParameter param = this.testMethod.annot(requestPart()).arg(Part.class);
	ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
	Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);

	StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
 
Example #25
Source File: RequestPartMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void personRequired() {
	MethodParameter param = this.testMethod.annot(requestPart()).arg(Person.class);
	ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
	Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);

	StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
 
Example #26
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void missingRequestParam() {

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class);
	Mono<Object> mono = this.resolver.resolveArgument(param, this.bindContext, exchange);

	StepVerifier.create(mono)
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #27
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test @SuppressWarnings("unchecked") // SPR-9942
public void emptyBody() throws Exception {
	MockServerHttpRequest request = post("/path").contentType(MediaType.APPLICATION_JSON).build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
	MethodParameter param = this.testMethod.arg(type);
	Mono<TestBean> result = (Mono<TestBean>) this.resolver.readBody(
			param, true, this.bindingContext, exchange).block();

	StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
 
Example #28
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void validateMonoTestBean() throws Exception {
	String body = "{\"bar\":\"b1\"}";
	ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
	MethodParameter param = this.testMethod.arg(type);
	Mono<TestBean> mono = resolveValue(param, body);

	StepVerifier.create(mono).expectNextCount(0).expectError(ServerWebInputException.class).verify();
}
 
Example #29
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void validateFluxTestBean() throws Exception {
	String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\"}]";
	ResolvableType type = forClassWithGenerics(Flux.class, TestBean.class);
	MethodParameter param = this.testMethod.arg(type);
	Flux<TestBean> flux = resolveValue(param, body);

	StepVerifier.create(flux)
			.expectNext(new TestBean("f1", "b1"))
			.expectError(ServerWebInputException.class)
			.verify();
}
 
Example #30
Source File: SessionAttributeMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolve() {
	MethodParameter param = initMethodParameter(0);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	StepVerifier.create(mono).expectError(ServerWebInputException.class).verify();

	Foo foo = new Foo();
	when(this.session.getAttribute("foo")).thenReturn(foo);
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}