Example usage for org.springframework.beans PropertyValue getConvertedValue

List of usage examples for org.springframework.beans PropertyValue getConvertedValue

Introduction

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

Prototype

@Nullable
public synchronized Object getConvertedValue() 

Source Link

Document

Return the converted value of this property value, after processed type conversion.

Usage

From source file:org.guicerecipes.spring.converter.SpringConverter.java

@SuppressWarnings("unchecked")
protected void generateBeanDefinition(ModuleGenerator generator, String name, BeanDefinition definition,
        String className) {//  w  w w  . j a  v  a  2  s .c o  m
    String shortClassName = addImport(className);
    ProduceMethod method = generator.startProvides(name, shortClassName);

    ConstructorArgumentValues constructors = definition.getConstructorArgumentValues();
    Map map = constructors.getIndexedArgumentValues();
    for (int i = 0, size = map.size(); i < size; i++) {
        ValueHolder valueHolder = (ValueHolder) map.get(i);
        if (valueHolder != null) {
            Object value = valueHolder.getValue();
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                String text = stringValue.getValue();
                System.out.printf("param %s=\"%s\"\n", i, text);
                String expression = null;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + text + "\"";
                }
                method.addConstructorExpression(expression);
            } else if (value instanceof BeanReference) {
                BeanReference reference = (BeanReference) value;
                String beanRef = reference.getBeanName();
                // TODO
                String typeName = "Object";
                String expression = addParameter(method, typeName, beanRef);
                method.addConstructorExpression(expression);
            }
        }
    }

    MutablePropertyValues propertyValues = definition.getPropertyValues();
    PropertyValue[] propertyArray = propertyValues.getPropertyValues();
    for (PropertyValue propertyValue : propertyArray) {
        String property = getSetterMethod(propertyValue);
        Object value = propertyValue.getConvertedValue();
        if (value == null) {
            value = propertyValue.getValue();
        }
        if (value instanceof BeanReference) {
            BeanReference reference = (BeanReference) value;
            String beanRef = reference.getBeanName();
            // TODO
            String typeName = "Object";
            String expression = addParameter(method, typeName, beanRef);
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        } else if (value instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) value;
            addChildBeanDefinition(generator, method, name, propertyValue,
                    beanDefinitionHolder.getBeanDefinition());
        } else if (value instanceof ChildBeanDefinition) {
            ChildBeanDefinition childBeanDefinition = (ChildBeanDefinition) value;
            addChildBeanDefinition(generator, method, name, propertyValue, childBeanDefinition);
        } else {
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                value = stringValue.getValue();

            }
            String valueType = (value == null) ? null : value.getClass().getName();
            System.out.printf("property %s=%s of type %s\n", property, value, valueType);

            String expression;
            if (value instanceof String) {
                String text = (String) value;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + value + "\"";
                }
            } else if (value == null) {
                expression = "null";
            } else {
                expression = value.toString();
            }
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        }
    }
}

From source file:org.guiceyfruit.spring.converter.SpringConverter.java

protected void generateBeanDefinition(ModuleGenerator generator, String name, BeanDefinition definition,
        String className) {/* w  ww  .  j  a va 2  s. com*/
    String shortClassName = addImport(className);
    ProduceMethod method = generator.startProvides(name, shortClassName);

    ConstructorArgumentValues constructors = definition.getConstructorArgumentValues();
    Map map = constructors.getIndexedArgumentValues();
    for (int i = 0, size = map.size(); i < size; i++) {
        ValueHolder valueHolder = (ValueHolder) map.get(i);
        if (valueHolder != null) {
            Object value = valueHolder.getValue();
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                String text = stringValue.getValue();
                System.out.printf("param %s=\"%s\"\n", i, text);
                String expression = null;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + text + "\"";
                }
                method.addConstructorExpression(expression);
            } else if (value instanceof BeanReference) {
                BeanReference reference = (BeanReference) value;
                String beanRef = reference.getBeanName();
                // TODO
                String typeName = "Object";
                String expression = addParameter(method, typeName, beanRef);
                method.addConstructorExpression(expression);
            }
        }
    }

    MutablePropertyValues propertyValues = definition.getPropertyValues();
    PropertyValue[] propertyArray = propertyValues.getPropertyValues();
    for (PropertyValue propertyValue : propertyArray) {
        String property = getSetterMethod(propertyValue);
        Object value = propertyValue.getConvertedValue();
        if (value == null) {
            value = propertyValue.getValue();
        }
        if (value instanceof BeanReference) {
            BeanReference reference = (BeanReference) value;
            String beanRef = reference.getBeanName();
            // TODO
            String typeName = "Object";
            String expression = addParameter(method, typeName, beanRef);
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        } else if (value instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) value;
            addChildBeanDefinition(generator, method, name, propertyValue,
                    beanDefinitionHolder.getBeanDefinition());
        } else if (value instanceof ChildBeanDefinition) {
            ChildBeanDefinition childBeanDefinition = (ChildBeanDefinition) value;
            addChildBeanDefinition(generator, method, name, propertyValue, childBeanDefinition);
        } else {
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                value = stringValue.getValue();

            }
            String valueType = (value == null) ? null : value.getClass().getName();
            System.out.printf("property %s=%s of type %s\n", property, value, valueType);

            String expression;
            if (value instanceof String) {
                String text = (String) value;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + value + "\"";
                }
            } else if (value == null) {
                expression = "null";
            } else {
                expression = value.toString();
            }
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        }
    }
}

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;/*from www .  j ava 2 s.c  om*/
        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.kuali.rice.krad.datadictionary.DataDictionary.java

/**
 * Returns a property value for the bean with the given name from the dictionary.
 *
 * @param beanName id or name for the bean definition
 * @param propertyName name of the property to retrieve, must be a valid property configured on
 * the bean definition/*from  ww  w  . j  av a  2 s .  c o  m*/
 * @return Object property value for property
 */
public Object getDictionaryBeanProperty(String beanName, String propertyName) {
    Object bean = ddBeans.getSingleton(beanName);
    if (bean != null) {
        return ObjectPropertyUtils.getPropertyValue(bean, propertyName);
    }

    BeanDefinition beanDefinition = ddBeans.getMergedBeanDefinition(beanName);

    if (beanDefinition == null) {
        throw new RuntimeException("Unable to get bean for bean name: " + beanName);
    }

    PropertyValues pvs = beanDefinition.getPropertyValues();
    if (pvs.contains(propertyName)) {
        PropertyValue propertyValue = pvs.getPropertyValue(propertyName);

        Object value;
        if (propertyValue.isConverted()) {
            value = propertyValue.getConvertedValue();
        } else if (propertyValue.getValue() instanceof String) {
            String unconvertedValue = (String) propertyValue.getValue();
            Scope scope = ddBeans.getRegisteredScope(beanDefinition.getScope());
            BeanExpressionContext beanExpressionContext = new BeanExpressionContext(ddBeans, scope);

            value = ddBeans.getBeanExpressionResolver().evaluate(unconvertedValue, beanExpressionContext);
        } else {
            value = propertyValue.getValue();
        }

        return value;
    }

    return null;
}

From source file:org.springframework.beans.AbstractNestablePropertyAccessor.java

private void processLocalProperty(PropertyTokenHolder tokens, PropertyValue pv) {
    PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
    if (ph == null || !ph.isWritable()) {
        if (pv.isOptional()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring optional value for property '" + tokens.actualName
                        + "' - property not found on bean class [" + getRootClass().getName() + "]");
            }// ww  w  .j av a2 s .co m
            return;
        } else {
            throw createNotWritablePropertyException(tokens.canonicalName);
        }
    }

    Object oldValue = null;
    try {
        Object originalValue = pv.getValue();
        Object valueToApply = originalValue;
        if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
            if (pv.isConverted()) {
                valueToApply = pv.getConvertedValue();
            } else {
                if (isExtractOldValueForEditor() && ph.isReadable()) {
                    try {
                        oldValue = ph.getValue();
                    } 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
                                    + tokens.canonicalName + "'", ex);
                        }
                    }
                }
                valueToApply = convertForProperty(tokens.canonicalName, oldValue, originalValue,
                        ph.toTypeDescriptor());
            }
            pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
        }
        ph.setValue(valueToApply);
    } catch (TypeMismatchException ex) {
        throw ex;
    } catch (InvocationTargetException ex) {
        PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(getRootInstance(),
                this.nestedPath + tokens.canonicalName, oldValue, pv.getValue());
        if (ex.getTargetException() instanceof ClassCastException) {
            throw new TypeMismatchException(propertyChangeEvent, ph.getPropertyType(), ex.getTargetException());
        } else {
            Throwable cause = ex.getTargetException();
            if (cause instanceof UndeclaredThrowableException) {
                // May happen e.g. with Groovy-generated methods
                cause = cause.getCause();
            }
            throw new MethodInvocationException(propertyChangeEvent, cause);
        }
    } catch (Exception ex) {
        PropertyChangeEvent pce = new PropertyChangeEvent(getRootInstance(),
                this.nestedPath + tokens.canonicalName, oldValue, pv.getValue());
        throw new MethodInvocationException(pce, ex);
    }
}

From source file:org.springframework.beans.BeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    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;// w  w  w. j  a v a  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()) {
                // TODO: 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.resolvedDescriptor;
        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().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                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().conversionNecessary = (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.tinygroup.weblayer.webcontext.parser.util.BeanWrapperImpl.java

private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    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 = null;/*  w  w  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) {
            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 (isExtractOldValueForEditor()) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                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) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class requiredType = null;
            if (JdkVersion.isAtLeastJava15()) {
                requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                        tokens.keys.length);
            }
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            try {
                Object convertedValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), requiredType);
                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);
                }
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                throw new TypeMismatchException(pce, requiredType, ex);
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class mapKeyType = null;
            Class mapValueType = null;
            if (JdkVersion.isAtLeastJava15()) {
                mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                        tokens.keys.length);
                mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                        tokens.keys.length);
            }
            Map map = (Map) propValue;
            Object convertedMapKey = null;
            Object convertedMapValue = null;
            try {
                // IMPORTANT: Do not pass full property name in here - property editors
                // must not kick in for map keys but rather only for map values.
                convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, null, pv.getValue());
                throw new TypeMismatchException(pce, mapKeyType, ex);
            }
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            try {
                // Pass full property name and old value in here, since we want full
                // conversion ability for map values.
                convertedMapValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), mapValueType, null,
                        new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1));
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                throw new TypeMismatchException(pce, mapValueType, ex);
            }
            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.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                        matches.buildErrorMessage(), matches.getPossibleMatches());
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        try {
                            oldValue = readMethod.invoke(this.object, new Object[0]);
                        } catch (Exception ex) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = this.typeConverterDelegate.convertIfNecessary(oldValue, originalValue, pd);
                }
                pv.getOriginalPropertyValue().conversionNecessary = Boolean
                        .valueOf(valueToApply != originalValue);
            }
            Method writeMethod = pd.getWriteMethod();
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                writeMethod.setAccessible(true);
            }
            writeMethod.invoke(this.object, new Object[] { valueToApply });
        } 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 (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}