org.springframework.core.MethodParameter Java Examples

The following examples show how to use org.springframework.core.MethodParameter. 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: RequestBodyArgumentResolver.java    From mPass with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean supportsParameter(MethodParameter parameter) {
    boolean supported = parameter.hasParameterAnnotation(RequestBody.class);
    if (!supported) {
        Method curMethod = (Method) parameter.getExecutable();
        Class<?> curClass = curMethod.getDeclaringClass();
        List<Class<?>> supperList =new ArrayList<>(Arrays.asList(curClass.getInterfaces()));
        Class superclass=curClass.getSuperclass();
        if(superclass!=null && !Object.class.equals(superclass) ){
            supperList.add(superclass);
        }
        for (Class<?> clazz : supperList) {
            if (hasRequestBodyAnnotation(clazz, parameter)) {
                supported = true;
                break;
            }
        }
    }
    return supported;
}
 
Example #2
Source File: CubaDefaultListableBeanFactory.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames,
                                TypeConverter typeConverter) throws BeansException {
    Field field = descriptor.getField();

    if (field != null && Logger.class == descriptor.getDependencyType()) {
        return LoggerFactory.getLogger(getDeclaringClass(descriptor));
    }

    if (field != null && Config.class.isAssignableFrom(field.getType())) {
        return getConfig(field.getType());
    }
    MethodParameter methodParam = descriptor.getMethodParameter();
    if (methodParam != null && Config.class.isAssignableFrom(methodParam.getParameterType())) {
        return getConfig(methodParam.getParameterType());
    }
    return super.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
}
 
Example #3
Source File: HeaderMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) {

	Object headerValue = message.getHeaders().get(name);
	Object nativeHeaderValue = getNativeHeaderValue(message, name);

	if (headerValue != null && nativeHeaderValue != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("A value was found for '" + name + "', in both the top level header map " +
					"and also in the nested map for native headers. Using the value from top level map. " +
					"Use 'nativeHeader.myHeader' to resolve the native header.");
		}
	}

	return (headerValue != null ? headerValue : nativeHeaderValue);
}
 
Example #4
Source File: CompositeUriComponentsContributor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	for (Object contributor : this.contributors) {
		if (contributor instanceof UriComponentsContributor) {
			UriComponentsContributor ucc = (UriComponentsContributor) contributor;
			if (ucc.supportsParameter(parameter)) {
				ucc.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService);
				break;
			}
		}
		else if (contributor instanceof HandlerMethodArgumentResolver) {
			if (((HandlerMethodArgumentResolver) contributor).supportsParameter(parameter)) {
				break;
			}
		}
	}
}
 
Example #5
Source File: AbstractWebArgumentResolverAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Delegate to the {@link WebArgumentResolver} instance.
 * @throws IllegalStateException if the resolved value is not assignable
 * to the method parameter.
 */
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	Class<?> paramType = parameter.getParameterType();
	Object result = this.adaptee.resolveArgument(parameter, webRequest);
	if (result == WebArgumentResolver.UNRESOLVED || !ClassUtils.isAssignableValue(paramType, result)) {
		throw new IllegalStateException(
				"Standard argument type [" + paramType.getName() + "] in method " + parameter.getMethod() +
				"resolved to incompatible value of type [" + (result != null ? result.getClass() : null) +
				"]. Consider declaring the argument type in a less specific fashion.");
	}
	return result;
}
 
Example #6
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseBodyAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseBody");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2XmlHttpMessageConverter());

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseBody();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #7
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolvePartList() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	MockPart expected1 = new MockPart("pfilelist", "Hello World 1".getBytes());
	MockPart expected2 = new MockPart("pfilelist", "Hello World 2".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(new MockPart("other", "Hello World 3".getBytes()));
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof List);
	assertEquals(Arrays.asList(expected1, expected2), result);
}
 
Example #8
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	Method method = JacksonController.class.getMethod("handleRequestBody", JacksonViewBean.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new MappingJackson2HttpMessageConverter());

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	JacksonViewBean result = (JacksonViewBean)processor.resolveArgument(methodParameter,
			this.mavContainer, this.webRequest, this.binderFactory);

	assertNotNull(result);
	assertEquals("with", result.getWithView1());
	assertNull(result.getWithView2());
	assertNull(result.getWithoutView());
}
 
Example #9
Source File: NacosValueAnnotationBeanPostProcessor.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
private Object convertIfNecessary(Method method, Object value) {
	Class<?>[] paramTypes = method.getParameterTypes();
	Object[] arguments = new Object[paramTypes.length];

	TypeConverter converter = beanFactory.getTypeConverter();

	if (arguments.length == 1) {
		return converter.convertIfNecessary(value, paramTypes[0],
				new MethodParameter(method, 0));
	}

	for (int i = 0; i < arguments.length; i++) {
		arguments[i] = converter.convertIfNecessary(value, paramTypes[i],
				new MethodParameter(method, i));
	}

	return arguments;
}
 
Example #10
Source File: ListenableFutureReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #11
Source File: ListenableFutureReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #12
Source File: PostBackManager.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 現在のリクエストに対してポストバック機構を開始します。
 * </p>
 * @param request リクエスト
 * @param handlerMethod ハンドラ
 */
public static void begin(HttpServletRequest request, HandlerMethod handlerMethod) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    PostBackManager instance = new PostBackManager(request , handlerMethod);
    requestAttributes.setAttribute(STORE_KEY_TO_REQUEST, instance, RequestAttributes.SCOPE_REQUEST);
    MessageContext messageContext = (MessageContext) requestAttributes.getAttribute(MessageContext.MESSAGE_CONTEXT_ATTRIBUTE_KEY, RequestAttributes.SCOPE_REQUEST);
    if (messageContext == null) {
        requestAttributes.setAttribute(MessageContext.MESSAGE_CONTEXT_ATTRIBUTE_KEY, new MessageContext(request), RequestAttributes.SCOPE_REQUEST);
    }
    instance.targetControllerType = handlerMethod.getBeanType();
    for (MethodParameter methodParameter : handlerMethod.getMethodParameters()) {
        ModelAttribute attr = methodParameter.getParameterAnnotation(ModelAttribute.class);
        if (attr != null) {
            instance.modelAttributeType = methodParameter.getParameterType();
        }
    }
}
 
Example #13
Source File: ResponseEntityResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handleReturnValueETagAndLastModified() throws Exception {
	String eTag = "\"deadb33f8badf00d\"";

	Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
	Instant oneMinAgo = currentTime.minusSeconds(60);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")
			.ifNoneMatch(eTag)
			.ifModifiedSince(currentTime.toEpochMilli())
			);

	ResponseEntity<String> entity = ok().eTag(eTag).lastModified(oneMinAgo.toEpochMilli()).body("body");
	MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
	HandlerResult result = handlerResult(entity, returnType);
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, eTag, oneMinAgo);
}
 
Example #14
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	Method method = JacksonController.class.getMethod("handleRequestBody", JacksonViewBean.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	JacksonViewBean result = (JacksonViewBean)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertEquals("with", result.getWithView1());
	assertNull(result.getWithView2());
	assertNull(result.getWithoutView());
}
 
Example #15
Source File: MessageMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveWithMatchingPayloadType() throws Exception {
	Message<Integer> message = MessageBuilder.withPayload(123).build();
	MethodParameter parameter = new MethodParameter(this.method, 1);

	assertTrue(this.resolver.supportsParameter(parameter));
	assertSame(message, this.resolver.resolveArgument(parameter, message));
}
 
Example #16
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
	Class<?> paramType = parameter.getParameterType();
	NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);

	Object arg = resolveArgumentInternal(parameter, message, namedValueInfo.name);
	if (arg == null) {
		if (namedValueInfo.defaultValue != null) {
			arg = resolveDefaultValue(namedValueInfo.defaultValue);
		}
		else if (namedValueInfo.required && !parameter.getParameterType().getName().equals("java.util.Optional")) {
			handleMissingValue(namedValueInfo.name, parameter, message);
		}
		arg = handleNullValue(namedValueInfo.name, arg, paramType);
	}
	else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
		arg = resolveDefaultValue(namedValueInfo.defaultValue);
	}

	if (!ClassUtils.isAssignableValue(paramType, arg)) {
		arg = this.conversionService.convert(
				arg, TypeDescriptor.valueOf(arg.getClass()), new TypeDescriptor(parameter));
	}

	handleResolvedValue(arg, namedValueInfo.name, parameter, message);

	return arg;
}
 
Example #17
Source File: HandlerMethod.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
protected static Object findProvidedArgument(MethodParameter parameter, @Nullable Object... providedArgs) {
	if (!ObjectUtils.isEmpty(providedArgs)) {
		for (Object providedArg : providedArgs) {
			if (parameter.getParameterType().isInstance(providedArg)) {
				return providedArg;
			}
		}
	}
	return null;
}
 
Example #18
Source File: ServletRequestMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void localeFromResolver() throws Exception {
	Locale locale = Locale.ENGLISH;
	servletRequest.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
			new FixedLocaleResolver(locale));

	MethodParameter localeParameter = new MethodParameter(method, 4);
	assertTrue("Locale not supported", resolver.supportsParameter(localeParameter));

	Object result = resolver.resolveArgument(localeParameter, null, webRequest, null);
	assertSame("Invalid result", locale, result);
}
 
Example #19
Source File: MockMethods.java    From jfilter with Apache License 2.0 5 votes vote down vote up
@FieldFilterSetting(className = MockUser.class, fields = {"id", "email", "fullName"})
@FieldFilterSetting(className = MockUser.class, fields = {"password", "intValue", "collectionValue"})
@FieldFilterSetting(className = MockUser.class, fields = {"mapValue", "boolValue", "byteValue", "charValue"})
@FieldFilterSetting(className = MockUser.class, fields = {"doubleValue", "floatValue", "longValue", "shortValue"})
public static MethodParameter multipleAnnotation() {
    return findMethodParameterByName("multipleAnnotation");
}
 
Example #20
Source File: MatrixVariableMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	if (!parameter.hasParameterAnnotation(MatrixVariable.class)) {
		return false;
	}
	if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {
		MatrixVariable matrixVariable = parameter.getParameterAnnotation(MatrixVariable.class);
		return (matrixVariable != null && StringUtils.hasText(matrixVariable.name()));
	}
	return true;
}
 
Example #21
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets return type.
 *
 * @param methodParameter the method parameter
 * @return the return type
 */
private Type getReturnType(MethodParameter methodParameter) {
	Type returnType = Object.class;
	for (ReturnTypeParser returnTypeParser : returnTypeParsers) {
		if (returnType.getTypeName().equals(Object.class.getTypeName())) {
			returnType = returnTypeParser.getReturnType(methodParameter);
		}
		else
			break;
	}

	return returnType;
}
 
Example #22
Source File: ModelInitializer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private String getAttributeName(MethodParameter param) {
	return Optional
			.ofNullable(AnnotatedElementUtils.findMergedAnnotation(param.getAnnotatedElement(), ModelAttribute.class))
			.filter(ann -> StringUtils.hasText(ann.value()))
			.map(ModelAttribute::value)
			.orElseGet(() -> Conventions.getVariableNameForParameter(param));
}
 
Example #23
Source File: MessageMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-16486
public void resolveWithJacksonConverter() throws Exception {
	Message<String> inMessage = MessageBuilder.withPayload("{\"foo\":\"bar\"}").build();
	MethodParameter parameter = new MethodParameter(this.method, 5);

	this.resolver = new MessageMethodArgumentResolver(new MappingJackson2MessageConverter());
	Object actual = this.resolver.resolveArgument(parameter, inMessage);

	assertTrue(actual instanceof Message);
	Message<?> outMessage = (Message<?>) actual;
	assertTrue(outMessage.getPayload() instanceof Foo);
	assertEquals("bar", ((Foo) outMessage.getPayload()).getFoo());
}
 
Example #24
Source File: HandlerMethodReturnValueHandlerCompositeTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {

	this.integerType = new MethodParameter(getClass().getDeclaredMethod("handleInteger"), -1);
	this.stringType = new MethodParameter(getClass().getDeclaredMethod("handleString"), -1);

	this.integerHandler = mock(HandlerMethodReturnValueHandler.class);
	when(this.integerHandler.supportsReturnType(this.integerType)).thenReturn(true);

	this.handlers = new HandlerMethodReturnValueHandlerComposite();
	this.handlers.addHandler(this.integerHandler);

	mavContainer = new ModelAndViewContainer();
}
 
Example #25
Source File: ModelFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ModelMethod(InvocableHandlerMethod handlerMethod) {
	this.handlerMethod = handlerMethod;
	for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
		if (parameter.hasParameterAnnotation(ModelAttribute.class)) {
			this.dependencies.add(getNameForParameter(parameter));
		}
	}
}
 
Example #26
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Fall back on the parameter name from the class file if necessary and
 * replace {@link ValueConstants#DEFAULT_NONE} with null.
 */
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
	String name = info.name;
	if (info.name.isEmpty()) {
		name = parameter.getParameterName();
		if (name == null) {
			Class<?> type = parameter.getParameterType();
			throw new IllegalArgumentException(
					"Name for argument of type [" + type.getName() + "] not specified, " +
							"and parameter name information not found in class file either.");
		}
	}
	return new NamedValueInfo(name, info.required,
			ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
}
 
Example #27
Source File: ServletRequestMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void timeZoneFromResolver() throws Exception {
	TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
	servletRequest.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
			new FixedLocaleResolver(Locale.US, timeZone));

	MethodParameter timeZoneParameter = new MethodParameter(method, 8);
	assertTrue("TimeZone not supported", resolver.supportsParameter(timeZoneParameter));

	Object result = resolver.resolveArgument(timeZoneParameter, null, webRequest, null);
	assertEquals("Invalid result", timeZone, result);
}
 
Example #28
Source File: MatrixVariablesMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = ServletRequestBindingException.class)
public void resolveArgumentMultipleMatches() throws Exception {
	getVariablesFor("var1").add("colors", "red");
	getVariablesFor("var2").add("colors", "green");
	MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class);

	this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null);
}
 
Example #29
Source File: InvocableHandlerMethod.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Mono<Object[]> getMethodArgumentValues(
		ServerWebExchange exchange, BindingContext bindingContext, Object... providedArgs) {

	if (ObjectUtils.isEmpty(getMethodParameters())) {
		return EMPTY_ARGS;
	}
	MethodParameter[] parameters = getMethodParameters();
	List<Mono<Object>> argMonos = new ArrayList<>(parameters.length);
	for (MethodParameter parameter : parameters) {
		parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
		Object providedArg = findProvidedArgument(parameter, providedArgs);
		if (providedArg != null) {
			argMonos.add(Mono.just(providedArg));
			continue;
		}
		if (!this.resolvers.supportsParameter(parameter)) {
			return Mono.error(new IllegalStateException(
					formatArgumentError(parameter, "No suitable resolver")));
		}
		try {
			argMonos.add(this.resolvers.resolveArgument(parameter, bindingContext, exchange)
					.defaultIfEmpty(NO_ARG_VALUE)
					.doOnError(cause -> logArgumentErrorIfNecessary(exchange, parameter, cause)));
		}
		catch (Exception ex) {
			logArgumentErrorIfNecessary(exchange, parameter, ex);
			argMonos.add(Mono.error(ex));
		}
	}
	return Mono.zip(argMonos, values ->
			Stream.of(values).map(o -> o != NO_ARG_VALUE ? o : null).toArray());
}
 
Example #30
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {

	NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
	MethodParameter nestedParameter = parameter.nestedIfOptional();

	Object resolvedName = resolveEmbeddedValuesAndExpressions(namedValueInfo.name);
	if (resolvedName == null) {
		throw new IllegalArgumentException(
				"Specified name must not resolve to null: [" + namedValueInfo.name + "]");
	}

	Object arg = resolveArgumentInternal(nestedParameter, message, resolvedName.toString());
	if (arg == null) {
		if (namedValueInfo.defaultValue != null) {
			arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
		}
		else if (namedValueInfo.required && !nestedParameter.isOptional()) {
			handleMissingValue(namedValueInfo.name, nestedParameter, message);
		}
		arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
	}
	else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
		arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);
	}

	if (parameter != nestedParameter || !ClassUtils.isAssignableValue(parameter.getParameterType(), arg)) {
		arg = this.conversionService.convert(arg, TypeDescriptor.forObject(arg), new TypeDescriptor(parameter));
	}

	handleResolvedValue(arg, namedValueInfo.name, parameter, message);

	return arg;
}