/** * Invoked only if the converter type is {@code FastJsonpHttpMessageConverter4}. */ public void beforeBodyWriteInternal(MappingFastJsonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); for (String name : this.jsonpQueryParamNames) { String value = servletRequest.getParameter(name); if (value != null) { if (!isValidJsonpQueryParam(value)) { continue; } // MediaType contentTypeToUse = getContentType(contentType, request, response); // response.getHeaders().setContentType(contentTypeToUse); bodyContainer.setJsonpFunction(value); break; } } }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String nonceBase64 = getNonceOrThrow(webRequest); String nonceSignatureBase64 = getNonceSignatureOrThrow(webRequest); if (!isBase64(nonceBase64)) { throw new BadRequestException("Nonce must be base64"); } if (!isBase64(nonceSignatureBase64)) { throw new BadRequestException("Nonce signature must be base64"); } return NonceAuthenticationImpl.builder() .nonceBase64(nonceBase64) .nonceSignatureBase64(nonceSignatureBase64) .build(); }
@Override protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request) throws Exception { HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); if (MultipartResolutionDelegate.isMultipartArgument(parameter)) { if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) { throw new MultipartException("Current request is not a multipart request"); } else { throw new MissingServletRequestPartException(name); } } else { throw new MissingServletRequestParameterException(name, parameter.getNestedParameterType().getSimpleName()); } }
protected AdminUser getAccessUser(HttpServletRequest request, LoggingContext loggingContext) { if(loggingContext.getHttpAccessLogging().isLogin()){ //用户正在登录 HandlerMethod handlerMethod = loggingContext.getHandlerMethod(); MethodParameter[] methodParameters = handlerMethod.getMethodParameters(); if(methodParameters != null){ for(MethodParameter methodParameter : methodParameters){ if(methodParameter.hasParameterAnnotation(RequestBody.class) && AdminUser.class.equals(methodParameter.getParameterType())){ HttpRequestParameter requestParameter = loggingContext.getHttpAccessLog().getRequestParameter(); Object requestBody = requestParameter.getBody(); MediaType contentType = loggingContext.getHttpAccessLog().getRequestContentType(); if (contentType != null && requestBody != null && requestBody instanceof Map && MediaType.APPLICATION_JSON.getType().equals(contentType.getType())) { Map<String,Object> requestBodyMap = (Map<String, Object>) requestBody; return adminUserService.getUserByUserName(MapUtils.getString(requestBodyMap, "userName"), false); } } } } return null; }else{ //用户已登录 LoginToken<AdminUser> loginToken = (LoginToken<AdminUser>) ShiroUtils.getSessionAttribute(LoginToken.LOGIN_TOKEN_SESSION_KEY); return loginToken == null ? null : loginToken.getLoginUser(); } }
@Override public synchronized Class<?> getPropertyType() { if (this.propertyType == null) { if (this.readMethod != null) { this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass); } else { MethodParameter writeMethodParam = getWriteMethodParameter(); if (writeMethodParam != null) { this.propertyType = writeMethodParam.getParameterType(); } else { this.propertyType = super.getPropertyType(); } } } return this.propertyType; }
/** * 有WxAsyncMessage注解且 * 返回值是WxMessage的子类 * 或者是CharSequence的子类,且有注解WxButton或者WXMessageMapping * * @param returnType * @return dummy */ @Override public boolean supportsReturnType(MethodParameter returnType) { // 如果是iterable或者array,都作为asyncMessage消息处理 boolean isIterableType = Iterable.class.isAssignableFrom(returnType.getParameterType()); boolean isArrayType = returnType.getParameterType().isArray(); boolean isGroupMessage = WxGroupMessage.class.isAssignableFrom(returnType.getParameterType()); boolean isTemplateMessage = WxTemplateMessage.class.isAssignableFrom(returnType.getParameterType()); // 理论上WxAsyncMessage已经被上层处理过了,这里保险起见再处理一次 boolean needAsyncSend = isIterableType || isArrayType || isGroupMessage || isTemplateMessage; Class realType = getGenericType(returnType); boolean isWxMessage = WxMessage.class.isAssignableFrom(realType); boolean isWxStringMessage = CharSequence.class.isAssignableFrom(realType) && returnType.hasMethodAnnotation(WxMapping.class); return needAsyncSend && (isWxMessage || isWxStringMessage); }
@Test public void testToBigDecimal() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("BigDecimalParam", BigDecimal.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); assertThat(this.invocableHandlerMethod.convert(param, (byte) 1)) .isEqualTo(new BigDecimal("1")); assertThat(this.invocableHandlerMethod.convert(param, (short) 2)) .isEqualTo(new BigDecimal("2")); assertThat(this.invocableHandlerMethod.convert(param, 3)) .isEqualTo(new BigDecimal("3")); assertThat(this.invocableHandlerMethod.convert(param, 4L)) .isEqualTo(new BigDecimal("4")); assertThat(this.invocableHandlerMethod.convert(param, 5.5f)) .isEqualTo(new BigDecimal("5.5")); assertThat(this.invocableHandlerMethod.convert(param, 6.6)) .isEqualTo(new BigDecimal("6.6")); assertThat(this.invocableHandlerMethod.convert(param, new BigDecimal("3.141"))) .isEqualTo(new BigDecimal("3.141")); }
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue); Observable<?> observable = asyncResponseEntity.getObservable(); Single<?> single = asyncResponseEntity.getSingle(); MultiValueMap<String, String> headers = asyncResponseEntity.getHeaders(); HttpStatus status = asyncResponseEntity.getStatus(); if(observable != null) WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer); else if(single != null) WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer); }
/** * Determine whether the provided bean definition is an autowire candidate. * <p>To be considered a candidate the bean's <em>autowire-candidate</em> * attribute must not have been set to 'false'. Also, if an annotation on * the field or parameter to be autowired is recognized by this bean factory * as a <em>qualifier</em>, the bean must 'match' against the annotation as * well as any attributes it may contain. The bean definition must contain * the same qualifier or match by meta attributes. A "value" attribute will * fallback to match against the bean name or an alias if a qualifier or * attribute does not match. * @see Qualifier */ @Override public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { boolean match = super.isAutowireCandidate(bdHolder, descriptor); if (match && descriptor != null) { match = checkQualifiers(bdHolder, descriptor.getAnnotations()); if (match) { MethodParameter methodParam = descriptor.getMethodParameter(); if (methodParam != null) { Method method = methodParam.getMethod(); if (method == null || void.class.equals(method.getReturnType())) { match = checkQualifiers(bdHolder, methodParam.getMethodAnnotations()); } } } } return match; }
@Override public BizRes beforeBodyWrite(BizRes body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { String deviceToken = response.getHeaders().getFirst(requestHeaderProperties.getDeviceToken()); if (body instanceof ErrorRes) { ((ErrorRes) body).setVd(deviceToken); return body; } if (body instanceof SuccessRes) { ((SuccessRes) body).setVd(deviceToken); return body; } SuccessRes res = new SuccessRes(body); res.setVd(deviceToken); return res; }
@Override public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException { try { if (arguments != null) { ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition); } if (this.method.isVarArgs()) { arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.method.getParameterTypes(), arguments); } ReflectionUtils.makeAccessible(this.method); Object value = this.method.invoke(target, arguments); return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.method, -1)).narrow(value)); } catch (Exception ex) { throw new AccessException("Problem invoking method: " + this.method, ex); } }
private UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) { CompositeUriComponentsContributor contributor = defaultUriComponentsContributor; int paramCount = method.getParameterTypes().length; int argCount = args.length; if (paramCount != argCount) { throw new IllegalArgumentException("方法参数量为" + paramCount + " 与真实参数量不匹配,真实参数量为" + argCount); } final Map<String, Object> uriVars = new HashMap<>(8); for (int i = 0; i < paramCount; i++) { MethodParameter param = new SynthesizingMethodParameter(method, i); param.initParameterNameDiscovery(parameterNameDiscoverer); contributor.contributeMethodArgument(param, args[i], builder, uriVars); } // We may not have all URI var values, expand only what we have return builder.build().expand(name -> uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE); }
@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<>(); @SuppressWarnings("unchecked") ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue; Futures.addCallback(futureValue, new FutureCallback<Object>() { @Override public void onSuccess(@Nullable Object result) { deferredResult.setResult(result); } @Override public void onFailure(Throwable ex) { deferredResult.setErrorResult(ex); } }); startDeferredResultProcessing(mavContainer, webRequest, deferredResult); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void handleReturnValue( Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { return; } else if (returnValue instanceof Map){ mavContainer.addAllAttributes((Map) returnValue); } else { // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { // Bind request parameter onto object... String name = attrName; if ("".equals(name)) { name = Conventions.getVariableNameForParameter(methodParam); } Class<?> paramType = methodParam.getParameterType(); Object bindObject; if (implicitModel.containsKey(name)) { bindObject = implicitModel.get(name); } else if (this.methodResolver.isSessionAttribute(name, paramType)) { bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); if (bindObject == null) { raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); } } else { bindObject = BeanUtils.instantiateClass(paramType); } WebDataBinder binder = createBinder(webRequest, bindObject, name); initBinder(handler, name, binder, webRequest); return binder; }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { //取出存入的用户ID String currentUserId = (String) webRequest.getAttribute(Constant.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST); if (currentUserId != null) { return userDao.findById(currentUserId); } return new MissingServletRequestPartException(Constant.CURRENT_USER_ID); }
/** * Obtain the named value for the given method parameter. */ private NamedValueInfo getNamedValueInfo(MethodParameter parameter) { NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter); if (namedValueInfo == null) { namedValueInfo = createNamedValueInfo(parameter); namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo); this.namedValueInfoCache.put(parameter, namedValueInfo); } return namedValueInfo; }
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class<?> paramType) throws Exception { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName); } throw new HttpMediaTypeNotSupportedException( "Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType +"\" using [" + messageConverter + "]"); } return messageConverter.read((Class) paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
private void findPayloadParameter(){ if(this.method.getParameterCount() == 0){ throw new IllegalStateException("Service methods must have at least one receiving parameter"); } else if(this.method.getParameterCount() == 1){ this.payloadParameter = new MethodParameter(this.method, 0); } int payloadAnnotations = Flux.just(this.method.getParameters()) .filter(parameter -> parameter.getAnnotation(Payload.class) != null) .reduce(0, (a, parameter) -> { return a+1; }) .block(); if(payloadAnnotations > 1){ throw new IllegalStateException("Service methods can have at most one @Payload annotated parameters"); } for(int i=0; i<this.method.getParameters().length; i++){ Parameter p = this.method.getParameters()[i]; if(p.getAnnotation(Payload.class) != null){ this.payloadParameter = new MethodParameter(this.method, i); break; } } if(this.payloadParameter == null){ throw new IllegalStateException("Service methods annotated with more than one parameter must declare one @Payload parameter"); } resolvePayloadType(); }
@Override public boolean handles(MethodParameter parameter) { if (parameter.getParameterIndex() != -1) { throw new IllegalArgumentException( "Method parameter must be a return value."); } Class<?> type = parameter.getParameterType(); return RestResponse.class.isAssignableFrom(type) || IRecordSet.class.isAssignableFrom(type) || type.getAnnotation(XmlRootElement.class) != null || IRecordSet.class.isAssignableFrom(type) || IJSONObject.class.isAssignableFrom(type) || IJSONArray.class.isAssignableFrom(type); }
/** * Obtain a new MethodParameter object for the write method of the * specified property. * @param pd the PropertyDescriptor for the property * @return a corresponding MethodParameter object */ public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) { if (pd instanceof GenericTypeAwarePropertyDescriptor) { return new MethodParameter(((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodParameter()); } else { return new MethodParameter(pd.getWriteMethod(), 0); } }
protected Object getUser(MethodParameter parameter, WxRequest wxRequest) { // 类型不匹配直接返回 if (!wxUserProvider.isMatch(parameter.getParameterType())) { return null; } else if (WX_USER.equals(parameter.getParameterName()) || !BeanUtils.isSimpleProperty(parameter.getParameterType())) { // 两个都转换失败时,判断是否是简单属性,如果不是,则尝试转换为用户 // 因为此时无法得知是要获取to还是from,所以取对于用户来说更需要的from return wxUserProvider.getUser(wxRequest.getBody().getFromUserName()); } return null; }
@PostConstruct void init() throws NoSuchMethodException { uploadDocumentsCommandMethodParameter = new MethodParameter( StoredDocumentController.class.getMethod( "createFrom", UploadDocumentsCommand.class, BindingResult.class), 0); }
@Test public void should_throw_404_when_MethodArgumentTypeMismatchException_thrown() throws Exception { final MethodArgumentTypeMismatchException exception = new MethodArgumentTypeMismatchException(new HashMap<String, String>(), Map.class, "test", new MethodParameter(Object.class.getMethod("toString"), 1), null); final ErrorStatusCodeAndMessage errorStatusCodeAndMessage = resolver.resolveStatusCodeAndMessage(exception, "It broke", 500); assertThat(errorStatusCodeAndMessage.getStatusCode(), equalTo(404)); }
@Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { ((ResponseBodyMessage) bodyContainer.getValue()).businessMsg = "xxxxxxxxxxxxxx"; }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) throws Exception { //获取用户ID Object object = request.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY, RequestAttributes.SCOPE_REQUEST); if(object == null){ return null; } //获取用户信息 UserEntity user = userService.queryObject((Long)object); return user; }
@Override public Object handleEmptyBody ( Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class< ? extends HttpMessageConverter< ? > > converterType ) { // 如果为空,给个默认值 return new PagingRequest(); }
/** * Find a registered {@link HandlerMethodReturnValueHandler} that supports the given return type. */ private HandlerMethodReturnValueHandler getReturnValueHandler(MethodParameter returnType) { for (HandlerMethodReturnValueHandler returnValueHandler : returnValueHandlers) { if (logger.isTraceEnabled()) { logger.trace("Testing if return value handler [" + returnValueHandler + "] supports [" + returnType.getGenericParameterType() + "]"); } if (returnValueHandler.supportsReturnType(returnType)) { return returnValueHandler; } } return null; }
/** * Attempt to resolve a method parameter from the list of provided argument values. */ private Object resolveProvidedArgument(MethodParameter parameter, Object... providedArgs) { if (providedArgs == null) { return null; } for (Object providedArg : providedArgs) { if (parameter.getParameterType().isInstance(providedArg)) { return providedArg; } } return null; }
@Override public WxMessage beforeBodyWrite(WxMessage body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (!(request instanceof ServletServerHttpRequest) || body == null) { return body; } HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); WxRequest wxRequest = WxWebUtils.getWxRequestFromRequest(servletRequest); return wxMessageProcessor.process(new WxRequestMessageParameter(wxRequest), body); }
@Override public RestResponse handleReturnValue(Object returnValue, MethodParameter parameter, RestRequest request) throws Exception { Class<?> type = parameter.getParameterType(); XmlRootElement xmlRootElement = type .getAnnotation(XmlRootElement.class); if (RestResponse.class.isAssignableFrom(type)) { return (RestResponse) returnValue; } else if (String.class.isAssignableFrom(type)) { return new RestResponse(null, JSONConverter.toByteArray((String) returnValue)); } else if (xmlRootElement != null) { return new RestResponse(null, objectMapper.writeValueAsBytes(returnValue)); } else if (IRecordSet.class.isAssignableFrom(type)) { return new RestResponse(null, objectMapper.writeValueAsBytes(returnValue)); } else if (IJSONObject.class.isAssignableFrom(type)) { return new RestResponse(null, JSONConverter.toByteArray(((IJSONObject) returnValue) .toJSONString(null))); } else if (IJSONArray.class.isAssignableFrom(type)) { return new RestResponse(null, JSONConverter.toByteArray(((IJSONArray) returnValue) .toJSONString(null))); } throw new IllegalArgumentException(String.format( "Cannot handle return value: %1$s", returnValue)); }
@Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Principal user = ((WampMessage) message).getPrincipal(); if (user == null) { throw new MessageHandlingException(message, "No \"PRINCIPAL\" header in message"); } return user; }
@Before public void setup() throws Exception { Method testMethod = getClass().getDeclaredMethod("handleMessage", CallMessage.class, String.class); this.resolver = new WampMessageMethodArgumentResolver(); this.messageParameter = new MethodParameter(testMethod, 0); this.stringParameter = new MethodParameter(testMethod, 1); }
/** * Abstract method defining "autowire by type" (bean properties by type) behavior. * <p>This is like PicoContainer default, in which there must be exactly one bean * of the property type in the bean factory. This makes bean factories simple to * configure for small namespaces, but doesn't work as well as standard Spring * behavior for bigger applications. * @param beanName the name of the bean to autowire by type * @param mbd the merged bean definition to update through autowiring * @param bw BeanWrapper from which we can obtain information about the bean * @param pvs the PropertyValues to register wired objects with */ protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } Set<String> autowiredBeanNames = new LinkedHashSet<String>(4); String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. if (!Object.class.equals(pd.getPropertyType())) { MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass()); DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { registerDependentBean(autowiredBeanName, beanName); if (logger.isDebugEnabled()) { logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
private ArgumentDefinition extractSingleArgumentDefinition(MethodParameter methodParameter){ Class<?> type = methodParameter.getParameterType(); List<Annotation> argumentDescriptors = Arrays.stream(methodParameter.getParameterAnnotations()) .filter(anno -> AnnotationUtils.isAnnotationMetaPresent(anno.getClass(), JobArgument.class)) .collect(Collectors.toList()); if (argumentDescriptors.size() != 1) { throw new BadJobDefinitionException("a job argument has to be annotated with exactly one @JobArgument meta-annotated annotation"); } return new ArgumentDefinition(type, argumentDescriptors.get(0)); }
@Test public void testToString() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("stringParam", String.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); assertThat(this.invocableHandlerMethod.convert(param, "str")).isEqualTo("str"); assertThat(this.invocableHandlerMethod.convert(param, (byte) 1)).isEqualTo("1"); assertThat(this.invocableHandlerMethod.convert(param, (short) 2)).isEqualTo("2"); assertThat(this.invocableHandlerMethod.convert(param, 3)).isEqualTo("3"); assertThat(this.invocableHandlerMethod.convert(param, 4L)).isEqualTo("4"); assertThat(this.invocableHandlerMethod.convert(param, 5.5f)).isEqualTo("5.5"); assertThat(this.invocableHandlerMethod.convert(param, 6.6)).isEqualTo("6.6"); assertThat(this.invocableHandlerMethod.convert(param, new BigDecimal("3.141"))) .isEqualTo("3.141"); }
@Test public void testToint() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("intParam", Integer.TYPE); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); assertThat(this.invocableHandlerMethod.convert(param, (byte) 1)).isEqualTo(1); assertThat(this.invocableHandlerMethod.convert(param, (short) 2)).isEqualTo(2); assertThat(this.invocableHandlerMethod.convert(param, 3)).isEqualTo(3); assertThat(this.invocableHandlerMethod.convert(param, 4L)).isEqualTo(4); assertThat(this.invocableHandlerMethod.convert(param, 5.5f)).isEqualTo(5); assertThat(this.invocableHandlerMethod.convert(param, 6.6)).isEqualTo(6); assertThat(this.invocableHandlerMethod.convert(param, new BigDecimal("3.141"))) .isEqualTo(3); }
/** * Supports the following: * <ul> * <li>@RequestParam-annotated method arguments. * This excludes {@link Map} params where the annotation doesn't * specify a name. See {@link RequestParamMapMethodArgumentResolver} * instead for such params. * <li>Arguments of type {@link MultipartFile} * unless annotated with @{@link RequestPart}. * <li>Arguments of type {@code javax.servlet.http.Part} * unless annotated with @{@link RequestPart}. * <li>In default resolution mode, simple type arguments * even if not with @{@link RequestParam}. * </ul> */ @Override public boolean supportsParameter(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); if (parameter.hasParameterAnnotation(RequestParam.class)) { if (Map.class.isAssignableFrom(paramType)) { String paramName = parameter.getParameterAnnotation(RequestParam.class).value(); return StringUtils.hasText(paramName); } else { return true; } } else { if (parameter.hasParameterAnnotation(RequestPart.class)) { return false; } else if (MultipartFile.class.equals(paramType) || "javax.servlet.http.Part".equals(paramType.getName())) { return true; } else if (this.useDefaultResolution) { return BeanUtils.isSimpleProperty(paramType); } else { return false; } } }
/** * Iterate over registered {@link HandlerMethodArgumentResolver}s and invoke the one that supports it. * @exception IllegalStateException if no suitable {@link HandlerMethodArgumentResolver} is found. */ @Override public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); Assert.notNull(resolver, "Unknown parameter type [" + parameter.getParameterType().getName() + "]"); return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testToList() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("listParam", List.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); assertThat((List) this.invocableHandlerMethod.convert(param, "1")).hasSize(1) .containsExactly("1"); assertThat( (List) this.invocableHandlerMethod.convert(param, Arrays.asList(1, 2, 3))) .hasSize(3).containsExactly("1", "2", "3"); }