Example usage for org.springframework.beans TypeMismatchException TypeMismatchException

List of usage examples for org.springframework.beans TypeMismatchException TypeMismatchException

Introduction

In this page you can find the example usage for org.springframework.beans TypeMismatchException TypeMismatchException.

Prototype

public TypeMismatchException(@Nullable Object value, @Nullable Class<?> requiredType,
        @Nullable Throwable cause) 

Source Link

Document

Create a new TypeMismatchException without a PropertyChangeEvent .

Usage

From source file:org.syncope.core.rest.controller.AbstractController.java

protected AttributableUtil getAttributableUtil(final String kind) {
    AttributableUtil result = null;/*from w  w w  .j ava2 s. com*/

    try {
        result = AttributableUtil.valueOf(kind.toUpperCase());
    } catch (Exception e) {
        LOG.error("Attributable not supported: " + kind);

        throw new TypeMismatchException(kind, AttributableUtil.class, e);
    }

    return result;
}

From source file:org.syncope.core.rest.controller.AbstractController.java

protected TaskUtil getTaskUtil(final String kind) {
    TaskUtil result = null;//from  w ww. j  a v a 2 s.  c o  m

    try {
        result = TaskUtil.valueOf(kind.toUpperCase());
    } catch (Exception e) {
        LOG.error("Task not supported: " + kind);

        throw new TypeMismatchException(kind, TaskUtil.class, e);
    }

    return result;
}

From source file:org.archive.spring.Sheet.java

/**
 * Ensure any properties targetted by this Sheet know to 
 * check the right property paths for overrides at lookup time,
 * and that the override values are compatible types for their 
 * destination properties. //from   w  ww  . ja  v  a 2s.c o m
 * 
 * Should be done as soon as all possible targets are 
 * constructed (ApplicationListener ContextRefreshedEvent)
 * 
 * TODO: consider if  an 'un-priming' also needs to occur to 
 * prevent confusing side-effects. 
 * TODO: consider if priming should move to another class
 */
public void prime() {
    for (String fullpath : map.keySet()) {
        int lastDot = fullpath.lastIndexOf(".");
        String beanPath = fullpath.substring(0, lastDot);
        String terminalProp = fullpath.substring(lastDot + 1);
        Object value = map.get(fullpath);
        int i = beanPath.indexOf(".");
        Object bean;
        HasKeyedProperties hkp;
        if (i < 0) {
            bean = beanFactory.getBean(beanPath);
        } else {
            String beanName = beanPath.substring(0, i);
            String propPath = beanPath.substring(i + 1);
            BeanWrapperImpl wrapper = new BeanWrapperImpl(beanFactory.getBean(beanName));
            bean = wrapper.getPropertyValue(propPath);
        }
        try {
            hkp = (HasKeyedProperties) bean;
        } catch (ClassCastException cce) {
            // targetted bean has no overridable properties
            throw new TypeMismatchException(bean, HasKeyedProperties.class, cce);
        }
        // install knowledge of this path 
        hkp.getKeyedProperties().addExternalPath(beanPath);
        // verify type-compatibility
        BeanWrapperImpl wrapper = new BeanWrapperImpl(hkp);
        Class<?> requiredType = wrapper.getPropertyType(terminalProp);
        try {
            // convert for destination type
            map.put(fullpath, wrapper.convertForProperty(value, terminalProp));
        } catch (TypeMismatchException tme) {
            TypeMismatchException tme2 = new TypeMismatchException(
                    new PropertyChangeEvent(hkp, fullpath, wrapper.getPropertyValue(terminalProp), value),
                    requiredType, tme);
            throw tme2;
        }
    }
}

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

@Override
public void setPropertyValue(String propertyName, Object newValue) throws BeansException {
    Field field = this.fieldMap.get(propertyName);
    if (field == null) {
        throw new NotWritablePropertyException(this.target.getClass(), propertyName,
                "Field '" + propertyName + "' does not exist");
    }// w  w  w.j  a  va2  s .co m
    Object oldValue = null;
    try {
        ReflectionUtils.makeAccessible(field);
        oldValue = field.get(this.target);
        // jlm - Adapt to simpleTypeConverter
        Object convertedValue = this.typeConverterDelegate.convertIfNecessary(newValue, field.getType());
        field.set(this.target, convertedValue);
    } catch (ConverterNotFoundException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.target, propertyName, oldValue, newValue);
        throw new ConversionNotSupportedException(pce, field.getType(), ex);
    } catch (ConversionException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.target, propertyName, oldValue, newValue);
        throw new TypeMismatchException(pce, field.getType(), ex);
    } catch (IllegalStateException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.target, propertyName, oldValue, newValue);
        throw new ConversionNotSupportedException(pce, field.getType(), ex);
    } catch (IllegalArgumentException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.target, propertyName, oldValue, newValue);
        throw new TypeMismatchException(pce, field.getType(), ex);
    } catch (IllegalAccessException ex) {
        throw new InvalidPropertyException(this.target.getClass(), propertyName, "Field is not accessible", ex);
    }
}

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

public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam)
        throws TypeMismatchException {
    try {/*w w  w .j a  v  a 2s .  c  o m*/
        return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam);
    } catch (IllegalArgumentException ex) {
        throw new TypeMismatchException(value, requiredType, ex);
    } catch (IllegalStateException ex) {
        throw new ConversionNotSupportedException(value, requiredType, ex);
    }
}

From source file:net.sf.morph.beans.MorphBeanWrapper.java

public void setPropertyValue(String propertyName, Object value) throws BeansException {
    try {//from   w ww  . j  av  a  2s. co  m
        beanReflector.set(bean, propertyName, value);
    } catch (ReflectionException e) {
        // TODO test that this actually results in TypeMismatchExceptions
        // being thrown as desired
        if (e.getCause() instanceof TransformationException) {
            Class requiredType = null;
            try {
                requiredType = getPropertyType(propertyName);
            } catch (BeansException logged) {
                if (log.isWarnEnabled()) {
                    log.warn("Type for property '" + propertyName + "' could not be determined", logged);
                }
            }
            throw new TypeMismatchException(getPropertyChangeEvent(propertyName, value), requiredType, e);
        }
        throw new MethodInvocationException(getPropertyChangeEvent(propertyName, value), e);
    }
}

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

private Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<?> requiredType,
        TypeDescriptor td) throws TypeMismatchException {
    try {/*from  www  .j  ava2  s  . c  o  m*/
        return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType,
                td);
    } catch (ConverterNotFoundException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                oldValue, newValue);
        throw new ConversionNotSupportedException(pce, td.getType(), ex);
    } catch (ConversionException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                oldValue, newValue);
        throw new TypeMismatchException(pce, requiredType, ex);
    } catch (IllegalStateException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                oldValue, newValue);
        throw new ConversionNotSupportedException(pce, requiredType, ex);
    } catch (IllegalArgumentException ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                oldValue, newValue);
        throw new TypeMismatchException(pce, requiredType, ex);
    }
}

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

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/* ww w  .  j a va  2  s  .  c  o  m*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException {
    String propertyName = tokens.canonicalName;

    if (tokens.keys != null) {
        // apply indexes and map keys: fetch value for all keys but the last one
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue = null;/*from   w w w . j av  a2s .  c o  m*/
        Type type;
        try {
            propValue = getPropertyValue(getterTokens);
            type = getPropertyType(getterTokens);
            if (propValue == null) {
                Class rawType = null;
                if (type instanceof ParameterizedType) {
                    if (((ParameterizedType) type).getRawType() instanceof Class) {
                        rawType = (Class) ((ParameterizedType) type).getRawType();
                    } else if (type instanceof Class) {
                        rawType = (Class) type;
                    }
                }
                if (rawType != null && List.class.isAssignableFrom(rawType)) {
                    PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder();
                    propertyTokenHolder.actualName = getterTokens.actualName;
                    propertyTokenHolder.canonicalName = getterTokens.canonicalName;
                    setPropertyValue(propertyTokenHolder, new ArrayList());
                }
            }
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // set value for last key
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "': returned null");
        } else if (propValue.getClass().isArray()) {
            Class requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (this.extractOldValueForEditor) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue,
                        newValue, requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, newValue);
                throw new TypeMismatchException(pce, requiredType, ex);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (this.extractOldValueForEditor && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    null);
            if (index < list.size()) {
                list.set(index, convertedValue);
            } else if (index >= list.size()) {
                for (int i = list.size(); i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + list.size()
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
        } else if (propValue instanceof Map) {
            Map map = (Map) propValue;
            propValue.getClass().getGenericSuperclass();
            Object oldValue = null;
            if (this.extractOldValueForEditor) {
                oldValue = map.get(key);
            }
            Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1];
            Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0];
            Class reqClass = null;
            Class keyReqClass = null;
            if (type2 instanceof Class) {
                reqClass = (Class) type2;
            } else if (type2 instanceof ParameterizedType) {
                reqClass = (Class) ((ParameterizedType) type2).getRawType();
            }

            if (type3 instanceof Class) {
                keyReqClass = (Class) type3;
            } else if (type3 instanceof ParameterizedType) {
                keyReqClass = (Class) ((ParameterizedType) type3).getRawType();
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    reqClass);
            Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass);
            map.put(convertedKey, convertedValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + newValue
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd == null || pd.getWriteMethod() == null) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName);
        }

        Method readMethod = pd.getReadMethod();
        Method writeMethod = pd.getWriteMethod();
        Object oldValue = null;

        if (this.extractOldValueForEditor && readMethod != null) {
            try {
                oldValue = readMethod.invoke(this.object, new Object[0]);
            } catch (Exception ex) {
                logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName,
                        ex);
            }
        }

        try {
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    pd.getPropertyType());

            if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) {
                throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '"
                        + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]");
            }

            if (logger.isDebugEnabled()) {
                logger.debug("About to invoke write method [" + writeMethod + "] on object of class ["
                        + this.object.getClass().getName() + "]");
            }
            writeMethod.invoke(this.object, new Object[] { convertedValue });
            if (logger.isDebugEnabled()) {
                logger.debug("Invoked write method [" + writeMethod + "] with value of type ["
                        + pd.getPropertyType().getName() + "]");
            }
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, newValue);
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property.//  w  w  w  .ja  v a 2  s  .  com
 * @param propertyName name of the property
 * @param oldValue previous value, if available (may be <code>null</code>)
 * @param newValue proposed change value
 * @param requiredType the type we must convert to
 * (or <code>null</code> if not known, for example in case of a collection element)
 * @return the new value, possibly the result of type conversion
 * @throws TypeMismatchException if type conversion failed
 */
protected Object doTypeConversionIfNecessary(String propertyName, String fullPropertyName, Object oldValue,
        Object newValue, Class requiredType) throws TypeMismatchException {

    Object convertedValue = newValue;
    if (convertedValue != null) {

        // Custom editor for this type?
        PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName);

        // Value not of required type?
        if (pe != null || (requiredType != null
                && (requiredType.isArray() || !requiredType.isAssignableFrom(convertedValue.getClass())))) {

            if (requiredType != null) {
                if (pe == null) {
                    // No custom editor -> check BeanWrapperImpl's default editors.
                    pe = (PropertyEditor) this.defaultEditors.get(requiredType);
                    if (pe == null) {
                        // No BeanWrapper default editor -> check standard JavaBean editors.
                        pe = PropertyEditorManager.findEditor(requiredType);
                    }
                }
            }

            if (pe != null && !(convertedValue instanceof String)) {
                // Not a String -> use PropertyEditor's setValue.
                // With standard PropertyEditors, this will return the very same object;
                // we just want to allow special PropertyEditors to override setValue
                // for type conversion from non-String values to the required type.
                try {
                    pe.setValue(convertedValue);
                    Object newConvertedValue = pe.getValue();
                    if (newConvertedValue != convertedValue) {
                        convertedValue = newConvertedValue;
                        // Reset PropertyEditor: It already did a proper conversion.
                        // Don't use it again for a setAsText call.
                        pe = null;
                    }
                } catch (IllegalArgumentException ex) {
                    throw new TypeMismatchException(
                            createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
                }
            }

            if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
                // Convert String array to a comma-separated String.
                // Only applies if no PropertyEditor converted the String array before.
                // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
                if (logger.isDebugEnabled()) {
                    logger.debug("Converting String array to comma-delimited String [" + convertedValue + "]");
                }
                convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
            }

            if (pe != null && convertedValue instanceof String) {
                // Use PropertyEditor's setAsText in case of a String value.
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Converting String to [" + requiredType + "] using property editor [" + pe + "]");
                }
                try {
                    pe.setValue(oldValue);
                    pe.setAsText((String) convertedValue);
                    convertedValue = pe.getValue();
                } catch (IllegalArgumentException ex) {
                    throw new TypeMismatchException(
                            createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
                }
            }

            if (requiredType != null) {
                // Array required -> apply appropriate conversion of elements.
                if (requiredType.isArray()) {
                    Class componentType = requiredType.getComponentType();
                    if (convertedValue instanceof Collection) {
                        // Convert Collection elements to array elements.
                        Collection coll = (Collection) convertedValue;
                        Object result = Array.newInstance(componentType, coll.size());
                        int i = 0;
                        for (Iterator it = coll.iterator(); it.hasNext(); i++) {
                            Object value = doTypeConversionIfNecessary(propertyName,
                                    propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null,
                                    it.next(), componentType);
                            Array.set(result, i, value);
                        }
                        return result;
                    } else if (convertedValue != null && convertedValue.getClass().isArray()) {
                        // Convert Collection elements to array elements.
                        int arrayLength = Array.getLength(convertedValue);
                        Object result = Array.newInstance(componentType, arrayLength);
                        for (int i = 0; i < arrayLength; i++) {
                            Object value = doTypeConversionIfNecessary(propertyName,
                                    propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null,
                                    Array.get(convertedValue, i), componentType);
                            Array.set(result, i, value);
                        }
                        return result;
                    } else {
                        // A plain value: convert it to an array with a single component.
                        Object result = Array.newInstance(componentType, 1);
                        Object value = doTypeConversionIfNecessary(propertyName,
                                propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX, null,
                                convertedValue, componentType);
                        Array.set(result, 0, value);
                        return result;
                    }
                }

                // If the resulting value definitely doesn't match the required type,
                // try field lookup as fallback. If no matching field found,
                // throw explicit TypeMismatchException with full context information.
                if (convertedValue != null && !requiredType.isPrimitive()
                        && !requiredType.isAssignableFrom(convertedValue.getClass())) {

                    // In case of String value, try to find matching field (for JDK 1.5
                    // enum or custom enum with values defined as static fields).
                    if (convertedValue instanceof String) {
                        try {
                            Field enumField = requiredType.getField((String) convertedValue);
                            return enumField.get(null);
                        } catch (Exception ex) {
                            logger.debug("Field [" + convertedValue + "] isn't an enum value", ex);
                        }
                    }

                    // Definitely doesn't match: throw TypeMismatchException.
                    throw new TypeMismatchException(
                            createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType);
                }
            }
        }
    }

    if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists
        Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod()
                .getGenericReturnType();
        if (genericReturnType instanceof ParameterizedType) {
            Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
            if (actualType instanceof Class && convertedValue != null) {
                List list = (List) convertedValue;
                for (int i = 0; i < list.size(); i++) {
                    Object o = list.remove(i);
                    o = doTypeConversionIfNecessary(o, (Class) actualType);
                    list.add(i, o);
                }
            }
        }
    }

    return convertedValue;
}