@Override
  public Object resolveArgument(MethodParameter param, NativeWebRequest request) throws Exception {

    if (request.getNativeRequest() instanceof ClientDataRequest
        && param.hasParameterAnnotation(PortletRequestBody.class)) {
      String value = param.getParameterAnnotation(PortletRequestBody.class).value();
      ClientDataRequest clientDataRequest = request.getNativeRequest(ClientDataRequest.class);
      if (!PortletRequestBody.DEFAULT.equals(value)) {
        if (isMethod(clientDataRequest, RequestMethod.POST)) {
          String json =
              JSON_MAPPER.readTree(getRequestBody(clientDataRequest)).get(value).toString();
          return JSON_MAPPER.readValue(json, param.getParameterType());
        } else if (isMethod(clientDataRequest, RequestMethod.GET)) {
          return JSON_MAPPER.readValue(request.getParameter(value), param.getParameterType());
        }
        throw new RuntimeException(
            MessageFormat.format(
                "REST Method {0} for values not supported.", clientDataRequest.getMethod()));
      }
      if (isMethod(clientDataRequest, RequestMethod.POST)) {
        return JSON_MAPPER.readValue(clientDataRequest.getReader(), param.getParameterType());
      }
      throw new RuntimeException(
          MessageFormat.format(
              "REST Method {0} for body not supported.", clientDataRequest.getMethod()));
    }
    return WebArgumentResolver.UNRESOLVED;
  }
 /**
  * Resolve the argument from the model or if not found instantiate it with its default if it is
  * available. The model attribute is then populated with request values via data binding and
  * optionally validated if {@code @java.validation.Valid} is present on the argument.
  *
  * @throws org.springframework.validation.BindException if data binding and validation result in
  *     an error and the next method parameter is not of type {@link
  *     org.springframework.validation.Errors}.
  * @throws Exception if WebDataBinder initialization fails.
  */
 public final Object resolveArgument(
     MethodParameter parameter,
     ModelAndViewContainer mavContainer,
     NativeWebRequest request,
     WebDataBinderFactory binderFactory)
     throws Exception {
   String name = parameter.getParameterAnnotation(FormModel.class).value();
   Object target =
       (mavContainer.containsAttribute(name))
           ? mavContainer.getModel().get(name)
           : createAttribute(name, parameter, binderFactory, request);
   WebDataBinder binder = binderFactory.createBinder(request, target, name);
   target = binder.getTarget();
   if (target != null) {
     bindRequestParameters(mavContainer, binderFactory, binder, request, parameter);
     validateIfApplicable(binder, parameter);
     if (binder.getBindingResult().hasErrors()) {
       if (isBindExceptionRequired(binder, parameter)) {
         throw new BindException(binder.getBindingResult());
       }
     }
   }
   target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType());
   mavContainer.addAttribute(name, target);
   return target;
 }
 public Object resolveArgument(
     MethodParameter parameter,
     ModelAndViewContainer mavContainer,
     NativeWebRequest webRequest,
     WebDataBinderFactory binderFactory)
     throws Exception {
   RequestAttribute attr = parameter.getParameterAnnotation(RequestAttribute.class);
   return webRequest.getAttribute(attr.value(), WebRequest.SCOPE_REQUEST);
 }
 @Override
 public boolean supportsParameter(MethodParameter parameter) {
   if (!parameter.hasParameterAnnotation(PathVariable.class)) {
     return false;
   }
   if (Map.class.isAssignableFrom(parameter.getParameterType())) {
     String paramName = parameter.getParameterAnnotation(PathVariable.class).value();
     return StringUtils.hasText(paramName);
   }
   return true;
 }
 /**
  * Creates action input parameter.
  *
  * @param methodParameter to describe
  * @param value used during sample invocation
  * @param conversionService to apply to value
  */
 public ActionInputParameter(
     MethodParameter methodParameter, Object value, ConversionService conversionService) {
   this.methodParameter = methodParameter;
   this.value = value;
   this.requestBody = methodParameter.getParameterAnnotation(RequestBody.class);
   this.requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
   this.pathVariable = methodParameter.getParameterAnnotation(PathVariable.class);
   this.requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
   // always determine input constraints,
   // might be a nested property which is neither requestBody, requestParam nor pathVariable
   this.inputAnnotation = methodParameter.getParameterAnnotation(Input.class);
   if (inputAnnotation != null) {
     putInputConstraint(Input.MIN, Integer.MIN_VALUE, inputAnnotation.min());
     putInputConstraint(Input.MAX, Integer.MAX_VALUE, inputAnnotation.max());
     putInputConstraint(Input.MIN_LENGTH, Integer.MIN_VALUE, inputAnnotation.minLength());
     putInputConstraint(Input.MAX_LENGTH, Integer.MAX_VALUE, inputAnnotation.maxLength());
     putInputConstraint(Input.STEP, 0, inputAnnotation.step());
     putInputConstraint(Input.PATTERN, "", inputAnnotation.pattern());
   }
   this.conversionService = conversionService;
   this.typeDescriptor = TypeDescriptor.nested(methodParameter, 0);
 }
 private String getPartName(MethodParameter parameter) {
   RequestPart annot = parameter.getParameterAnnotation(RequestPart.class);
   String partName = (annot != null ? annot.value() : "");
   if (partName.length() == 0) {
     partName = parameter.getParameterName();
     Assert.notNull(
         partName,
         "Request part name for argument type ["
             + parameter.getParameterType().getName()
             + "] not specified, and parameter name information not found in class file either.");
   }
   return partName;
 }
  @Override
  public Object resolveArgument(
      final MethodParameter methodParameter, final NativeWebRequest nativeWebRequest)
      throws Exception {
    final GreetingParam greetingParam = methodParameter.getParameterAnnotation(GreetingParam.class);

    if (greetingParam != null) {
      if (nativeWebRequest.getNativeRequest() instanceof ServletRequest) {
        final ServletRequest request = (ServletRequest) nativeWebRequest.getNativeRequest();
        return request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
      }
    }
    return UNRESOLVED;
  }
 /**
  * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
  *
  * @param annotationClass the class of the {@link Annotation} to find on the {@link
  *     MethodParameter}
  * @param parameter the {@link MethodParameter} to search for an {@link Annotation}
  * @return the {@link Annotation} that was found or null.
  */
 private <T extends Annotation> T findMethodAnnotation(
     Class<T> annotationClass, MethodParameter parameter) {
   T annotation = parameter.getParameterAnnotation(annotationClass);
   if (annotation != null) {
     return annotation;
   }
   Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
   for (Annotation toSearch : annotationsToSearch) {
     annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
     if (annotation != null) {
       return annotation;
     }
   }
   return null;
 }
  private Object[] getPossibleValues(
      MethodParameter methodParameter, AnnotatedParameters actionDescriptor) {
    try {
      Class<?> parameterType = methodParameter.getNestedParameterType();
      Object[] possibleValues;
      Class<?> nested;
      if (Enum[].class.isAssignableFrom(parameterType)) {
        possibleValues = parameterType.getComponentType().getEnumConstants();
      } else if (Enum.class.isAssignableFrom(parameterType)) {
        possibleValues = parameterType.getEnumConstants();
      } else if (Collection.class.isAssignableFrom(parameterType)
          && Enum.class.isAssignableFrom(
              nested = TypeDescriptor.nested(methodParameter, 1).getType())) {
        possibleValues = nested.getEnumConstants();
      } else {
        Select select = methodParameter.getParameterAnnotation(Select.class);
        if (select != null) {
          Class<? extends Options> optionsClass = select.options();
          Options options = optionsClass.newInstance();
          // collect call values to pass to options.get
          List<Object> from = new ArrayList<Object>();
          for (String paramName : select.args()) {
            AnnotatedParameter parameterValue = actionDescriptor.getAnnotatedParameter(paramName);
            if (parameterValue != null) {
              from.add(parameterValue.getCallValue());
            }
          }

          Object[] args = from.toArray();
          possibleValues = options.get(select.value(), args);
        } else {
          possibleValues = new Object[0];
        }
      }
      return possibleValues;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  public void contributeMethodArgument(
      MethodParameter parameter,
      Object value,
      UriComponentsBuilder builder,
      Map<String, Object> uriVariables,
      ConversionService conversionService) {

    if (Map.class.isAssignableFrom(parameter.getParameterType())) {
      return;
    }

    PathVariable annot = parameter.getParameterAnnotation(PathVariable.class);
    String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value();

    if (conversionService != null) {
      value =
          conversionService.convert(value, new TypeDescriptor(parameter), STRING_TYPE_DESCRIPTOR);
    }

    uriVariables.put(name, value);
  }
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest,
      WebDataBinderFactory binderFactory)
      throws Exception {

    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    NoodleRequestParam requestParam = parameter.getParameterAnnotation(NoodleRequestParam.class);

    String input = request.getParameter(requestParam.name());
    if (input != null && !input.isEmpty()) {
      if (logger.isDebugEnabled()) {
        logger.debug("resolveArgument -> input string -> " + input);
      }
      if (requestParam.type().equals("json")) {
        return JSON.parseObject(input, parameter.getParameterType());
      } else if (requestParam.type().equals("date")) {
        String param = request.getParameter(parameter.getParameterName());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(param);
        return date;
      }
    } else {
      if (logger.isDebugEnabled()) {
        logger.debug("resolveArgument -> input string -> null");
      }
      Class<?> parameterType = parameter.getParameterType();
      if (parameterType.getConstructors().length > 0) {
        return parameterType.newInstance();
      } else {
        String className = parameterType.getCanonicalName();
        Class<?> T = Class.forName(className.substring(0, className.length() - 2));
        return (Object[]) Array.newInstance(T, (int) 0);
      }
    }

    return null;
  }
 public boolean supportsParameter(MethodParameter methodParameter) {
   return methodParameter.getParameterAnnotation(CurrentUser.class) != null
       && methodParameter.getParameterType().equals(User.class);
 }
 @Override
 protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
   Value annotation = parameter.getParameterAnnotation(Value.class);
   return new ExpressionValueNamedValueInfo(annotation);
 }
  @Override
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest request,
      WebDataBinderFactory binderFactory)
      throws Exception {

    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    assertIsMultipartRequest(servletRequest);

    MultipartHttpServletRequest multipartRequest =
        WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

    String partName = getPartName(parameter);
    Object arg;

    if (MultipartFile.class.equals(parameter.getParameterType())) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      arg = multipartRequest.getFile(partName);
    } else if (isMultipartFileCollection(parameter)) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      arg = multipartRequest.getFiles(partName);
    } else if (isMultipartFileArray(parameter)) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      List<MultipartFile> files = multipartRequest.getFiles(partName);
      arg = files.toArray(new MultipartFile[files.size()]);
    } else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName())) {
      assertIsMultipartRequest(servletRequest);
      arg = servletRequest.getPart(partName);
    } else if (isPartCollection(parameter)) {
      assertIsMultipartRequest(servletRequest);
      arg = new ArrayList<Object>(servletRequest.getParts());
    } else if (isPartArray(parameter)) {
      assertIsMultipartRequest(servletRequest);
      arg = RequestPartResolver.resolvePart(servletRequest);
    } else {
      try {
        HttpInputMessage inputMessage =
            new RequestPartServletServerHttpRequest(servletRequest, partName);
        arg = readWithMessageConverters(inputMessage, parameter, parameter.getParameterType());
        WebDataBinder binder = binderFactory.createBinder(request, arg, partName);
        if (arg != null) {
          validate(binder, parameter);
        }
        mavContainer.addAttribute(
            BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult());
      } catch (MissingServletRequestPartException ex) {
        // handled below
        arg = null;
      }
    }

    RequestPart annot = parameter.getParameterAnnotation(RequestPart.class);
    boolean isRequired = (annot == null || annot.required());

    if (arg == null && isRequired) {
      throw new MissingServletRequestPartException(partName);
    }

    return arg;
  }
Пример #15
0
 public <T extends Annotation> T getAnnotation(Class<T> annotation) {
   return methodParameter.getParameterAnnotation(annotation);
 }
 public boolean supportsParameter(MethodParameter parameter) {
   return parameter.getParameterAnnotation(RequestAttribute.class) != null;
 }
 public boolean supportsParameter(MethodParameter parameter) {
   return parameter.getParameterAnnotation(NoodleRequestParam.class) != null;
 }
 @Override
 protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
   PathVariable annotation = parameter.getParameterAnnotation(PathVariable.class);
   return new PathVariableNamedValueInfo(annotation);
 }
 @Override
 public boolean supportsParameter(MethodParameter parameter) {
   return parameter.getParameterAnnotation(AuthUser.class) != null
       && parameter.getParameterType().equals(UserVo.class);
 }
 private ServletRequest prepareServletRequest(
     Object target, NativeWebRequest request, MethodParameter parameter) {
   String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
   HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
   MultipartRequest multipartRequest =
       WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
   MockHttpServletRequest mockRequest = null;
   if (multipartRequest != null) {
     MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
     for (MultipartFile file : multipartRequest.getFileMap().values()) {
       mockMultipartRequest.addFile(
           new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file));
     }
     mockRequest = mockMultipartRequest;
   } else {
     mockRequest = new MockHttpServletRequest();
   }
   for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
     String parameterName = entry.getKey();
     String value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
     Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
     String parameterName = entry.getKey();
     String[] value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   return mockRequest;
 }