org.springframework.web.reactive.BindingContext Java Examples

The following examples show how to use org.springframework.web.reactive.BindingContext. 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: WebSessionArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolverArgument() {

	BindingContext context = new BindingContext();
	WebSession session = mock(WebSession.class);
	MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
	ServerWebExchange exchange = MockServerWebExchange.builder(request).session(session).build();

	MethodParameter param = this.testMethod.arg(WebSession.class);
	Object actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertSame(session, actual);

	param = this.testMethod.arg(Mono.class, WebSession.class);
	actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertNotNull(actual);
	assertTrue(Mono.class.isAssignableFrom(actual.getClass()));
	assertSame(session, ((Mono<?>) actual).block());

	param = this.testMethod.arg(Single.class, WebSession.class);
	actual = this.resolver.resolveArgument(param, context, exchange).block();
	assertNotNull(actual);
	assertTrue(Single.class.isAssignableFrom(actual.getClass()));
	assertSame(session, ((Single<?>) actual).blockingGet());
}
 
Example #2
Source File: AbstractNamedValueArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Resolve the default value, if any.
 */
private Mono<Object> getDefaultValue(NamedValueInfo namedValueInfo, MethodParameter parameter,
		BindingContext bindingContext, Model model, ServerWebExchange exchange) {

	return Mono.fromSupplier(() -> {
		Object value = null;
		if (namedValueInfo.defaultValue != null) {
			value = resolveStringValue(namedValueInfo.defaultValue);
		}
		else if (namedValueInfo.required && !parameter.isOptional()) {
			handleMissingValue(namedValueInfo.name, parameter, exchange);
		}
		value = handleNullValue(namedValueInfo.name, value, parameter.getNestedParameterType());
		value = applyConversion(value, namedValueInfo, parameter, bindingContext, exchange);
		handleResolvedValue(value, namedValueInfo.name, parameter, model, exchange);
		return value;
	});
}
 
Example #3
Source File: SyncInvocableHandlerMethod.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Invoke the method for the given exchange.
 * @param exchange the current exchange
 * @param bindingContext the binding context to use
 * @param providedArgs optional list of argument values to match by type
 * @return a Mono with a {@link HandlerResult}.
 * @throws ServerErrorException if method argument resolution or method invocation fails
 */
@Nullable
public HandlerResult invokeForHandlerResult(ServerWebExchange exchange,
		BindingContext bindingContext, Object... providedArgs) {

	MonoProcessor<HandlerResult> processor = MonoProcessor.create();
	this.delegate.invoke(exchange, bindingContext, providedArgs).subscribeWith(processor);

	if (processor.isTerminated()) {
		Throwable ex = processor.getError();
		if (ex != null) {
			throw (ex instanceof ServerErrorException ? (ServerErrorException) ex :
					new ServerErrorException("Failed to invoke: " + getShortLogMessage(), getMethod(), ex));
		}
		return processor.peek();
	}
	else {
		// Should never happen...
		throw new IllegalStateException(
				"SyncInvocableHandlerMethod should have completed synchronously.");
	}
}
 
Example #4
Source File: RequestHeaderMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.refresh();
	ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
	this.resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultFormattingConversionService());
	this.bindingContext = new BindingContext(initializer);

	Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
	this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 0);
	this.paramNamedValueStringArray = new SynthesizingMethodParameter(method, 1);
	this.paramSystemProperty = new SynthesizingMethodParameter(method, 2);
	this.paramResolvedNameWithExpression = new SynthesizingMethodParameter(method, 3);
	this.paramResolvedNameWithPlaceholder = new SynthesizingMethodParameter(method, 4);
	this.paramNamedValueMap = new SynthesizingMethodParameter(method, 5);
	this.paramDate = new SynthesizingMethodParameter(method, 6);
	this.paramInstant = new SynthesizingMethodParameter(method, 7);
	this.paramMono = new SynthesizingMethodParameter(method, 8);
}
 
Example #5
Source File: CookieValueMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.refresh();

	ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
	this.resolver = new CookieValueMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);
	this.bindingContext = new BindingContext();

	Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
	this.cookieParameter = new SynthesizingMethodParameter(method, 0);
	this.cookieStringParameter = new SynthesizingMethodParameter(method, 1);
	this.stringParameter = new SynthesizingMethodParameter(method, 2);
	this.cookieMonoParameter = new SynthesizingMethodParameter(method, 3);
}
 
Example #6
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void testHttpOptions(String requestURI, Set<HttpMethod> allowedMethods) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options(requestURI));
	HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();

	BindingContext bindingContext = new BindingContext();
	InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
	Mono<HandlerResult> mono = invocable.invoke(exchange, bindingContext);

	HandlerResult result = mono.block();
	assertNotNull(result);

	Object value = result.getReturnValue();
	assertNotNull(value);
	assertEquals(HttpHeaders.class, value.getClass());
	assertEquals(allowedMethods, ((HttpHeaders) value).getAllow());
}
 
Example #7
Source File: ModelMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object resolveArgumentValue(
		MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {

	Class<?> type = parameter.getParameterType();
	if (Model.class.isAssignableFrom(type)) {
		return context.getModel();
	}
	else if (Map.class.isAssignableFrom(type)) {
		return context.getModel().asMap();
	}
	else {
		// Should never happen..
		throw new IllegalStateException("Unexpected method parameter type: " + type);
	}
}
 
Example #8
Source File: RequestAttributeMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveOptional() throws Exception {
	MethodParameter param = this.testMethod.annot(requestAttribute().name("foo")).arg(Optional.class, Foo.class);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);

	assertNotNull(mono.block());
	assertEquals(Optional.class, mono.block().getClass());
	assertFalse(((Optional<?>) mono.block()).isPresent());

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultFormattingConversionService());
	BindingContext bindingContext = new BindingContext(initializer);

	Foo foo = new Foo();
	this.exchange.getAttributes().put("foo", foo);
	mono = this.resolver.resolveArgument(param, bindingContext, this.exchange);

	assertNotNull(mono.block());
	assertEquals(Optional.class, mono.block().getClass());
	Optional<?> optional = (Optional<?>) mono.block();
	assertTrue(optional.isPresent());
	assertSame(foo, optional.get());
}
 
Example #9
Source File: RequestAttributeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-16158
public void resolveMonoParameter() {
	MethodParameter param = this.testMethod.annot(requestAttribute().noName()).arg(Mono.class, Foo.class);

	// Mono attribute
	Foo foo = new Foo();
	Mono<Foo> fooMono = Mono.just(foo);
	this.exchange.getAttributes().put("fooMono", fooMono);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(fooMono, mono.block(Duration.ZERO));

	// RxJava Single attribute
	Single<Foo> singleMono = Single.just(foo);
	this.exchange.getAttributes().clear();
	this.exchange.getAttributes().put("fooMono", singleMono);
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	Object value = mono.block(Duration.ZERO);
	assertTrue(value instanceof Mono);
	assertSame(foo, ((Mono<?>) value).block(Duration.ZERO));

	// No attribute --> Mono.empty
	this.exchange.getAttributes().clear();
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(Mono.empty(), mono.block(Duration.ZERO));
}
 
Example #10
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 #11
Source File: InitBinderBindingContextTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinder() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example #12
Source File: RequestPartMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Flux<?> decodePartValues(Flux<Part> parts, MethodParameter elementType, BindingContext bindingContext,
		ServerWebExchange exchange, boolean isRequired) {

	return parts.flatMap(part -> {
		ServerHttpRequest partRequest = new PartServerHttpRequest(exchange.getRequest(), part);
		ServerWebExchange partExchange = exchange.mutate().request(partRequest).build();
		if (logger.isDebugEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Decoding part '" + part.name() + "'");
		}
		return readBody(elementType, isRequired, bindingContext, partExchange);
	});
}
 
Example #13
Source File: InitBinderBindingContextTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrName() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example #14
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 #15
Source File: RequestAttributeMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveWithName() throws Exception {
	MethodParameter param = this.testMethod.annot(requestAttribute().name("specialFoo")).arg();
	Foo foo = new Foo();
	this.exchange.getAttributes().put("specialFoo", foo);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}
 
Example #16
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void partNotRequired() {
	MethodParameter param = this.testMethod.annot(requestPart().notRequired()).arg(Part.class);
	ServerWebExchange exchange = createExchange(new MultipartBodyBuilder());
	Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);

	StepVerifier.create(result).verifyComplete();
}
 
Example #17
Source File: ControllerAdviceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void initBinderAdvice() throws Exception {
	ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
	RequestMappingHandlerAdapter adapter = createAdapter(context);
	TestController controller = context.getBean(TestController.class);

	Validator validator = mock(Validator.class);
	controller.setValidator(validator);

	BindingContext bindingContext = handle(adapter, controller, "handle").getBindingContext();

	WebExchangeDataBinder binder = bindingContext.createDataBinder(this.exchange, "name");
	assertEquals(Collections.singletonList(validator), binder.getValidators());
}
 
Example #18
Source File: PathVariableMapMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveArgumentNoUriVars() throws Exception {
	Mono<Object> mono = this.resolver.resolveArgument(this.paramMap, new BindingContext(), this.exchange);
	Object result = mono.block();

	assertEquals(Collections.emptyMap(), result);
}
 
Example #19
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T resolveValue(MethodParameter param, String body) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/path").body(body));
	Mono<Object> result = this.resolver.readBody(param, true, new BindingContext(), exchange);
	Object value = result.block(Duration.ofSeconds(5));

	assertNotNull(value);
	assertTrue("Unexpected return value type: " + value,
			param.getParameterType().isAssignableFrom(value.getClass()));

	//no inspection unchecked
	return (T) value;
}
 
Example #20
Source File: RequestBodyMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T resolveValue(MethodParameter param, String body) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/path").body(body));
	Mono<Object> result = this.resolver.readBody(param, true, new BindingContext(), exchange);
	Object value = result.block(Duration.ofSeconds(5));

	assertNotNull(value);
	assertTrue("Unexpected return value type: " + value,
			param.getParameterType().isAssignableFrom(value.getClass()));

	//no inspection unchecked
	return (T) value;
}
 
Example #21
Source File: InitBinderBindingContextTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderNullAttrName() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);

	assertNull(dataBinder.getDisallowedFields());
}
 
Example #22
Source File: InitBinderBindingContextTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
Example #23
Source File: SessionAttributeMethodArgumentResolverTests.java    From spring-analysis-note 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();
	given(this.session.getAttribute("foo")).willReturn(foo);
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}
 
Example #24
Source File: ProxyExchangeArgumentResolver.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Object> resolveArgument(MethodParameter parameter,
		BindingContext bindingContext, ServerWebExchange exchange) {
	ProxyExchange<?> proxy = new ProxyExchange<>(rest, exchange, bindingContext,
			type(parameter));
	proxy.headers(headers);
	if (this.autoForwardedHeaders.size() > 0) {
		proxy.headers(extractAutoForwardedHeaders(exchange));
	}
	if (sensitive != null) {
		proxy.sensitive(sensitive.toArray(new String[0]));
	}
	return Mono.just(proxy);
}
 
Example #25
Source File: MatrixVariablesMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveArgumentNoParams() throws Exception {

	MethodParameter param = this.testMethod.annot(matrixAttribute().noName())
			.arg(Map.class, String.class, String.class);

	@SuppressWarnings("unchecked")
	Map<String, String> map = (Map<String, String>)
			this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO);

	assertEquals(Collections.emptyMap(), map);
}
 
Example #26
Source File: RequestAttributeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveNotRequired() {
	MethodParameter param = this.testMethod.annot(requestAttribute().name("foo").notRequired()).arg();
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertNull(mono.block());

	Foo foo = new Foo();
	this.exchange.getAttributes().put("foo", foo);
	mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}
 
Example #27
Source File: RequestAttributeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveWithName() {
	MethodParameter param = this.testMethod.annot(requestAttribute().name("specialFoo")).arg();
	Foo foo = new Foo();
	this.exchange.getAttributes().put("specialFoo", foo);
	Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
	assertSame(foo, mono.block());
}
 
Example #28
Source File: RequestAttributeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolve() {
	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 #29
Source File: HttpEntityArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {

	Class<?> entityType = parameter.getParameterType();
	return readBody(parameter.nested(), parameter, false, bindingContext, exchange)
			.map(body -> createEntity(body, entityType, exchange.getRequest()))
			.defaultIfEmpty(createEntity(null, entityType, exchange.getRequest()));
}
 
Example #30
Source File: PathVariableMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveArgument() {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	BindingContext bindingContext = new BindingContext();
	Mono<Object> mono = this.resolver.resolveArgument(this.paramNamedString, bindingContext, this.exchange);
	Object result = mono.block();
	assertEquals("value", result);
}