Search in sources :

Example 6 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project spring-framework by spring-projects.

the class CollectionToCollectionConverterTests method scalarList.

@Test
public void scalarList() throws Exception {
    List<String> list = new ArrayList<>();
    list.add("9");
    list.add("37");
    TypeDescriptor sourceType = TypeDescriptor.forObject(list);
    TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget"));
    assertTrue(conversionService.canConvert(sourceType, targetType));
    try {
        conversionService.convert(list, sourceType, targetType);
    } catch (ConversionFailedException ex) {
        assertTrue(ex.getCause() instanceof ConverterNotFoundException);
    }
    conversionService.addConverterFactory(new StringToNumberConverterFactory());
    assertTrue(conversionService.canConvert(sourceType, targetType));
    @SuppressWarnings("unchecked") List<Integer> result = (List<Integer>) conversionService.convert(list, sourceType, targetType);
    assertFalse(list.equals(result));
    assertEquals(9, result.get(0).intValue());
    assertEquals(37, result.get(1).intValue());
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 7 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project camel by apache.

the class SpringTypeConverter method convertTo.

@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }
    // do not attempt to convert List -> Map. Ognl expression may use this converter as a fallback expecting null
    if (type.isAssignableFrom(Map.class) && (value.getClass().isArray() || value instanceof Collection)) {
        return null;
    }
    TypeDescriptor sourceType = types.computeIfAbsent(value.getClass(), TypeDescriptor::valueOf);
    TypeDescriptor targetType = types.computeIfAbsent(type, TypeDescriptor::valueOf);
    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(sourceType, targetType)) {
            try {
                return (T) conversionService.convert(value, sourceType, targetType);
            } catch (ConversionFailedException e) {
                //
                if (e.getCause() instanceof ConverterNotFoundException && isArrayOrCollection(value)) {
                    return null;
                } else {
                    throw new TypeConversionException(value, type, e);
                }
            }
        }
    }
    return null;
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) TypeConversionException(org.apache.camel.TypeConversionException) ConversionService(org.springframework.core.convert.ConversionService) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Collection(java.util.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 8 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project disconf by knightliao.

the class MyExceptionHandler method getParamErrors.

/**
     * TypeMismatchException中获取到参数错误类型
     *
     * @param e
     */
private ModelAndView getParamErrors(TypeMismatchException e) {
    Throwable t = e.getCause();
    if (t instanceof ConversionFailedException) {
        ConversionFailedException x = (ConversionFailedException) t;
        TypeDescriptor type = x.getTargetType();
        Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
        Map<String, String> errors = new HashMap<String, String>();
        for (Annotation a : annotations) {
            if (a instanceof RequestParam) {
                errors.put(((RequestParam) a).value(), "parameter type error!");
            }
        }
        if (errors.size() > 0) {
            return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
        }
    }
    JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
    return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) HashMap(java.util.HashMap) JsonObjectBase(com.baidu.dsp.common.vo.JsonObjectBase) Annotation(java.lang.annotation.Annotation)

Example 9 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project cas by apereo.

the class CasConfigurationEmbeddedValueResolver method convertValueToDurationIfPossible.

private String convertValueToDurationIfPossible(final String value) {
    try {
        final ConversionService service = applicationContext.getEnvironment().getConversionService();
        final Duration dur = service.convert(value, Duration.class);
        if (dur != null) {
            return String.valueOf(dur.toMillis());
        }
    } catch (final ConversionFailedException e) {
        LOGGER.trace(e.getMessage());
    }
    return null;
}
Also used : ConversionFailedException(org.springframework.core.convert.ConversionFailedException) ConversionService(org.springframework.core.convert.ConversionService) Duration(java.time.Duration)

Example 10 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project spring-framework by spring-projects.

the class TypeConverterDelegate method convertIfNecessary.

/**
	 * Convert the value to the required type (if necessary from a String),
	 * for the specified property.
	 * @param propertyName name of the property
	 * @param oldValue the previous value, if available (may be {@code null})
	 * @param newValue the proposed new value
	 * @param requiredType the type we must convert to
	 * (or {@code null} if not known, for example in case of a collection element)
	 * @param typeDescriptor the descriptor for the target property or field
	 * @return the new value, possibly the result of type conversion
	 * @throws IllegalArgumentException if type conversion failed
	 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException {
    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);
    ConversionFailedException conversionAttemptEx = null;
    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
            try {
                return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                conversionAttemptEx = ex;
            }
        }
    }
    Object convertedValue = newValue;
    // Value not of required type?
    if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) {
            TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor();
            if (elementTypeDesc != null) {
                Class<?> elementType = elementTypeDesc.getType();
                if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }
    boolean standardConversion = false;
    if (requiredType != null) {
        if (convertedValue != null) {
            if (Object.class == requiredType) {
                return (T) convertedValue;
            } else if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor<T> strCtor = requiredType.getConstructor(String.class);
                        return BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Construction via String failed for type [" + requiredType.getName() + "]", ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) {
                convertedValue = NumberUtils.convertNumberToTargetClass((Number) convertedValue, (Class<Number>) requiredType);
                standardConversion = true;
            }
        } else {
            // convertedValue == null
            if (requiredType == Optional.class) {
                convertedValue = Optional.empty();
            }
        }
        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (conversionAttemptEx != null) {
                // Original exception from former ConversionService call above...
                throw conversionAttemptEx;
            } else if (conversionService != null) {
                // ConversionService not tried before, probably custom editor found
                // but editor couldn't produce the required type...
                TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
                if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
                    return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
                }
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type '").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("' to required type '").append(ClassUtils.getQualifiedName(requiredType)).append("'");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName()).append("] returned inappropriate value of type '").append(ClassUtils.getDescriptiveType(convertedValue)).append("'");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }
    if (conversionAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) {
            throw conversionAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", conversionAttemptEx);
    }
    return (T) convertedValue;
}
Also used : Constructor(java.lang.reflect.Constructor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionService(org.springframework.core.convert.ConversionService) PropertyEditor(java.beans.PropertyEditor) Collection(java.util.Collection) Map(java.util.Map)

Aggregations

ConversionFailedException (org.springframework.core.convert.ConversionFailedException)12 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)10 Test (org.junit.Test)6 Map (java.util.Map)5 ConverterNotFoundException (org.springframework.core.convert.ConverterNotFoundException)5 HashMap (java.util.HashMap)4 EnumMap (java.util.EnumMap)3 LinkedHashMap (java.util.LinkedHashMap)3 ConversionService (org.springframework.core.convert.ConversionService)3 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)3 MultiValueMap (org.springframework.util.MultiValueMap)3 Constructor (java.lang.reflect.Constructor)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Collection (java.util.Collection)2 List (java.util.List)2 JsonObjectBase (com.baidu.dsp.common.vo.JsonObjectBase)1 PropertyEditor (java.beans.PropertyEditor)1 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 Member (java.lang.reflect.Member)1