Example usage for org.springframework.core.convert TypeDescriptor TypeDescriptor

List of usage examples for org.springframework.core.convert TypeDescriptor TypeDescriptor

Introduction

In this page you can find the example usage for org.springframework.core.convert TypeDescriptor TypeDescriptor.

Prototype

public TypeDescriptor(Property property) 

Source Link

Document

Create a new type descriptor from a Property .

Usage

From source file:ch.rasc.wampspring.method.MethodParameterConverter.java

public Object convert(MethodParameter parameter, Object argument) {
    if (argument == null) {
        if (parameter.getParameterType().getName().equals("java.util.Optional")) {
            return OptionalUnwrapper.empty();
        }//from w w  w .j av a 2 s . c  o  m

        return null;
    }

    Class<?> sourceClass = argument.getClass();
    Class<?> targetClass = parameter.getParameterType();

    TypeDescriptor td = new TypeDescriptor(parameter);

    if (targetClass.isAssignableFrom(sourceClass)) {
        return convertListElements(td, argument);
    }

    if (this.conversionService.canConvert(sourceClass, targetClass)) {
        try {
            return convertListElements(td, this.conversionService.convert(argument, targetClass));
        } catch (Exception e) {

            TypeFactory typeFactory = this.objectMapper.getTypeFactory();
            if (td.isCollection()) {
                JavaType type = CollectionType.construct(td.getType(),
                        typeFactory.constructType(td.getElementTypeDescriptor().getType()));
                return this.objectMapper.convertValue(argument, type);
            } else if (td.isArray()) {
                JavaType type = typeFactory.constructArrayType(td.getElementTypeDescriptor().getType());
                return this.objectMapper.convertValue(argument, type);
            }

            throw e;
        }
    }
    return this.objectMapper.convertValue(argument, targetClass);
}

From source file:ch.ralscha.extdirectspring.util.ParameterInfo.java

public ParameterInfo(Class<?> clazz, Method method, int paramIndex) {

    MethodParameter methodParam = new MethodParameter(method, paramIndex);
    methodParam.initParameterNameDiscovery(discoverer);
    GenericTypeResolver.resolveParameterType(methodParam, clazz);

    this.name = methodParam.getParameterName();
    this.typeDescriptor = new TypeDescriptor(methodParam);

    Class<?> paramType = methodParam.getParameterType();
    javaUtilOptional = paramType.getName().equals("java.util.Optional");

    this.supportedParameter = SupportedParameters.isSupported(typeDescriptor.getObjectType());

    Annotation[] paramAnnotations = methodParam.getParameterAnnotations();

    for (Annotation paramAnn : paramAnnotations) {

        this.hasRequestParamAnnotation = false;
        this.hasMetadataParamAnnotation = false;
        this.hasRequestHeaderAnnotation = false;
        this.hasCookieValueAnnotation = false;
        this.hasAuthenticationPrincipalAnnotation = null;

        if (RequestParam.class.isInstance(paramAnn)) {
            RequestParam requestParam = (RequestParam) paramAnn;
            if (StringUtils.hasText(requestParam.value())) {
                this.name = requestParam.value();
            }/*from w ww.ja  v a 2  s . com*/
            this.required = requestParam.required();
            this.defaultValue = ValueConstants.DEFAULT_NONE.equals(requestParam.defaultValue()) ? null
                    : requestParam.defaultValue();
            this.hasRequestParamAnnotation = true;
            break;
        } else if (MetadataParam.class.isInstance(paramAnn)) {
            MetadataParam metadataParam = (MetadataParam) paramAnn;
            if (StringUtils.hasText(metadataParam.value())) {
                this.name = metadataParam.value();
            }
            this.required = metadataParam.required();
            this.defaultValue = ValueConstants.DEFAULT_NONE.equals(metadataParam.defaultValue()) ? null
                    : metadataParam.defaultValue();
            this.hasMetadataParamAnnotation = true;
            break;
        } else if (RequestHeader.class.isInstance(paramAnn)) {
            RequestHeader requestHeader = (RequestHeader) paramAnn;
            if (StringUtils.hasText(requestHeader.value())) {
                this.name = requestHeader.value();
            }
            this.required = requestHeader.required();
            this.defaultValue = ValueConstants.DEFAULT_NONE.equals(requestHeader.defaultValue()) ? null
                    : requestHeader.defaultValue();
            this.hasRequestHeaderAnnotation = true;
            break;
        } else if (CookieValue.class.isInstance(paramAnn)) {
            CookieValue cookieValue = (CookieValue) paramAnn;
            if (StringUtils.hasText(cookieValue.value())) {
                this.name = cookieValue.value();
            }
            this.required = cookieValue.required();
            this.defaultValue = ValueConstants.DEFAULT_NONE.equals(cookieValue.defaultValue()) ? null
                    : cookieValue.defaultValue();
            this.hasCookieValueAnnotation = true;
            break;
        } else if (paramAnn.annotationType().getName()
                .equals("org.springframework.security.web.bind.annotation.AuthenticationPrincipal")
                || paramAnn.annotationType().getName()
                        .equals("org.springframework.security.core.annotation.AuthenticationPrincipal")) {
            hasAuthenticationPrincipalAnnotation = (Boolean) AnnotationUtils.getValue(paramAnn,
                    "errorOnInvalidType");
        }
    }
}

From source file:org.jdal.ui.bind.DirectFieldAccessor.java

public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException {
    Field field = this.fieldMap.get(propertyName);
    if (field != null) {
        return new TypeDescriptor(field);
    }//from   w  w  w . j a  v a2 s .c o m
    return null;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the specified required type.
 * //from  w  ww.  ja v  a2  s. c o  m
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param methodParam
 *            the method parameter that is the target of the conversion (may be <code>null</code>)
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
public <T> T convertIfNecessary(Object newValue, Class<T> requiredType, MethodParameter methodParam)
        throws IllegalArgumentException {

    return convertIfNecessary(null, null, newValue, requiredType,
            (methodParam != null ? new TypeDescriptor(methodParam) : TypeDescriptor.valueOf(requiredType)));
}

From source file:org.gvnix.web.json.ConversionServiceBeanSerializerModifier.java

@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
        List<BeanPropertyWriter> beanProperties) {

    // We need the BeanPropertyDefinition to get the related Field
    List<BeanPropertyDefinition> properties = beanDesc.findProperties();
    Map<String, BeanPropertyDefinition> propertyDefMap = new HashMap<String, BeanPropertyDefinition>();
    for (BeanPropertyDefinition property : properties) {
        propertyDefMap.put(property.getName(), property);
    }/* ww w. j ava  2s .c  o  m*/

    // iterate over bean's properties to configure serializers
    for (int i = 0; i < beanProperties.size(); i++) {
        BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
        Class<?> propertyType = beanPropertyWriter.getPropertyType();

        if (beanPropertyWriter.hasSerializer()) {
            continue;
        }

        // For conversion between collection, array, and map types,
        // ConversionService.canConvert() method will return 'true'
        // but better to delegate in default Jackson property writer for
        // right start and ends markers serialization and iteration
        if (propertyType.isArray() || Collection.class.isAssignableFrom(propertyType)
                || Map.class.isAssignableFrom(propertyType)) {

            // Don't set ConversionService serializer, let Jackson
            // use default Collection serializer
            continue;
        } else if (BindingResult.class.isAssignableFrom(propertyType)) {
            // Use BindingResultSerializer
            beanPropertyWriter.assignSerializer(bindingResultSerializer);
        } else {

            // ConversionService uses value Class plus related Field
            // annotations to be able to select the right converter,
            // so we must get/ the Field annotations for success
            // formatting
            BeanPropertyDefinition propertyDef = propertyDefMap.get(beanPropertyWriter.getName());
            AnnotatedField annotatedField = propertyDef.getField();
            if (annotatedField == null) {
                continue;
            }
            AnnotatedElement annotatedEl = annotatedField.getAnnotated();

            // Field contains info about Annotations, info that
            // ConversionService uses for success formatting, use it if
            // available. Otherwise use the class of given value.
            TypeDescriptor sourceType = annotatedEl != null ? new TypeDescriptor((Field) annotatedEl)
                    : TypeDescriptor.valueOf(propertyType);

            TypeDescriptor targetType = TypeDescriptor.valueOf(String.class);
            if (beanPropertyWriter.getSerializationType() != null) {
                targetType = TypeDescriptor.valueOf(beanPropertyWriter.getSerializationType().getRawClass());
            }
            if (ObjectUtils.equals(sourceType, targetType)) {
                // No conversion needed
                continue;
            } else if (sourceType.getObjectType() == Object.class && targetType.getObjectType() == String.class
                    && beanPropertyWriter.getSerializationType() == null) {
                // Can't determine source type and no target type has been
                // configure. Delegate on jackson.
                continue;
            }

            // All other converters must be set in ConversionService
            if (this.conversionService.canConvert(sourceType, targetType)) {

                // We must create BeanPropertyWriter own Serializer that
                // has knowledge about the Field related to that
                // BeanPropertyWriter in order to have access to
                // Field Annotations for success serialization
                JsonSerializer<Object> jsonSerializer = new ConversionServicePropertySerializer(
                        this.conversionService, sourceType, targetType);

                beanPropertyWriter.assignSerializer(jsonSerializer);
            }
            // If no converter set, use default Jackson property writer
            else {
                continue;
            }
        }
    }
    return beanProperties;
}

From source file:com.drillmap.crm.repository.extensions.invoker.ReflectionRepositoryInvoker.java

private Object[] prepareParameters(Method method, Map<String, String[]> rawParameters, Pageable pageable,
        Sort sort) {/* w ww  .j  av  a 2 s. com*/

    List<MethodParameter> parameters = new MethodParameters(method, PARAM_ANNOTATION).getParameters();

    if (parameters.isEmpty()) {
        return new Object[0];
    }

    Object[] result = new Object[parameters.size()];
    Sort sortToUse = pageable == null ? sort : pageable.getSort();

    for (int i = 0; i < result.length; i++) {

        MethodParameter param = parameters.get(i);
        Class<?> targetType = param.getParameterType();

        if (Pageable.class.isAssignableFrom(targetType)) {
            result[i] = pageable;
        } else if (Sort.class.isAssignableFrom(targetType)) {
            result[i] = sortToUse;
        } else {

            String parameterName = param.getParameterName();

            if (!StringUtils.hasText(parameterName)) {
                throw new IllegalArgumentException("No @Param annotation found on query method "
                        + method.getName() + " for parameter " + parameterName);
            }

            String[] parameterValue = rawParameters.get(parameterName);
            Object value = parameterValue == null ? null
                    : parameterValue.length == 1 ? parameterValue[0] : parameterValue;

            result[i] = conversionService.convert(value, TypeDescriptor.forObject(value),
                    new TypeDescriptor(param));
        }
    }

    return result;
}

From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java

/**
 * Create a model attribute from a String request value (e.g. URI template variable, request parameter) using type
 * conversion./*from  ww  w.j  ava 2  s  .c o  m*/
 * <p>
 * The default implementation converts only if there a registered
 * {@link org.springframework.core.convert.converter.Converter} that can perform the conversion.
 * 
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute, never {@code null}
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null}
 * @throws Exception
 */
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
        MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
        throws Exception {
    DataBinder binder = binderFactory.createBinder(request, null, attributeName);
    ConversionService conversionService = binder.getConversionService();
    if (conversionService != null) {
        TypeDescriptor source = TypeDescriptor.valueOf(String.class);
        TypeDescriptor target = new TypeDescriptor(parameter);
        if (conversionService.canConvert(source, target)) {
            return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
        }
    }
    return null;
}

From source file:com.p5solutions.core.json.JsonDeserializer.java

/**
 * Sets the value. May also use the {@link ConversionService} to convert
 * types, such as {@link Date} using the {@link DateTimeFormat}. @see
 * /*from   w  ww  .  j a v  a  2s  .c o  m*/
 * @param method
 *          the method
 * @param fieldName
 *          the field name
 * @param target
 *          the target
 * @param value
 *          the value
 * @param binder
 *          the binder {@link ConversionService} and implementation of custom
 *          converters by implementing {@link GenericConverter}
 * @throws Exception
 */
protected void setValue(Method method, String fieldName, Object target, Object value, WebRequest webRequest,
        WebDataBinder binder) {

    // Expose the real method, if proxied, since annotations need to be found.
    Method realMethod = method;
    if (target instanceof Targetable) {
        Targetable proxy = (Targetable) target;
        Class<?> clazz = proxy.getTarget().getClass();

        realMethod = ReflectionUtility.findMethod(clazz, realMethod.getName());
    }
    // TODO expose TrackStateUtility as part of Core??
    // Method realMethod = TrackStateUtility.exposeRealMethod(method, target);

    if (realMethod == null && method == null) {
        // if there are any binding, or formatting issues, put an error
        // in the model state.

        Object tempState = webRequest.getAttribute(ModelState.MODEL_STATE, WebRequest.SCOPE_REQUEST);
        if (tempState == null) {
            tempState = new ModelState();
        }
        ModelState modelState = (ModelState) tempState;
        modelState.add(fieldName,
                "Cannot bind value " + value + " to target object "
                        + (target != null ? target.getClass() : "<null>"),
                new RuntimeException(
                        "Field " + fieldName + " does not exist for " + target.getClass().getName()));
        webRequest.setAttribute(ModelState.MODEL_STATE, modelState, WebRequest.SCOPE_REQUEST);
    }
    // get the nullable property annotation, if any
    JsonNotNullProperty jnullpt = ReflectionUtility.findAnnotation(realMethod, JsonNotNullProperty.class);

    // get the json property, if any
    JsonProperty jpt = ReflectionUtility.findAnnotation(realMethod, JsonProperty.class);

    Class<?> returnType = method.getReturnType();
    if (ReflectionUtility.isNumberClass(returnType)) {

        try {
            Object numeric = NumberUtils.valueOf(value.toString(), returnType);
            ReflectionUtility.setValue(fieldName, target, numeric);
        } catch (NumberFormatException nfe) {
            // if there are any binding, or formatting issues, put an error
            // in the model state.

            Object tempState = webRequest.getAttribute(ModelState.MODEL_STATE, WebRequest.SCOPE_REQUEST);
            if (tempState == null) {
                tempState = new ModelState();
            }
            ModelState modelState = (ModelState) tempState;
            modelState.add(fieldName, "Cannot bind value " + value + " to target object "
                    + (target != null ? target.getClass() : "<null>"), nfe);
            webRequest.setAttribute(ModelState.MODEL_STATE, modelState, WebRequest.SCOPE_REQUEST);
        }

    } else if (ReflectionUtility.isStringClass(returnType)) {

        // set empty values to null
        String sv = (String) value;
        sv = Comparison.isEmpty(sv) ? null : sv;

        // if the Nullable property is et with emptyNull to false
        // then actually set the value, even if its empty.
        if (jnullpt != null) {
            sv = (String) value;
        }

        // unescape the sting character.
        sv = unescape(sv);
        sv = unnull(sv);

        ReflectionUtility.setValue(fieldName, target, sv);
    } else if (!attemptListMapping(fieldName, target, value, returnType, jpt, webRequest, binder)) {

        // / attempt to map of Map<?,?>
        if (!attemptMapMapping(fieldName, target, value, returnType, jpt, webRequest, binder)) {

            // attempt to simple map the object
            if (!attemptSimpleMapping(fieldName, target, value, returnType, webRequest, binder)) {

                // Use the Spring Conversion service and try to map the
                // values
                TypeDescriptor sourceType = TypeDescriptor.forObject(value);

                // specify the method, -1 such that it uses the return value
                // type
                MethodParameter mp = new MethodParameter(realMethod, -1);

                // setup the type descriptor and pass it to the converter
                TypeDescriptor targetType = new TypeDescriptor(mp);

                // PropertyValue pv = new PropertyValue(fieldName, value);

                Object converted = null;
                PropertyEditor editor = null;
                if (binder != null) {
                    editor = binder.findCustomEditor(returnType, null);
                }

                if (editor != null) {
                    editor.setAsText(value.toString());
                    converted = editor.getValue();
                } else if (conversionService != null) {
                    // use the conversion service to translate the value
                    converted = this.conversionService.convert(value, sourceType, targetType);
                }

                // set the converted value, if any
                ReflectionUtility.setValue(fieldName, target, converted);
            }
        }
    }
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@Override
public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException {
    try {/*from w  ww  .  j ava2 s  .  c  om*/
        ExtendedBeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName);
        String finalPath = getFinalPath(nestedBw, propertyName);
        PropertyTokenHolder tokens = getPropertyNameTokens(finalPath);
        PropertyDescriptor pd = nestedBw.getCachedIntrospectionResults()
                .getPropertyDescriptor(tokens.actualName);
        if (pd != null) {
            if (tokens.keys != null) {
                if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
                    return TypeDescriptor.nested(property(pd), tokens.keys.length);
                }
            } else {
                if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
                    return new TypeDescriptor(property(pd));
                }
            }
        }
    } catch (InvalidPropertyException ex) {
        // Consider as not determinable.
    }
    return null;
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

/**
 * Convert the given value for the specified property to the latter's type.
 * <p>/*from   w  ww .  j  a  v a 2 s.co  m*/
 * This method is only intended for optimizations in a BeanFactory. Use the {@code convertIfNecessary} methods for programmatic conversion.
 * 
 * @param value
 *            the value to convert
 * @param propertyName
 *            the target property (note that nested or indexed properties are not supported here)
 * @return the new value, possibly the result of type conversion
 * @throws TypeMismatchException
 *             if type conversion failed
 */
public Object convertForProperty(Object value, String propertyName) throws TypeMismatchException {
    CachedIntrospectionResults cachedIntrospectionResults = getCachedIntrospectionResults();
    PropertyDescriptor pd = cachedIntrospectionResults.getPropertyDescriptor(propertyName);
    if (pd == null) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "No property '" + propertyName + "' found");
    }
    TypeDescriptor td = cachedIntrospectionResults.getTypeDescriptor(pd);
    if (td == null) {
        td = cachedIntrospectionResults.addTypeDescriptor(pd, new TypeDescriptor(property(pd)));
    }
    return convertForProperty(propertyName, null, value, td);
}