Example usage for org.springframework.web.bind WebDataBinder convertIfNecessary

List of usage examples for org.springframework.web.bind WebDataBinder convertIfNecessary

Introduction

In this page you can find the example usage for org.springframework.web.bind WebDataBinder convertIfNecessary.

Prototype

@Override
    @Nullable
    public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType,
            @Nullable MethodParameter methodParam) throws TypeMismatchException 

Source Link

Usage

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

@SuppressWarnings("unchecked")
private Object resolveRequestParam(String paramName, boolean required, String defaultValue,
        MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
        throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (Map.class.isAssignableFrom(paramType) && paramName.length() == 0) {
        return resolveRequestParamMap((Class<? extends Map>) paramType, webRequest);
    }//  w  ww.j  a v a 2s  . c  om
    if (paramName.length() == 0) {
        paramName = getRequiredParameterName(methodParam);
    }
    Object paramValue = null;
    MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class);
    if (multipartRequest != null) {
        List<MultipartFile> files = multipartRequest.getFiles(paramName);
        if (!files.isEmpty()) {
            if (files.size() == 1 && !paramType.isArray() && !Collection.class.isAssignableFrom(paramType)) {
                paramValue = files.get(0);
            } else {
                paramValue = files;
            }
        }
    }
    if (paramValue == null) {
        String[] paramValues = webRequest.getParameterValues(paramName);
        if (paramValues != null) {
            if (paramValues.length == 1 && !paramType.isArray()
                    && !Collection.class.isAssignableFrom(paramType)) {
                paramValue = paramValues[0];
            } else {
                paramValue = paramValues;
            }
        }
    }
    if (paramValue == null) {
        if (defaultValue != null) {
            paramValue = resolveDefaultValue(defaultValue);
        } else if (required) {
            raiseMissingParameterException(paramName, paramType);
        }
        paramValue = checkValue(paramName, paramValue, paramType);
    }
    WebDataBinder binder = createBinder(webRequest, null, paramName);
    initBinder(handlerForInitBinderCall, paramName, binder, webRequest);
    return binder.convertIfNecessary(paramValue, paramType, methodParam);
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

@SuppressWarnings("unchecked")
private Object resolveRequestHeader(String headerName, boolean required, String defaultValue,
        MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
        throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (Map.class.isAssignableFrom(paramType)) {
        return resolveRequestHeaderMap((Class<? extends Map>) paramType, webRequest);
    }//  ww  w. ja  v a2 s  .  c  om
    if (headerName.length() == 0) {
        headerName = getRequiredParameterName(methodParam);
    }
    Object headerValue = null;
    String[] headerValues = webRequest.getHeaderValues(headerName);
    if (headerValues != null) {
        headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues);
    }
    if (headerValue == null) {
        if (defaultValue != null) {
            headerValue = resolveDefaultValue(defaultValue);
        } else if (required) {
            raiseMissingHeaderException(headerName, paramType);
        }
        headerValue = checkValue(headerName, headerValue, paramType);
    }
    WebDataBinder binder = createBinder(webRequest, null, headerName);
    initBinder(handlerForInitBinderCall, headerName, binder, webRequest);
    return binder.convertIfNecessary(headerValue, paramType, methodParam);
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

private Object resolveCookieValue(String cookieName, boolean required, String defaultValue,
        MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
        throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (cookieName.length() == 0) {
        cookieName = getRequiredParameterName(methodParam);
    }// w  w  w  .ja  va 2s . c  om
    Object cookieValue = resolveCookieValue(cookieName, paramType, webRequest);
    if (cookieValue == null) {
        if (defaultValue != null) {
            cookieValue = resolveDefaultValue(defaultValue);
        } else if (required) {
            raiseMissingCookieException(cookieName, paramType);
        }
        cookieValue = checkValue(cookieName, cookieValue, paramType);
    }
    WebDataBinder binder = createBinder(webRequest, null, cookieName);
    initBinder(handlerForInitBinderCall, cookieName, binder, webRequest);
    return binder.convertIfNecessary(cookieValue, paramType, methodParam);
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

private Object resolvePathVariable(String pathVarName, MethodParameter methodParam, NativeWebRequest webRequest,
        Object handlerForInitBinderCall) throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (pathVarName.length() == 0) {
        pathVarName = getRequiredParameterName(methodParam);
    }/*from w w w .  j  a  v  a  2s . c o m*/
    String pathVarValue = resolvePathVariable(pathVarName, paramType, webRequest);
    WebDataBinder binder = createBinder(webRequest, null, pathVarName);
    initBinder(handlerForInitBinderCall, pathVarName, binder, webRequest);
    return binder.convertIfNecessary(pathVarValue, paramType, methodParam);
}

From source file:org.springframework.faces.mvc.annotation.support.AnnotatedMethodInvoker.java

/**
 * Resolve a single request parameter//from ww w.  ja v a 2  s  .  c  o m
 * @param paramName The parameter name or an empty string if the name should be taken from the <tt>methodParam</tt>
 * @param paramRequired <tt>true</tt> if the parameter is required or <tt>false</tt> if the parameter is optional
 * @param methodParam The method parameter
 * @param webRequest The web request
 * @param handlerForInitBinderCall The handler for use with init binder (can be <tt>null</tt>)
 * @return The resolved request parameter
 * @throws Exception on error
 */
private Object resolveRequestParam(String paramName, boolean paramRequired, MethodParameter methodParam,
        NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception {
    Class paramType = methodParam.getParameterType();
    if ("".equals(paramName)) {
        paramName = methodParam.getParameterName();
        if (paramName == null) {
            throw new IllegalStateException("No parameter specified for @RequestParam argument of type ["
                    + paramType.getName() + "], and no parameter name information found in class file either.");
        }
    }
    Object paramValue = null;
    if (webRequest.getNativeRequest() instanceof MultipartRequest) {
        paramValue = ((MultipartRequest) webRequest.getNativeRequest()).getFile(paramName);
    }
    if (paramValue == null) {
        String[] paramValues = webRequest.getParameterValues(paramName);
        if (paramValues != null) {
            paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues);
        }
    }
    if (paramValue == null) {
        if (paramRequired) {
            raiseMissingParameterException(paramName, paramType);
        }
        if (paramType.isPrimitive()) {
            throw new IllegalStateException("Optional " + paramType + " parameter '" + paramName
                    + "' is not present but cannot be translated into "
                    + "a null value due to being declared as a "
                    + "primitive type. Consider declaring it as object wrapper for the corresponding primitive type.");
        }
    }
    WebDataBinder binder = createBinder(webRequest, null, paramName);
    initBinder(handlerForInitBinderCall, paramName, binder, webRequest);
    return binder.convertIfNecessary(paramValue, paramType, methodParam);
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

@SuppressWarnings("unchecked")
private Object resolveRequestParam(String paramName, boolean required, String defaultValue,
        MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
        throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (Map.class.isAssignableFrom(paramType) && paramName.length() == 0) {
        return resolveRequestParamMap((Class<? extends Map<?, ?>>) paramType, webRequest);
    }/*  ww  w .  j  av a2 s  .  c o  m*/
    if (paramName.length() == 0) {
        paramName = getRequiredParameterName(methodParam);
    }
    Object paramValue = null;
    MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class);
    if (multipartRequest != null) {
        List<MultipartFile> files = multipartRequest.getFiles(paramName);
        if (!files.isEmpty()) {
            paramValue = (files.size() == 1 ? files.get(0) : files);
        }
    }
    if (paramValue == null) {
        String[] paramValues = webRequest.getParameterValues(paramName);
        if (paramValues != null) {
            paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues);
        }
    }
    if (paramValue == null) {
        if (defaultValue != null) {
            paramValue = resolveDefaultValue(defaultValue);
        } else if (required) {
            raiseMissingParameterException(paramName, paramType);
        }
        paramValue = checkValue(paramName, paramValue, paramType);
    }
    WebDataBinder binder = createBinder(webRequest, null, paramName);
    initBinder(handlerForInitBinderCall, paramName, binder, webRequest);
    return binder.convertIfNecessary(paramValue, paramType, methodParam);
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

@SuppressWarnings("unchecked")
private Object resolveRequestHeader(String headerName, boolean required, String defaultValue,
        MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
        throws Exception {

    Class<?> paramType = methodParam.getParameterType();
    if (Map.class.isAssignableFrom(paramType)) {
        return resolveRequestHeaderMap((Class<? extends Map<?, ?>>) paramType, webRequest);
    }/*from w  ww. j  a v  a2  s  .  c o m*/
    if (headerName.length() == 0) {
        headerName = getRequiredParameterName(methodParam);
    }
    Object headerValue = null;
    String[] headerValues = webRequest.getHeaderValues(headerName);
    if (headerValues != null) {
        headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues);
    }
    if (headerValue == null) {
        if (defaultValue != null) {
            headerValue = resolveDefaultValue(defaultValue);
        } else if (required) {
            raiseMissingHeaderException(headerName, paramType);
        }
        headerValue = checkValue(headerName, headerValue, paramType);
    }
    WebDataBinder binder = createBinder(webRequest, null, headerName);
    initBinder(handlerForInitBinderCall, headerName, binder, webRequest);
    return binder.convertIfNecessary(headerValue, paramType, methodParam);
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * 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 BindException if data binding and validation result in an error
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 *///from  w w w. jav a2  s  .  c  o m
@Override
@Nullable
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

    Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
    Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");

    String name = ModelFactory.getNameForParameter(parameter);
    ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
    if (ann != null) {
        mavContainer.setBinding(name, ann.binding());
    }

    Object attribute = null;
    BindingResult bindingResult = null;

    if (mavContainer.containsAttribute(name)) {
        attribute = mavContainer.getModel().get(name);
    } else {
        // Create attribute instance
        try {
            attribute = createAttribute(name, parameter, binderFactory, webRequest);
        } catch (BindException ex) {
            if (isBindExceptionRequired(parameter)) {
                // No BindingResult parameter -> fail with BindException
                throw ex;
            }
            // Otherwise, expose null/empty value and associated BindingResult
            if (parameter.getParameterType() == Optional.class) {
                attribute = Optional.empty();
            }
            bindingResult = ex.getBindingResult();
        }
    }

    if (bindingResult == null) {
        // Bean property binding and validation;
        // skipped in case of binding failure on construction.
        WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
        if (binder.getTarget() != null) {
            if (!mavContainer.isBindingDisabled(name)) {
                bindRequestParameters(binder, webRequest);
            }
            validateIfApplicable(binder, parameter);
            if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
        // Value type adaptation, also covering java.util.Optional
        if (!parameter.getParameterType().isInstance(attribute)) {
            attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
        }
        bindingResult = binder.getBindingResult();
    }

    // Add resolved attribute and BindingResult at the end of the model
    Map<String, Object> bindingResultModel = bindingResult.getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return attribute;
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * Construct a new attribute instance with the given constructor.
 * <p>Called from/*w  w  w. j av a2s  .com*/
 * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)}
 * after constructor resolution.
 * @param ctor the constructor to use
 * @param attributeName the name of the attribute (never {@code null})
 * @param binderFactory for creating WebDataBinder instance
 * @param webRequest the current request
 * @return the created model attribute (never {@code null})
 * @throws BindException in case of constructor argument binding failure
 * @throws Exception in case of constructor invocation failure
 * @since 5.0
 */
protected Object constructAttribute(Constructor<?> ctor, String attributeName,
        WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

    if (ctor.getParameterCount() == 0) {
        // A single default constructor -> clearly a standard JavaBeans arrangement.
        return BeanUtils.instantiateClass(ctor);
    }

    // A single data class constructor -> resolve constructor arguments from request parameters.
    ConstructorProperties cp = ctor.getAnnotation(ConstructorProperties.class);
    String[] paramNames = (cp != null ? cp.value() : parameterNameDiscoverer.getParameterNames(ctor));
    Assert.state(paramNames != null, () -> "Cannot resolve parameter names for constructor " + ctor);
    Class<?>[] paramTypes = ctor.getParameterTypes();
    Assert.state(paramNames.length == paramTypes.length,
            () -> "Invalid number of parameter names: " + paramNames.length + " for constructor " + ctor);

    Object[] args = new Object[paramTypes.length];
    WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName);
    String fieldDefaultPrefix = binder.getFieldDefaultPrefix();
    String fieldMarkerPrefix = binder.getFieldMarkerPrefix();
    boolean bindingFailure = false;

    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        Class<?> paramType = paramTypes[i];
        Object value = webRequest.getParameterValues(paramName);
        if (value == null) {
            if (fieldDefaultPrefix != null) {
                value = webRequest.getParameter(fieldDefaultPrefix + paramName);
            }
            if (value == null && fieldMarkerPrefix != null) {
                if (webRequest.getParameter(fieldMarkerPrefix + paramName) != null) {
                    value = binder.getEmptyValue(paramType);
                }
            }
        }
        try {
            MethodParameter methodParam = new MethodParameter(ctor, i);
            if (value == null && methodParam.isOptional()) {
                args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null);
            } else {
                args[i] = binder.convertIfNecessary(value, paramType, methodParam);
            }
        } catch (TypeMismatchException ex) {
            ex.initPropertyName(paramName);
            binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult());
            bindingFailure = true;
            args[i] = value;
        }
    }

    if (bindingFailure) {
        if (binder.getBindingResult() instanceof AbstractBindingResult) {
            AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult();
            for (int i = 0; i < paramNames.length; i++) {
                result.recordFieldValue(paramNames[i], paramTypes[i], args[i]);
            }
        }
        throw new BindException(binder.getBindingResult());
    }

    return BeanUtils.instantiateClass(ctor, args);
}