Java Code Examples for org.springframework.web.method.HandlerMethod#getMethodParameters()

The following examples show how to use org.springframework.web.method.HandlerMethod#getMethodParameters() . 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: HttpEntityMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveArgumentTypeVariable() throws Exception {
	Method method = MySimpleParameterizedController.class.getMethod("handleDto", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

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

	@SuppressWarnings("unchecked")
	HttpEntity<SimpleBean> result = (HttpEntity<SimpleBean>)
			processor.resolveArgument(methodParam, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getBody().getName());
}
 
Example 2
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-14470
public void resolveParameterizedWithTypeVariableArgument() throws Exception {
	Method method = MyParameterizedControllerWithList.class.getMethod("handleDto", List.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedControllerWithList(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

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

	@SuppressWarnings("unchecked")
	List<SimpleBean> result = (List<SimpleBean>) processor.resolveArgument(
			methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.get(0).getName());
	assertEquals("Robert", result.get(1).getName());
}
 
Example 3
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 4
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 5
Source File: HandlerMethodResolverWrapper.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private Function<ResolvedMethod, List<ResolvedMethodParameter>> toParameters(final HandlerMethod methodToResolve) {
    return new Function<ResolvedMethod, List<ResolvedMethodParameter>>() {
        @Override
        public List<ResolvedMethodParameter> apply(ResolvedMethod input) {
            List<ResolvedMethodParameter> parameters = newArrayList();
            MethodParameter[] methodParameters = methodToResolve.getMethodParameters();
            for (int i = 0; i < methodParameters.length; i++) {
                methodParameters[i] = interfaceMethodParameter(methodParameters[i]);
            }
            for (int i = 0; i < input.getArgumentCount(); i++) {
                parameters.add(
                    new ResolvedMethodParameter(discoveredName(methodParameters[i]).or(String.format("param%s", i)),
                        methodParameters[i], input.getArgumentType(i)));
            }
            return parameters;
        }
    };
}
 
Example 6
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-11225
public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	HttpMessageConverter<Object> target = new MappingJackson2HttpMessageConverter();
	HttpMessageConverter<?> proxy = ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
	converters.add(proxy);
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example 7
Source File: AbstractParameterSnippet.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
@Override
protected FieldDescriptors createFieldDescriptors(Operation operation,
        HandlerMethod handlerMethod) {
    JavadocReader javadocReader = getJavadocReader(operation);
    SnippetTranslationResolver translationResolver = getTranslationResolver(operation);
    ConstraintReader constraintReader = getConstraintReader(operation);

    FieldDescriptors fieldDescriptors = new FieldDescriptors();
    for (MethodParameter param : handlerMethod.getMethodParameters()) {
        A annot = getAnnotation(param);
        if (annot != null) {
            addFieldDescriptor(handlerMethod, javadocReader, constraintReader, fieldDescriptors,
                    param, annot);
        }
    }

    if (shouldFailOnUndocumentedParams()) {
        assertAllDocumented(fieldDescriptors.values(), translationResolver.translate(getHeaderKey(operation)).toLowerCase());
    }

    return fieldDescriptors;
}
 
Example 8
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note 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 9
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_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 MappingJackson2XmlHttpMessageConverter());

	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 10
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

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

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

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

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

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example 11
Source File: ModelFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find {@code @ModelAttribute} arguments also listed as {@code @SessionAttributes}.
 */
private List<String> findSessionAttributeArguments(HandlerMethod handlerMethod) {
	List<String> result = new ArrayList<String>();
	for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
		if (parameter.hasParameterAnnotation(ModelAttribute.class)) {
			String name = getNameForParameter(parameter);
			Class<?> paramType = parameter.getParameterType();
			if (this.sessionAttributesHandler.isHandlerSessionAttribute(name, paramType)) {
				result.add(name);
			}
		}
	}
	return result;
}
 
Example 12
Source File: JacksonModelAttributeSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
@Override
protected Type getType(HandlerMethod method) {
    for (MethodParameter param : method.getMethodParameters()) {
        if (isModelAttribute(param) || isProcessedAsModelAttribute(param)) {
            return getType(param);
        }
    }
    return null;
}
 
Example 13
Source File: WebUtil.java    From api-document with GNU General Public License v3.0 5 votes vote down vote up
private static boolean hasRequestBody(HandlerMethod handlerMethod) {
    for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
        RequestBody body = parameter.getParameterAnnotation(RequestBody.class);
        if (Tools.isNotBlank(body)) {
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: DataRestRequestBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build parameters.
 *
 * @param domainType the domain type
 * @param openAPI the open api
 * @param handlerMethod the handler method
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param resourceMetadata the resource metadata
 */
public void buildParameters(Class<?> domainType, OpenAPI openAPI, HandlerMethod handlerMethod, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, ResourceMetadata resourceMetadata) {
	String[] pNames = this.localSpringDocParameterNameDiscoverer.getParameterNames(handlerMethod.getMethod());
	MethodParameter[] parameters = handlerMethod.getMethodParameters();
	if (!resourceMetadata.isPagingResource()) {
		Optional<MethodParameter> methodParameterPage = Arrays.stream(parameters).filter(methodParameter -> DefaultedPageable.class.equals(methodParameter.getParameterType())).findFirst();
		if (methodParameterPage.isPresent())
			parameters = ArrayUtils.removeElement(parameters, methodParameterPage.get());
	}
	String[] reflectionParametersNames = Arrays.stream(handlerMethod.getMethod().getParameters()).map(java.lang.reflect.Parameter::getName).toArray(String[]::new);
	if (pNames == null || Arrays.stream(pNames).anyMatch(Objects::isNull))
		pNames = reflectionParametersNames;
	buildCommonParameters(domainType, openAPI, requestMethod, methodAttributes, operation, pNames, parameters);
}
 
Example 15
Source File: HandlerMethodUtil.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
public static boolean isPageRequest(HandlerMethod method) {
    for (MethodParameter param : method.getMethodParameters()) {
        if (isPageable(param)) {
            return true;
        }
    }
    return false;
}
 
Example 16
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-9964
public void parameterizedMethodArgument() throws Exception {
	Method method = AbstractParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new ConcreteParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];
	SimpleBean simpleBean = resolveValue(methodParam, "{\"name\" : \"Jad\"}");

	assertEquals("Jad", simpleBean.getName());
}
 
Example 17
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Find {@code @ModelAttribute} arguments also listed as {@code @SessionAttributes}.
 */
private List<String> findSessionAttributeArguments(HandlerMethod handlerMethod) {
	List<String> result = new ArrayList<String>();
	for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
		if (parameter.hasParameterAnnotation(ModelAttribute.class)) {
			String name = getNameForParameter(parameter);
			if (this.sessionAttributesHandler.isHandlerSessionAttribute(name, parameter.getParameterType())) {
				result.add(name);
			}
		}
	}
	return result;
}
 
Example 18
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

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

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

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

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

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example 19
Source File: MessageReaderArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-9964
public void parameterizedMethodArgument() throws Exception {
	Method method = AbstractParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new ConcreteParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];
	SimpleBean simpleBean = resolveValue(methodParam, "{\"name\" : \"Jad\"}");

	assertEquals("Jad", simpleBean.getName());
}
 
Example 20
Source File: PathParametersSnippetTest.java    From spring-auto-restdocs with Apache License 2.0 4 votes vote down vote up
private void initParameters(HandlerMethod handlerMethod) {
    for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
        parameter.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
    }
}