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 Project: spring-analysis-note   Author: Vip-Augus   File: RequestResponseBodyMethodProcessorTests.java    License: 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 #2
Source Project: spring4-understanding   Author: langtianya   File: RequestResponseBodyMethodProcessorTests.java    License: 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 #3
Source Project: nacos-spring-project   Author: nacos-group   File: NacosValueAnnotationBeanPostProcessor.java    License: 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 #4
Source Project: lams   Author: lamsfoundation   File: ListenableFutureReturnValueHandler.java    License: 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 #5
Source Project: java-technology-stack   Author: codeEngraver   File: ResponseEntityResultHandlerTests.java    License: 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 #6
Source Project: mPass   Author: tiankong0310   File: RequestBodyArgumentResolver.java    License: 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 #7
Source Project: java-technology-stack   Author: codeEngraver   File: RequestResponseBodyMethodProcessorTests.java    License: 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 #8
Source Project: sinavi-jfw   Author: ctc-g   File: PostBackManager.java    License: 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 #9
Source Project: spring4-understanding   Author: langtianya   File: ListenableFutureReturnValueHandler.java    License: 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 #10
Source Project: cuba   Author: cuba-platform   File: CubaDefaultListableBeanFactory.java    License: 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 #11
Source Project: java-technology-stack   Author: codeEngraver   File: RequestParamMethodArgumentResolverTests.java    License: 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 #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: HeaderMethodArgumentResolver.java    License: 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 #13
Source Project: lams   Author: lamsfoundation   File: CompositeUriComponentsContributor.java    License: 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 #14
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractWebArgumentResolverAdapter.java    License: 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 #15
Source Project: java-technology-stack   Author: codeEngraver   File: WebSessionArgumentResolver.java    License: MIT License 5 votes vote down vote up
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {

	Mono<WebSession> session = exchange.getSession();
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType());
	return (adapter != null ? Mono.just(adapter.fromPublisher(session)) : Mono.from(session));
}
 
Example #16
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestResponseBodyAdviceChainTests.java    License: MIT License 5 votes vote down vote up
@Override
public String beforeBodyWrite(String body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return body + "-TargetedControllerAdvice";
}
 
Example #17
Source Project: spring4-understanding   Author: langtianya   File: RequestPartMethodArgumentResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Class<?> getCollectionParameterType(MethodParameter methodParam) {
	Class<?> paramType = methodParam.getNestedParameterType();
	if (Collection.class == paramType || List.class.isAssignableFrom(paramType)){
		Class<?> valueType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam);
		if (valueType != null) {
			return valueType;
		}
	}
	return null;
}
 
Example #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Test
public void doesNotSupportParameterWithDefaultResolutionTurnedOff() {
	ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
	this.resolver = new RequestParamMethodArgumentResolver(null, adapterRegistry, false);

	MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class);
	assertFalse(this.resolver.supportsParameter(param));
}
 
Example #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestParamMethodArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Test(expected = MultipartException.class)
public void noMultipartContent() throws Exception {
	request.setMethod("POST");
	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
	resolver.resolveArgument(param, null, webRequest, null);
	fail("Expected exception: no multipart content");
}
 
Example #20
Source Project: blog_demos   Author: zq2599   File: GenericTypeAwarePropertyDescriptor.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized MethodParameter getWriteMethodParameter() {
	if (this.writeMethod == null) {
		return null;
	}
	if (this.writeMethodParameter == null) {
		this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
		GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
	}
	return this.writeMethodParameter;
}
 
Example #21
Source Project: spring4-understanding   Author: langtianya   File: RequestHeaderMethodArgumentResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
	String[] headerValues = request.getHeaderValues(name);
	if (headerValues != null) {
		return (headerValues.length == 1 ? headerValues[0] : headerValues);
	}
	else {
		return null;
	}
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: ResponseEntityResultHandlerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void handleResponseEntityWithNullBody() throws Exception {
	Object returnValue = Mono.just(notFound().build());
	MethodParameter type = on(TestController.class).resolveReturnType(Mono.class, entity(String.class));
	HandlerResult result = handlerResult(returnValue, type);
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/path"));
	this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));

	assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
	assertResponseBodyIsEmpty(exchange);
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: AbstractMessageConverterMethodArgumentResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the binding target if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter descriptor
 * @since 4.1.5
 * @see #isBindExceptionRequired
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
	Annotation[] annotations = parameter.getParameterAnnotations();
	for (Annotation ann : annotations) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example #24
Source Project: java-technology-stack   Author: codeEngraver   File: ModelFactory.java    License: MIT License 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 #25
Source Project: lams   Author: lamsfoundation   File: MethodArgumentTypeMismatchException.java    License: GNU General Public License v2.0 5 votes vote down vote up
public MethodArgumentTypeMismatchException(Object value, Class<?> requiredType,
		String name, MethodParameter param, Throwable cause) {

	super(value, requiredType, cause);
	this.name = name;
	this.parameter = param;
}
 
Example #26
Source Project: nakadi   Author: zalando   File: SubscriptionControllerTest.java    License: MIT License 5 votes vote down vote up
@Override
public Object resolveArgument(final MethodParameter parameter,
                              final ModelAndViewContainer mavContainer,
                              final NativeWebRequest webRequest,
                              final WebDataBinderFactory binderFactory) {
    return new NakadiClient("nakadiClientId", "");
}
 
Example #27
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractMappingJacksonResponseBodyAdvice.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public final Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	if (body == null) {
		return null;
	}
	MappingJacksonValue container = getOrCreateContainer(body);
	beforeBodyWriteInternal(container, contentType, returnType, request, response);
	return container;
}
 
Example #28
Source Project: spring-analysis-note   Author: Vip-Augus   File: MessageMethodArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Test
public void resolveWithConversion() throws Exception {
	Message<String> message = MessageBuilder.withPayload("test").build();
	MethodParameter parameter = new MethodParameter(this.method, 1);

	given(this.converter.fromMessage(message, Integer.class)).willReturn(4);

	@SuppressWarnings("unchecked")
	Message<Integer> actual = (Message<Integer>) this.resolver.resolveArgument(parameter, message);

	assertNotNull(actual);
	assertSame(message.getHeaders(), actual.getHeaders());
	assertEquals(new Integer(4), actual.getPayload());
}
 
Example #29
Source Project: spring-auto-restdocs   Author: ScaCap   File: SkippableConstraintResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<Constraint> resolveForParameter(MethodParameter parameter) {
    List<Constraint> result = new ArrayList<>();
    for (Constraint constraint : delegate.resolveForParameter(parameter)) {
        if (isSkippable(constraint))
            continue;
        result.add(constraint);
    }
    return result;
}
 
Example #30
Source Project: spring-analysis-note   Author: Vip-Augus   File: MatrixVariablesMethodArgumentResolverTests.java    License: 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);
}