类org.springframework.core.MethodParameter源码实例Demo

下面列出了怎么用org.springframework.core.MethodParameter的API类实例代码及写法,或者点击链接到github查看源代码。

@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>"));
}
 
@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());
}
 
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;
}
 
源代码4 项目: lams   文件: ListenableFutureReturnValueHandler.java
@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);
		}
	});
}
 
@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);
}
 
源代码6 项目: mPass   文件: RequestBodyArgumentResolver.java
@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;
}
 
@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());
}
 
源代码8 项目: sinavi-jfw   文件: PostBackManager.java
/**
 * <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();
        }
    }
}
 
@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);
		}
	});
}
 
源代码10 项目: cuba   文件: CubaDefaultListableBeanFactory.java
@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);
}
 
@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);
}
 
@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);
}
 
源代码13 项目: lams   文件: CompositeUriComponentsContributor.java
@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;
			}
		}
	}
}
 
/**
 * 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;
}
 
@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));
}
 
@Override
public String beforeBodyWrite(String body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return body + "-TargetedControllerAdvice";
}
 
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;
}
 
@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));
}
 
@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");
}
 
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;
}
 
@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;
	}
}
 
@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);
}
 
/**
 * 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;
		}
	}
}
 
源代码24 项目: java-technology-stack   文件: ModelFactory.java
public ModelMethod(InvocableHandlerMethod handlerMethod) {
	this.handlerMethod = handlerMethod;
	for (MethodParameter parameter : handlerMethod.getMethodParameters()) {
		if (parameter.hasParameterAnnotation(ModelAttribute.class)) {
			this.dependencies.add(getNameForParameter(parameter));
		}
	}
}
 
源代码25 项目: lams   文件: MethodArgumentTypeMismatchException.java
public MethodArgumentTypeMismatchException(Object value, Class<?> requiredType,
		String name, MethodParameter param, Throwable cause) {

	super(value, requiredType, cause);
	this.name = name;
	this.parameter = param;
}
 
源代码26 项目: nakadi   文件: SubscriptionControllerTest.java
@Override
public Object resolveArgument(final MethodParameter parameter,
                              final ModelAndViewContainer mavContainer,
                              final NativeWebRequest webRequest,
                              final WebDataBinderFactory binderFactory) {
    return new NakadiClient("nakadiClientId", "");
}
 
@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;
}
 
@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());
}
 
@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;
}
 
@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);
}
 
 类所在包
 同包方法