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());
}
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;
}
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);
}
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;
}
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;
}
Aggregations