Search in sources :

Example 1 with ConversionFailedException

use of org.springframework.core.convert.ConversionFailedException in project centipede by paulhoule.

the class OptionParser method parse.

public HasOptions parse(Iterable<String> args) throws IllegalAccessException {
    HasOptions options;
    try {
        options = (HasOptions) that.getConstructor().newInstance();
    } catch (NoSuchMethodException ex) {
        throw new IllegalArgumentException("Class " + that + " doesn't have a zero argument constructor", ex);
    } catch (IllegalAccessException ex) {
        throw new IllegalArgumentException("Class " + that + " has a non-public zero argument constructor", ex);
    } catch (InstantiationException ex) {
        throw new IllegalArgumentException("Class " + that + " cannot be abstract", ex);
    } catch (InvocationTargetException ex) {
        throw new IllegalArgumentException("Class " + that + " threw an exception during construction", ex);
    }
    Map<String, RWOption> lookup = getStringAnnotationMap(that);
    for (RWOption o : lookup.values()) {
        if (isSomeKindOfBoolean(o)) {
            o.getField().setBoolean(options, false);
        } else {
            Object defaultValue = null;
            if (!o.getDefaultValue().isEmpty()) {
                try {
                    defaultValue = conversionService.convert(o.getDefaultValue(), TypeDescriptor.valueOf(String.class), new TypeDescriptor(o.getField()));
                } catch (ConversionFailedException x) {
                    throw new UnparsableDefaultException(o.getName(), o.getDefaultValue(), o.getType(), x);
                }
            } else {
                defaultValue = defaultValueFor(o.getType());
            }
            o.getField().set(options, defaultValue);
        }
    }
    Set<Field> sawOption = new HashSet<>();
    Iterator<String> p = args.iterator();
    String peek = null;
    while (p.hasNext()) {
        peek = p.next();
        if (!peek.startsWith("-"))
            break;
        String name = peek.substring(1);
        if (!lookup.containsKey(name))
            throw new InvalidOptionException("invalid option :" + name);
        RWOption field = lookup.get(name);
        sawOption.add(field.getField());
        if (isSomeKindOfBoolean(field)) {
            field.getField().setBoolean(options, true);
        } else {
            String value = p.next();
            try {
                if (field.isList()) {
                    String[] parts = value.split(",");
                    Class elementType = field.getElementType();
                    for (String part : parts) {
                        final Object innerValue = field.convertFrom(options, conversionService, part);
                        ((List) field.getField().get(options)).add(innerValue);
                    }
                } else {
                    final Object innerValue = field.convertFrom(options, conversionService, value);
                    field.getField().set(options, innerValue);
                }
            } catch (ConversionFailedException x) {
                throw new UnparsableOptionException(name, value, field.getType(), x);
            }
        }
        peek = null;
    }
    for (RWOption o : lookup.values()) {
        if (o.isRequired() && !sawOption.contains(o.getField()))
            throw new MissingOptionException("Required option -" + o.getName() + " is missing");
    }
    List<String> positional = new ArrayList<String>();
    if (peek != null)
        positional.add(peek);
    while (p.hasNext()) positional.add(p.next());
    Field positionalField = findPositionalParameter(that);
    if (positionalField != null)
        positionalField.set(options, positional);
    return options;
}
Also used : Field(java.lang.reflect.Field) InvocationTargetException(java.lang.reflect.InvocationTargetException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException)

Example 2 with ConversionFailedException

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

the class AbstractPropertyAccessorTests method setPropertyIntermediateListIsNullWithBadConversionService.

@Test
public void setPropertyIntermediateListIsNullWithBadConversionService() {
    Foo target = new Foo();
    AbstractPropertyAccessor accessor = createAccessor(target);
    accessor.setConversionService(new GenericConversionService() {

        @Override
        public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            throw new ConversionFailedException(sourceType, targetType, source, null);
        }
    });
    accessor.setAutoGrowNestedPaths(true);
    accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9");
    assertEquals("9", target.listOfMaps.get(0).get("luckyNumber"));
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) Test(org.junit.Test)

Example 3 with ConversionFailedException

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

the class ObjectToObjectConverter method convert.

@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    if (source == null) {
        return null;
    }
    Class<?> sourceClass = sourceType.getType();
    Class<?> targetClass = targetType.getType();
    Member member = getValidatedMember(targetClass, sourceClass);
    try {
        if (member instanceof Method) {
            Method method = (Method) member;
            ReflectionUtils.makeAccessible(method);
            if (!Modifier.isStatic(method.getModifiers())) {
                return method.invoke(source);
            } else {
                return method.invoke(null, source);
            }
        } else if (member instanceof Constructor) {
            Constructor<?> ctor = (Constructor<?>) member;
            ReflectionUtils.makeAccessible(ctor);
            return ctor.newInstance(source);
        }
    } catch (InvocationTargetException ex) {
        throw new ConversionFailedException(sourceType, targetType, source, ex.getTargetException());
    } catch (Throwable ex) {
        throw new ConversionFailedException(sourceType, targetType, source, ex);
    }
    // method or Integer(java.lang.Number) constructor exists on java.lang.Integer.
    throw new IllegalStateException(String.format("No to%3$s() method exists on %1$s, " + "and no static valueOf/of/from(%1$s) method or %3$s(%1$s) constructor exists on %2$s.", sourceClass.getName(), targetClass.getName(), targetClass.getSimpleName()));
}
Also used : ConversionFailedException(org.springframework.core.convert.ConversionFailedException) Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method) Member(java.lang.reflect.Member) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with ConversionFailedException

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

the class MapToMapConverterTests method scalarMap.

@Test
public void scalarMap() throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("1", "9");
    map.put("2", "37");
    TypeDescriptor sourceType = TypeDescriptor.forObject(map);
    TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
    assertTrue(conversionService.canConvert(sourceType, targetType));
    try {
        conversionService.convert(map, sourceType, targetType);
    } catch (ConversionFailedException ex) {
        assertTrue(ex.getCause() instanceof ConverterNotFoundException);
    }
    conversionService.addConverterFactory(new StringToNumberConverterFactory());
    assertTrue(conversionService.canConvert(sourceType, targetType));
    @SuppressWarnings("unchecked") Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
    assertFalse(map.equals(result));
    assertEquals((Integer) 9, result.get(1));
    assertEquals((Integer) 37, result.get(2));
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) EnumMap(java.util.EnumMap) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.Test)

Example 5 with ConversionFailedException

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

the class MapToMapConverterTests method collectionMap.

@Test
public void collectionMap() throws Exception {
    Map<String, List<String>> map = new HashMap<>();
    map.put("1", Arrays.asList("9", "12"));
    map.put("2", Arrays.asList("37", "23"));
    TypeDescriptor sourceType = TypeDescriptor.forObject(map);
    TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
    assertTrue(conversionService.canConvert(sourceType, targetType));
    try {
        conversionService.convert(map, sourceType, targetType);
    } catch (ConversionFailedException ex) {
        assertTrue(ex.getCause() instanceof ConverterNotFoundException);
    }
    conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
    conversionService.addConverterFactory(new StringToNumberConverterFactory());
    assertTrue(conversionService.canConvert(sourceType, targetType));
    @SuppressWarnings("unchecked") Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
    assertFalse(map.equals(result));
    assertEquals(Arrays.asList(9, 12), result.get(1));
    assertEquals(Arrays.asList(37, 23), result.get(2));
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) List(java.util.List) EnumMap(java.util.EnumMap) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.Test)

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