Exemplo n.º 1
0
 /**
  * Determine if a given {@link FacesWrapperFactory} is suitable by resolving generic arguments.
  *
  * @param factory the factory to test
  * @return <tt>true</tt> if the <tt>factory</tt> is supported, otherwise <tt>false</tt>
  */
 @SuppressWarnings({"rawtypes", "unchecked"})
 private boolean isFactorySupported(FacesWrapperFactory factory) {
   Class typeArg =
       GenericTypeResolver.resolveTypeArgument(factory.getClass(), FacesWrapperFactory.class);
   if (typeArg == null) {
     Class targetClass = AopUtils.getTargetClass(factory);
     if (targetClass != factory.getClass()) {
       typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, FacesWrapperFactory.class);
     }
   }
   return (typeArg == null || typeArg.isAssignableFrom(this.typeClass));
 }
 @SuppressWarnings("unchecked")
 private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
     String className, ConfigurableApplicationContext wac) {
   try {
     Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
     Class<?> initializerContextClass =
         GenericTypeResolver.resolveTypeArgument(
             initializerClass, ApplicationContextInitializer.class);
     if (initializerContextClass != null) {
       Assert.isAssignable(
           initializerContextClass,
           wac.getClass(),
           String.format(
               "Could not add context initializer [%s] since its generic parameter [%s] "
                   + "is not assignable from the type of application context used by this "
                   + "framework servlet [%s]: ",
               initializerClass.getName(),
               initializerContextClass.getName(),
               wac.getClass().getName()));
     }
     return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
   } catch (Exception ex) {
     throw new IllegalArgumentException(
         String.format(
             "Could not instantiate class [%s] specified "
                 + "via 'contextInitializerClasses' init-param",
             className),
         ex);
   }
 }
  public final Object invokeHandlerMethod(
      Method handlerMethod,
      Object handler,
      NativeWebRequest webRequest,
      ExtendedModelMap implicitModel)
      throws Exception {

    Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
    try {
      boolean debug = logger.isDebugEnabled();
      for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
        Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName);
        if (attrValue != null) {
          implicitModel.addAttribute(attrName, attrValue);
        }
      }
      for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) {
        Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod);
        Object[] args =
            resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel);
        if (debug) {
          logger.debug("Invoking model attribute method: " + attributeMethodToInvoke);
        }
        String attrName =
            AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value();
        if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) {
          continue;
        }
        ReflectionUtils.makeAccessible(attributeMethodToInvoke);
        Object attrValue = attributeMethodToInvoke.invoke(handler, args);
        if ("".equals(attrName)) {
          Class<?> resolvedType =
              GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass());
          attrName =
              Conventions.getVariableNameForReturnType(
                  attributeMethodToInvoke, resolvedType, attrValue);
        }
        if (!implicitModel.containsAttribute(attrName)) {
          implicitModel.addAttribute(attrName, attrValue);
        }
      }
      Object[] args =
          resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
      if (debug) {
        logger.debug("Invoking request handler method: " + handlerMethodToInvoke);
      }
      ReflectionUtils.makeAccessible(handlerMethodToInvoke);
      return handlerMethodToInvoke.invoke(handler, args);
    } catch (IllegalStateException ex) {
      // Internal assertion failed (e.g. invalid signature):
      // throw exception with full handler method context...
      throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex);
    } catch (InvocationTargetException ex) {
      // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception...
      ReflectionUtils.rethrowException(ex.getTargetException());
      return null;
    }
  }
 private List<ConnectInterceptor<?>> interceptingConnectionsTo(
     ConnectionFactory<?> connectionFactory) {
   Class<?> serviceType =
       GenericTypeResolver.resolveTypeArgument(
           connectionFactory.getClass(), ConnectionFactory.class);
   List<ConnectInterceptor<?>> typedInterceptors = connectInterceptors.get(serviceType);
   if (typedInterceptors == null) {
     typedInterceptors = Collections.emptyList();
   }
   return typedInterceptors;
 }
Exemplo n.º 5
0
 @SuppressWarnings("unchecked")
 private void initApiProxy() {
   Class<?> apiType =
       GenericTypeResolver.resolveTypeArgument(serviceProvider.getClass(), ServiceProvider.class);
   if (apiType.isInterface()) {
     apiProxy =
         (A)
             Proxy.newProxyInstance(
                 apiType.getClassLoader(), new Class[] {apiType}, new ApiInvocationHandler());
   }
 }
Exemplo n.º 6
0
  protected final void addReturnValueAsModelAttribute(
      Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel) {

    ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class);
    String attrName = (attr != null ? attr.value() : "");
    if ("".equals(attrName)) {
      Class resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType);
      attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue);
    }
    implicitModel.addAttribute(attrName, returnValue);
  }
  /** Resolve the prepared arguments stored in the given bean definition. */
  private Object[] resolvePreparedArguments(
      String beanName,
      RootBeanDefinition mbd,
      BeanWrapper bw,
      Member methodOrCtor,
      Object[] argsToResolve) {

    Class<?>[] paramTypes =
        (methodOrCtor instanceof Method
            ? ((Method) methodOrCtor).getParameterTypes()
            : ((Constructor<?>) methodOrCtor).getParameterTypes());
    TypeConverter converter =
        (this.beanFactory.getCustomTypeConverter() != null
            ? this.beanFactory.getCustomTypeConverter()
            : bw);
    BeanDefinitionValueResolver valueResolver =
        new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
      Object argValue = argsToResolve[argIndex];
      MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
      GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
      if (argValue instanceof AutowiredArgumentMarker) {
        argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
      } else if (argValue instanceof BeanMetadataElement) {
        argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
      } else if (argValue instanceof String) {
        argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
      }
      Class<?> paramType = paramTypes[argIndex];
      try {
        resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
      } catch (TypeMismatchException ex) {
        String methodType =
            (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
        throw new UnsatisfiedDependencyException(
            mbd.getResourceDescription(),
            beanName,
            argIndex,
            paramType,
            "Could not convert "
                + methodType
                + " argument value of type ["
                + ObjectUtils.nullSafeClassName(argValue)
                + "] to required type ["
                + paramType.getName()
                + "]: "
                + ex.getMessage());
      }
    }
    return resolvedArgs;
  }
Exemplo n.º 8
0
  public final Object invokeHandlerMethod(
      Method handlerMethod,
      Object handler,
      NativeWebRequest webRequest,
      ExtendedModelMap implicitModel)
      throws Exception {

    Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
    try {
      boolean debug = logger.isDebugEnabled();
      for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
        Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName);
        if (attrValue != null) {
          implicitModel.addAttribute(attrName, attrValue);
        }
      }
      for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) {
        Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod);
        Object[] args =
            resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel);
        if (debug) {
          logger.debug("Invoking model attribute method: " + attributeMethodToInvoke);
        }
        String attrName =
            AnnotationUtils.findAnnotation(attributeMethodToInvoke, ModelAttribute.class).value();
        if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) {
          continue;
        }
        Object attrValue = doInvokeMethod(attributeMethodToInvoke, handler, args);
        if ("".equals(attrName)) {
          Class resolvedType =
              GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass());
          attrName =
              Conventions.getVariableNameForReturnType(
                  attributeMethodToInvoke, resolvedType, attrValue);
        }
        if (!implicitModel.containsAttribute(attrName)) {
          implicitModel.addAttribute(attrName, attrValue);
        }
      }
      Object[] args =
          resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
      if (debug) {
        logger.debug("Invoking request handler method: " + handlerMethodToInvoke);
      }
      return doInvokeMethod(handlerMethodToInvoke, handler, args);
    } catch (IllegalStateException ex) {
      // Throw exception with full handler method context...
      throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex);
    }
  }
  private Mono<Object[]> resolveArguments(
      ServerWebExchange exchange, BindingContext bindingContext, Object... providedArgs) {

    if (ObjectUtils.isEmpty(getMethodParameters())) {
      return NO_ARGS;
    }
    try {
      List<Mono<Object>> monos =
          Stream.of(getMethodParameters())
              .map(
                  param -> {
                    param.initParameterNameDiscovery(this.parameterNameDiscoverer);
                    GenericTypeResolver.resolveParameterType(param, getBean().getClass());
                    if (!ObjectUtils.isEmpty(providedArgs)) {
                      for (Object providedArg : providedArgs) {
                        if (param.getParameterType().isInstance(providedArg)) {
                          return Mono.just(providedArg).log("reactor.resolved");
                        }
                      }
                    }
                    HandlerMethodArgumentResolver resolver =
                        this.resolvers
                            .stream()
                            .filter(r -> r.supportsParameter(param))
                            .findFirst()
                            .orElseThrow(() -> getArgError("No resolver for ", param, null));
                    try {
                      return resolver
                          .resolveArgument(param, bindingContext, exchange)
                          .defaultIfEmpty(NO_VALUE)
                          .doOnError(
                              cause -> {
                                if (logger.isDebugEnabled()) {
                                  logger.debug(
                                      getDetailedErrorMessage("Error resolving ", param), cause);
                                }
                              })
                          .log("reactor.unresolved");
                    } catch (Exception ex) {
                      throw getArgError("Error resolving ", param, ex);
                    }
                  })
              .collect(Collectors.toList());

      // Create Mono with array of resolved values...
      return Mono.when(monos, args -> Stream.of(args).map(o -> o != NO_VALUE ? o : null).toArray());
    } catch (Throwable ex) {
      return Mono.error(ex);
    }
  }
 @SuppressWarnings("unchecked")
 public AbstractMethodAnnotationPostProcessor(ConfigurableListableBeanFactory beanFactory) {
   Assert.notNull(beanFactory, "'beanFactory' must not be null");
   this.messageHandlerAttributes.add(SEND_TIMEOUT_ATTRIBUTE);
   this.beanFactory = beanFactory;
   ConversionService conversionService = this.beanFactory.getConversionService();
   if (conversionService != null) {
     this.conversionService = conversionService;
   } else {
     this.conversionService = DefaultConversionService.getSharedInstance();
   }
   this.channelResolver = new BeanFactoryChannelResolver(beanFactory);
   this.annotationType =
       (Class<T>)
           GenericTypeResolver.resolveTypeArgument(
               this.getClass(), MethodAnnotationPostProcessor.class);
 }
Exemplo n.º 11
0
  /**
   * Creates {@link TypeInformation} for the given {@link Type}.
   *
   * @param fieldType the field type
   * @return the type information
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  protected TypeInformation<?> createInfo(Type fieldType) {

    if (fieldType.equals(this.type)) {
      return this;
    }

    if (fieldType instanceof Class) {
      return new ClassTypeInformation((Class<?>) fieldType);
    }

    Map<TypeVariable, Type> variableMap =
        GenericTypeResolver.getTypeVariableMap(resolveType(fieldType));

    if (fieldType instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) fieldType;
      return new ParameterizedTypeInformation(parameterizedType, this);
    }

    if (fieldType instanceof TypeVariable) {
      TypeVariable<?> variable = (TypeVariable<?>) fieldType;
      return new TypeVariableTypeInformation(variable, type, this, variableMap);
    }

    if (fieldType instanceof GenericArrayType) {
      return new GenericArrayTypeInformation((GenericArrayType) fieldType, this);
    }

    if (fieldType instanceof WildcardType) {

      WildcardType wildcardType = (WildcardType) fieldType;
      Type[] bounds = wildcardType.getLowerBounds();

      if (bounds.length > 0) {
        return createInfo(bounds[0]);
      }

      bounds = wildcardType.getUpperBounds();

      if (bounds.length > 0) {
        return createInfo(bounds[0]);
      }
    }

    throw new IllegalArgumentException();
  }
 public ImmutableRepositoryDescriptor(
     Class<R> repositoryType,
     Map<K, E> data,
     Map<MethodDescriptor, DataOperation<E, K>> operations,
     String keyProperty,
     KeyGeneration keyGeneration) {
   this.repositoryType = repositoryType;
   this.data = data == null ? new HashMap<K, E>() : new HashMap<K, E>(data);
   this.operations =
       operations == null
           ? new HashMap<MethodDescriptor, DataOperation<E, K>>()
           : new HashMap<MethodDescriptor, DataOperation<E, K>>(operations);
   this.keyProperty = keyProperty;
   this.keyGeneration = keyGeneration;
   final Class<?>[] typeArguments =
       GenericTypeResolver.resolveTypeArguments(repositoryType, Repository.class);
   //noinspection unchecked
   entityType = (Class<E>) typeArguments[0];
   //noinspection unchecked
   keyType = (Class<K>) typeArguments[1];
 }
  @Override
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void afterPropertiesSet() {
    // code borrowed from AbstractAuthorizeTag
    ApplicationContext appContext =
        WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    Map<String, SecurityExpressionHandler> handlers =
        appContext.getBeansOfType(SecurityExpressionHandler.class);

    for (SecurityExpressionHandler h : handlers.values()) {
      if (FilterInvocation.class.equals(
          GenericTypeResolver.resolveTypeArgument(h.getClass(), SecurityExpressionHandler.class))) {
        handler = h;
        break;
      }
    }

    if (handler == null) {
      throw new IllegalStateException(
          "No visible WebSecurityExpressionHandler instance "
              + "could be found in the application context");
    }
    super.afterPropertiesSet();
  }
Exemplo n.º 14
0
  /**
   * Resolves the given type into a plain {@link Class}.
   *
   * @param type the type
   * @return the class
   */
  @SuppressWarnings("unchecked")
  protected Class<S> resolveType(Type type) {

    return (Class<S>) GenericTypeResolver.resolveType(type, getTypeVariableMap());
  }
Exemplo n.º 15
0
  private Object[] resolveInitBinderArguments(
      Object handler, Method initBinderMethod, WebDataBinder binder, NativeWebRequest webRequest)
      throws Exception {

    Class[] initBinderParams = initBinderMethod.getParameterTypes();
    Object[] initBinderArgs = new Object[initBinderParams.length];

    for (int i = 0; i < initBinderArgs.length; i++) {
      MethodParameter methodParam = new MethodParameter(initBinderMethod, i);
      methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
      GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
      String paramName = null;
      boolean paramRequired = false;
      String paramDefaultValue = null;
      String pathVarName = null;
      Annotation[] paramAnns = methodParam.getParameterAnnotations();

      for (Annotation paramAnn : paramAnns) {
        if (RequestParam.class.isInstance(paramAnn)) {
          RequestParam requestParam = (RequestParam) paramAnn;
          paramName = requestParam.value();
          paramRequired = requestParam.required();
          paramDefaultValue = requestParam.defaultValue();
          break;
        } else if (ModelAttribute.class.isInstance(paramAnn)) {
          throw new IllegalStateException(
              "@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod);
        } else if (PathVariable.class.isInstance(paramAnn)) {
          PathVariable pathVar = (PathVariable) paramAnn;
          pathVarName = pathVar.value();
        }
      }

      if (paramName == null && pathVarName == null) {
        Object argValue = resolveCommonArgument(methodParam, webRequest);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
          initBinderArgs[i] = argValue;
        } else {
          Class paramType = initBinderParams[i];
          if (paramType.isInstance(binder)) {
            initBinderArgs[i] = binder;
          } else if (BeanUtils.isSimpleProperty(paramType)) {
            paramName = "";
          } else {
            throw new IllegalStateException(
                "Unsupported argument ["
                    + paramType.getName()
                    + "] for @InitBinder method: "
                    + initBinderMethod);
          }
        }
      }

      if (paramName != null) {
        initBinderArgs[i] =
            resolveRequestParam(
                paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
      } else if (pathVarName != null) {
        initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null);
      }
    }

    return initBinderArgs;
  }
Exemplo n.º 16
0
  @SuppressWarnings("unchecked")
  private Object[] resolveHandlerArguments(
      Method handlerMethod,
      Object handler,
      NativeWebRequest webRequest,
      ExtendedModelMap implicitModel)
      throws Exception {

    Class[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];

    for (int i = 0; i < args.length; i++) {
      MethodParameter methodParam = new MethodParameter(handlerMethod, i);
      methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
      GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
      String paramName = null;
      String headerName = null;
      boolean requestBodyFound = false;
      String cookieName = null;
      String pathVarName = null;
      String attrName = null;
      boolean required = false;
      String defaultValue = null;
      boolean validate = false;
      int found = 0;
      Annotation[] paramAnns = methodParam.getParameterAnnotations();

      for (Annotation paramAnn : paramAnns) {
        if (RequestParam.class.isInstance(paramAnn)) {
          RequestParam requestParam = (RequestParam) paramAnn;
          paramName = requestParam.value();
          required = requestParam.required();
          defaultValue = requestParam.defaultValue();
          found++;
        } else if (RequestHeader.class.isInstance(paramAnn)) {
          RequestHeader requestHeader = (RequestHeader) paramAnn;
          headerName = requestHeader.value();
          required = requestHeader.required();
          defaultValue = requestHeader.defaultValue();
          found++;
        } else if (RequestBody.class.isInstance(paramAnn)) {
          requestBodyFound = true;
          found++;
        } else if (CookieValue.class.isInstance(paramAnn)) {
          CookieValue cookieValue = (CookieValue) paramAnn;
          cookieName = cookieValue.value();
          required = cookieValue.required();
          defaultValue = cookieValue.defaultValue();
          found++;
        } else if (PathVariable.class.isInstance(paramAnn)) {
          PathVariable pathVar = (PathVariable) paramAnn;
          pathVarName = pathVar.value();
          found++;
        } else if (ModelAttribute.class.isInstance(paramAnn)) {
          ModelAttribute attr = (ModelAttribute) paramAnn;
          attrName = attr.value();
          found++;
        } else if (Value.class.isInstance(paramAnn)) {
          defaultValue = ((Value) paramAnn).value();
        } else if ("Valid".equals(paramAnn.annotationType().getSimpleName())) {
          validate = true;
        }
      }

      if (found > 1) {
        throw new IllegalStateException(
            "Handler parameter annotations are exclusive choices - "
                + "do not specify more than one such annotation on the same parameter: "
                + handlerMethod);
      }

      if (found == 0) {
        Object argValue = resolveCommonArgument(methodParam, webRequest);
        if (argValue != WebArgumentResolver.UNRESOLVED) {
          args[i] = argValue;
        } else if (defaultValue != null) {
          args[i] = resolveDefaultValue(defaultValue);
        } else {
          Class paramType = methodParam.getParameterType();
          if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {
            args[i] = implicitModel;
          } else if (SessionStatus.class.isAssignableFrom(paramType)) {
            args[i] = this.sessionStatus;
          } else if (Errors.class.isAssignableFrom(paramType)) {
            throw new IllegalStateException(
                "Errors/BindingResult argument declared "
                    + "without preceding model attribute. Check your handler method signature!");
          } else if (BeanUtils.isSimpleProperty(paramType)) {
            paramName = "";
          } else {
            attrName = "";
          }
        }
      }

      if (paramName != null) {
        args[i] =
            resolveRequestParam(
                paramName, required, defaultValue, methodParam, webRequest, handler);
      } else if (headerName != null) {
        args[i] =
            resolveRequestHeader(
                headerName, required, defaultValue, methodParam, webRequest, handler);
      } else if (requestBodyFound) {
        args[i] = resolveRequestBody(methodParam, webRequest, handler);
      } else if (cookieName != null) {
        args[i] =
            resolveCookieValue(
                cookieName, required, defaultValue, methodParam, webRequest, handler);
      } else if (pathVarName != null) {
        args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
      } else if (attrName != null) {
        WebDataBinder binder =
            resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);
        boolean assignBindingResult =
            (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));
        if (binder.getTarget() != null) {
          doBind(binder, webRequest, validate, !assignBindingResult);
        }
        args[i] = binder.getTarget();
        if (assignBindingResult) {
          args[i + 1] = binder.getBindingResult();
          i++;
        }
        implicitModel.putAll(binder.getBindingResult().getModel());
      }
    }

    return args;
  }
Exemplo n.º 17
0
 /**
  * Gets the type argument.
  *
  * @param type the type
  * @param bound the bound
  * @param index the index
  * @return the type argument
  */
 private TypeInformation<?> getTypeArgument(Class<?> type, Class<?> bound, int index) {
   Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(type, bound);
   return arguments == null ? null : createInfo(arguments[index]);
 }
Exemplo n.º 18
0
  /**
   * 得到参数列表
   *
   * @param method
   * @param model
   * @param request
   * @param response
   * @param c
   * @return
   */
  @SuppressWarnings("unchecked")
  public static Object[] getArgs(
      Method method,
      Map<String, Object> model,
      HttpServletRequest request,
      HttpServletResponse response,
      Class<?> c) {
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    Map<String, String> pathValues = null;
    PathPattern pathPattern = method.getAnnotation(PathPattern.class);
    if (pathPattern != null) {
      String path = request.getRequestURI();
      int index = path.lastIndexOf('.');
      if (index != -1) {
        path = path.substring(0, index);
        String[] patterns = pathPattern.patterns();
        pathValues = getPathValues(patterns, path);
      }
    }
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer =
        new LocalVariableTableParameterNameDiscoverer();
    for (int i = 0; i < paramTypes.length; i++) {
      Class<?> paramType = paramTypes[i];

      MethodParameter methodParam = new MethodParameter(method, i);
      methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
      GenericTypeResolver.resolveParameterType(methodParam, c.getClass());

      String paramName = methodParam.getParameterName();
      // map
      if (Map.class.isAssignableFrom(paramType)) {
        args[i] = model;
      }
      // HttpServletRequest
      else if (HttpServletRequest.class.isAssignableFrom(paramType)) {
        args[i] = request;
      }
      // HttpServletResponse
      else if (HttpServletResponse.class.isAssignableFrom(paramType)) {
        args[i] = response;
      }
      // HttpSession
      else if (HttpSession.class.isAssignableFrom(paramType)) {
        args[i] = request.getSession();
      }
      // Errors
      else if (Errors.class.isAssignableFrom(paramType)) {
        args[i] = errors;
      }
      // MultipartFile
      else if (MultipartFile.class.isAssignableFrom(paramType)) {
        MultipartFile[] files = resolveMultipartFiles(request, errors, paramName);
        if (files != null && files.length > 0) {
          args[i] = files[0];
        }
      }
      // MultipartFile[]
      else if (MultipartFile[].class.isAssignableFrom(paramType)) {
        args[i] = resolveMultipartFiles(request, errors, paramName);
      } else {
        // 简单数据类型
        if (BeanUtils.isSimpleProperty(paramType)) {
          SimpleTypeConverter converter = new SimpleTypeConverter();
          Object value;
          // 是否是数组
          if (paramType.isArray()) {
            value = request.getParameterValues(paramName);
          } else {
            Object[] parameterAnnotations = methodParam.getParameterAnnotations();
            value = null;
            if (parameterAnnotations != null && parameterAnnotations.length > 0) {
              if (pathValues != null && pathValues.size() > 0) {
                for (Object object : parameterAnnotations) {
                  if (PathVariable.class.isInstance(object)) {
                    PathVariable pv = (PathVariable) object;
                    if (StringUtils.isEmpty(pv.value())) {
                      value = pathValues.get(paramName);
                    } else {
                      value = pathValues.get(pv.value());
                    }
                    break;
                  }
                }
              }
            } else {
              value = request.getParameter(paramName);
            }
          }
          try {
            args[i] = converter.convertIfNecessary(value, paramType, methodParam);
            model.put(paramName, args[i]);
          } catch (TypeMismatchException e) {
            errors.addError(new FieldError(paramName, paramName, e.getMessage()));
          }
        } else {
          // 复杂数据类型POJO类
          if (paramType.isArray()) {
            ObjectArrayDataBinder binder =
                new ObjectArrayDataBinder(paramType.getComponentType(), paramName);
            args[i] = binder.bind(request);
            model.put(paramName, args[i]);
          } else {
            Object bindObject = BeanUtils.instantiateClass(paramType);
            SummerServletRequestDataBinder binder =
                new SummerServletRequestDataBinder(bindObject, paramName);
            binder.bind(request);
            BindException be = new BindException(binder.getBindingResult());
            List<FieldError> fieldErrors = be.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
              errors.addError(fieldError);
            }
            args[i] = binder.getTarget();
            model.put(paramName, args[i]);
          }
        }
      }
    }
    return args;
  }
Exemplo n.º 19
0
  /**
   * Registers an annotation-based formatter.
   *
   * @param clazz class handled by this formatter
   * @param formatter the formatter to register
   */
  @SuppressWarnings("unchecked")
  public static <A extends Annotation, T> void register(
      final Class<T> clazz, final AnnotationFormatter<A, T> formatter) {
    final Class<? extends Annotation> annotationType =
        (Class<? extends Annotation>)
            GenericTypeResolver.resolveTypeArguments(
                formatter.getClass(), AnnotationFormatter.class)[0];

    conversion.addConverter(
        new ConditionalGenericConverter() {
          public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() {
            Set<GenericConverter.ConvertiblePair> types =
                new HashSet<GenericConverter.ConvertiblePair>();
            types.add(new GenericConverter.ConvertiblePair(clazz, String.class));
            return types;
          }

          public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
            return (sourceType.getAnnotation(annotationType) != null);
          }

          public Object convert(
              Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            final A a = (A) sourceType.getAnnotation(annotationType);
            Locale locale = LocaleContextHolder.getLocale();
            try {
              return formatter.print(a, (T) source, locale);
            } catch (Exception ex) {
              throw new ConversionFailedException(sourceType, targetType, source, ex);
            }
          }

          public String toString() {
            return "@"
                + annotationType.getName()
                + " "
                + clazz.getName()
                + " -> "
                + String.class.getName()
                + ": "
                + formatter;
          }
        });

    conversion.addConverter(
        new ConditionalGenericConverter() {
          public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() {
            Set<GenericConverter.ConvertiblePair> types =
                new HashSet<GenericConverter.ConvertiblePair>();
            types.add(new GenericConverter.ConvertiblePair(String.class, clazz));
            return types;
          }

          public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
            return (targetType.getAnnotation(annotationType) != null);
          }

          public Object convert(
              Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            final A a = (A) targetType.getAnnotation(annotationType);
            Locale locale = LocaleContextHolder.getLocale();
            try {
              return formatter.parse(a, (String) source, locale);
            } catch (Exception ex) {
              throw new ConversionFailedException(sourceType, targetType, source, ex);
            }
          }

          public String toString() {
            return String.class.getName()
                + " -> @"
                + annotationType.getName()
                + " "
                + clazz.getName()
                + ": "
                + formatter;
          }
        });
  }
 @Override
 protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
   if (checkPropertySkipping(pvs)) {
     return;
   }
   Method method = (Method) this.member;
   try {
     Object[] arguments;
     if (this.cached) {
       // Shortcut for avoiding synchronization...
       arguments = resolveCachedArguments(beanName);
     } else {
       Class<?>[] paramTypes = method.getParameterTypes();
       arguments = new Object[paramTypes.length];
       DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
       Set<String> autowiredBeanNames = new LinkedHashSet<String>(paramTypes.length);
       TypeConverter typeConverter = beanFactory.getTypeConverter();
       for (int i = 0; i < arguments.length; i++) {
         MethodParameter methodParam = new MethodParameter(method, i);
         GenericTypeResolver.resolveParameterType(methodParam, bean.getClass());
         descriptors[i] = new DependencyDescriptor(methodParam, this.required);
         arguments[i] =
             beanFactory.resolveDependency(
                 descriptors[i], beanName, autowiredBeanNames, typeConverter);
         if (arguments[i] == null && !this.required) {
           arguments = null;
           break;
         }
       }
       synchronized (this) {
         if (!this.cached) {
           if (arguments != null) {
             this.cachedMethodArguments = new Object[arguments.length];
             for (int i = 0; i < arguments.length; i++) {
               this.cachedMethodArguments[i] = descriptors[i];
             }
             registerDependentBeans(beanName, autowiredBeanNames);
             if (autowiredBeanNames.size() == paramTypes.length) {
               Iterator<String> it = autowiredBeanNames.iterator();
               for (int i = 0; i < paramTypes.length; i++) {
                 String autowiredBeanName = it.next();
                 if (beanFactory.containsBean(autowiredBeanName)) {
                   if (beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
                     this.cachedMethodArguments[i] = new RuntimeBeanReference(autowiredBeanName);
                   }
                 }
               }
             }
           } else {
             this.cachedMethodArguments = null;
           }
           this.cached = true;
         }
       }
     }
     if (arguments != null) {
       ReflectionUtils.makeAccessible(method);
       method.invoke(bean, arguments);
     }
   } catch (InvocationTargetException ex) {
     throw ex.getTargetException();
   } catch (Throwable ex) {
     throw new BeanCreationException("Could not autowire method: " + method, ex);
   }
 }