Example usage for org.springframework.beans NullValueInNestedPathException NullValueInNestedPathException

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

Introduction

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

Prototype

public NullValueInNestedPathException(Class<?> beanClass, String propertyName, String msg) 

Source Link

Document

Create a new NullValueInNestedPathException.

Usage

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

private PropertyValue createDefaultPropertyValue(PropertyTokenHolder tokens) {
    TypeDescriptor desc = getPropertyTypeDescriptor(tokens.canonicalName);
    Class<?> type = desc.getType();
    if (type == null) {
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName,
                "Could not determine property type for auto-growing a default value");
    }//from  ww w.j a  v  a  2s  .com
    Object defaultValue = newValue(type, desc, tokens.canonicalName);
    return new PropertyValue(tokens.canonicalName, defaultValue);
}

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

private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
    try {/*from ww w .j a v  a  2s. c om*/
        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            // #TO#DO# - only handles 2-dimensional arrays
            if (componentType.isArray()) {
                Object array = Array.newInstance(componentType, 1);
                Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
                return array;
            } else {
                return Array.newInstance(componentType, 0);
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
            return CollectionFactory.createCollection(type,
                    (elementDesc != null ? elementDesc.getType() : null), 16);
        } else if (Map.class.isAssignableFrom(type)) {
            TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
            return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
        } else {
            return type.newInstance();
        }
    } catch (Exception ex) {
        // #TO#DO#: Root cause exception context is lost here; just exception message preserved.
        // Should we throw another exception type that preserves context instead?
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
                "Could not instantiate property type [" + type.getName()
                        + "] to auto-grow nested property path: " + ex);
    }
}

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

@SuppressWarnings("unchecked")
private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }/* ww w  . java 2s .c o  m*/
    final Method readMethod = pd.getReadMethod();
    try {
        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);
            }
        }

        Object value;
        if (System.getSecurityManager() != null) {
            try {
                value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        return readMethod.invoke(object, (Object[]) null);
                    }
                }, acc);
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            value = readMethod.invoke(object, (Object[]) null);
        }

        if (tokens.keys != null) {
            if (value == null) {
                if (isAutoGrowNestedPaths()) {
                    value = setDefaultValue(tokens.actualName);
                } else {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                }
            }
            String indexedPropertyName = tokens.actualName;
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];
                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    int index = Integer.parseInt(key);
                    value = growArrayIfNecessary(value, index, indexedPropertyName);
                    value = Array.get(value, index);
                } else if (value instanceof List) {
                    int index = Integer.parseInt(key);
                    List<Object> list = (List<Object>) value;
                    growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1);
                    value = list.get(index);
                } else if (value instanceof Set) {
                    // Apply index to Iterator in case of a Set.
                    Set<Object> set = (Set<Object>) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'");
                    }
                    Iterator<Object> it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    Map<Object, Object> map = (Map<Object, Object>) value;
                    Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                            i + 1);
                    // 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);
                    value = map.get(convertedMapKey);
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
                indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX;
            }
        }
        return value;
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (TypeMismatchException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (Exception ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", 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;//from w  ww.jav 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()) {
                // #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

/**
 * Retrieve a BeanWrapper for the given nested property.
 * Create a new one if not found in the cache.
 * <p>Note: Caching nested BeanWrappers is necessary now,
 * to keep registered custom editors for nested properties.
 * @param nestedProperty property to create the BeanWrapper for
 * @return the BeanWrapper instance, either cached or newly created
 */// w w w .  j a  va2 s  .c  o  m
private ExtendedBeanWrapper getNestedBeanWrapper(String nestedProperty) throws BeansException {
    if (this.nestedBeanWrappers == null) {
        this.nestedBeanWrappers = new HashMap();
    }
    // get value of bean property
    PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty);
    Object propertyValue = getPropertyValue(tokens);
    String canonicalName = tokens.canonicalName;
    String propertyName = tokens.actualName;
    if (propertyValue == null) {
        //tentar instanciar o objeto
        String errorMsg = "";
        try {
            Type returnType = getPropertyType(tokens);
            Class clazz = null;
            if (returnType instanceof Class) {
                clazz = (Class) returnType;
            } else if (returnType instanceof ParameterizedType) {
                clazz = (Class) ((ParameterizedType) returnType).getRawType();
            }
            if (clazz != null) {
                errorMsg = "O erro pode ser evitado se a classe " + clazz.getName()
                        + " possuir um construtor pblico sem argumentos";
                propertyValue = clazz.newInstance();
                setPropertyValue(nestedProperty, propertyValue);
            }
        } catch (Exception e) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + canonicalName, errorMsg);
        }

    }

    // lookup cached sub-BeanWrapper, create new one if not found
    ExtendedBeanWrapper nestedBw = (ExtendedBeanWrapper) this.nestedBeanWrappers.get(canonicalName);
    if (nestedBw == null || nestedBw.getWrappedInstance() != propertyValue) {
        if (logger.isDebugEnabled()) {
            logger.debug("Creating new nested BeanWrapper for property '" + canonicalName + "'");
        }
        nestedBw = new ExtendedBeanWrapper(propertyValue,
                this.nestedPath + canonicalName + NESTED_PROPERTY_SEPARATOR, this);
        // inherit all type-specific PropertyEditors
        if (this.customEditors != null) {
            for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                if (entry.getKey() instanceof Class) {
                    Class requiredType = (Class) entry.getKey();
                    PropertyEditor editor = (PropertyEditor) entry.getValue();
                    nestedBw.registerCustomEditor(requiredType, editor);
                } else if (entry.getKey() instanceof String) {
                    String editorPath = (String) entry.getKey();
                    int pos = getNestedPropertySeparatorIndex(editorPath, false);
                    if (pos != -1) {
                        String editorNestedProperty = editorPath.substring(0, pos);
                        String editorNestedPath = editorPath.substring(pos + 1);
                        if (editorNestedProperty.equals(canonicalName)
                                || editorNestedProperty.equals(propertyName)) {
                            CustomEditorHolder editorHolder = (CustomEditorHolder) entry.getValue();
                            nestedBw.registerCustomEditor(editorHolder.getRegisteredType(), editorNestedPath,
                                    editorHolder.getPropertyEditor());
                        }
                    }
                }
            }
        }
        this.nestedBeanWrappers.put(canonicalName, nestedBw);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Using cached nested BeanWrapper for property '" + canonicalName + "'");
        }
    }
    return nestedBw;
}

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

protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }/* ww w .jav  a2s  . co  m*/
    if (logger.isDebugEnabled())
        logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class ["
                + this.object.getClass().getName() + "]");
    try {
        Object value = pd.getReadMethod().invoke(this.object, (Object[]) null);
        Type genericReturnType = pd.getReadMethod().getGenericReturnType();
        Class rawReturnType = pd.getReadMethod().getReturnType();
        if (tokens.keys != null) {
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];

                //cria listas sob demanda.. no  mais necessrio utilizar o ListSet no pojo
                Class originalClass = null;
                if (value != null) {
                    originalClass = value.getClass();
                }
                if (value == null && rawReturnType != null && genericReturnType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                    if (Map.class.isAssignableFrom(rawReturnType)) {
                        value = new LinkedHashMap();
                        pd.getWriteMethod().invoke(this.object, value);
                    } else if (List.class.isAssignableFrom(rawReturnType)
                            || Set.class.isAssignableFrom(rawReturnType)) {
                        Type type = parameterizedType.getActualTypeArguments()[0];
                        value = new ListSet(type instanceof Class ? (Class) type
                                : (Class) ((ParameterizedType) type).getRawType());
                        pd.getWriteMethod().invoke(this.object, value);
                    }
                }
                //fim da criacao sob demanda

                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    value = Array.get(value, Integer.parseInt(key));
                } else if (value instanceof List) {
                    List list = (List) value;
                    try {
                        value = list.get(Integer.parseInt(key));
                    } catch (IndexOutOfBoundsException e) {
                        //tentar instanciar um bean da lista
                        String extraMessage = "";
                        if (genericReturnType instanceof ParameterizedType) {
                            ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                            Type type = parameterizedType.getActualTypeArguments()[0];
                            if (type instanceof Class) {
                                Class clazz = (Class) type;
                                extraMessage = "A classe " + clazz.getName()
                                        + " no possui um construtor publico sem argumentos";
                                try {
                                    value = clazz.newInstance();
                                    int index = Integer.parseInt(key);
                                    int insertNulls = index - list.size();
                                    while (insertNulls > 0) { // 11/06/2012
                                        list.add(null);
                                        insertNulls--;
                                    }

                                    list.add(index, value); // CDIGO 15/01/2007
                                } catch (InstantiationException e1) {
                                    throw new RuntimeException(
                                            "Aconteceu um erro ao acessar um elemento da classe "
                                                    + originalClass.getName() + " propriedade " + propertyName
                                                    + "  No foi possvel instanciar um bean para preencher a lista. "
                                                    + extraMessage,
                                            e);
                                }
                            }
                        } else if (originalClass != null) {
                            throw new RuntimeException("Aconteceu um erro ao acessar um elemento da classe "
                                    + originalClass.getName() + " propriedade " + propertyName
                                    + "  Sugesto: Utilize uma lista que cresa quando for necessrio como o ListSet ou no instancie nenhum objeto para essa propriedade",
                                    e);
                        } else {
                            throw e;
                        }
                    }
                } else if (value instanceof Set) {
                    // apply index to Iterator in case of a Set
                    //TODO CRIAR AUTOMATICAMENTE O BEAN DO SET
                    Set set = (Set) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'"
                                        + "  Sugesto: Utilize o ListSet ou no instancie nenhum objeto");
                    }
                    Iterator it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    if (!(genericReturnType instanceof ParameterizedType)) {
                        throw new NotParameterizedTypeException(
                                "Path direciona a um Map no parameterizado com generics. " + " Propriedade '"
                                        + this.nestedPath + propertyName + "' da classe ["
                                        + this.rootObject.getClass().getName() + "]");
                    }
                    ParameterizedType parameterizedType = ((ParameterizedType) genericReturnType);
                    Type mapKeyType = parameterizedType.getActualTypeArguments()[0];
                    Type mapValueType = parameterizedType.getActualTypeArguments()[1];
                    Class rawKeyType = mapKeyType instanceof Class ? (Class) mapKeyType
                            : (Class) ((ParameterizedType) mapKeyType).getRawType();
                    Class rawValueType = mapValueType instanceof Class ? (Class) mapValueType
                            : (Class) ((ParameterizedType) mapValueType).getRawType();
                    Object objectKey = doTypeConversionIfNecessary(key, rawKeyType);
                    Map map = (Map) value;
                    value = map.get(objectKey);
                    if (value == null && List.class.isAssignableFrom(rawValueType)) {
                        List mapValue;
                        try {
                            Type listType = ((ParameterizedType) mapValueType).getActualTypeArguments()[0];
                            mapValue = new ListSet(listType instanceof Class ? (Class) listType
                                    : (Class) ((ParameterizedType) listType).getRawType());
                        } catch (ClassCastException e) {
                            throw new RuntimeException(
                                    "Na path " + propertyName + " um mapa contm uma lista no parametrizada");
                        }
                        map.put(objectKey, mapValue);
                        value = mapValue;
                    }
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
            }
        }
        return value;
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (IllegalAccessException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", 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 . jav a 2 s.c  om
        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

private Type getPropertyType(PropertyTokenHolder tokens) {
    String propertyName = tokens.canonicalName;
    PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }/*w  w  w.  j  a  va  2s .co  m*/
    if (logger.isDebugEnabled())
        logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class ["
                + this.object.getClass().getName() + "]");
    try {
        Type type = pd.getReadMethod().getGenericReturnType();
        if (tokens.keys != null) {
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                if (type == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (type instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) type;
                    Class clazz = (Class) parameterizedType.getRawType();
                    if (Map.class.isAssignableFrom(clazz)) {
                        type = parameterizedType.getActualTypeArguments()[1];
                    } else if (Collection.class.isAssignableFrom(clazz)) {
                        type = parameterizedType.getActualTypeArguments()[0];
                    } else {
                        throw new RuntimeException("Tipo desconhecido " + parameterizedType);
                    }
                } else if (type instanceof Class && ((Class) type).isArray()) {
                    return type;
                } else {
                    throw new RuntimeException("Implementar converso!!!");
                }
            }
        }
        return type;
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    }
}

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

private Object getPropertyHoldingValue(PropertyTokenHolder tokens) {
    // Apply indexes and map keys: fetch value for all keys but the last one.
    Assert.state(tokens.keys != null, "No token keys");
    PropertyTokenHolder getterTokens = new PropertyTokenHolder(tokens.actualName);
    getterTokens.canonicalName = tokens.canonicalName;
    getterTokens.keys = new String[tokens.keys.length - 1];
    System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);

    Object propValue;//from   w  w w.  ja va  2 s  .c  om
    try {
        propValue = getPropertyValue(getterTokens);
    } catch (NotReadablePropertyException ex) {
        throw new NotWritablePropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                "Cannot access indexed value in property referenced " + "in indexed property path '"
                        + tokens.canonicalName + "'",
                ex);
    }

    if (propValue == null) {
        // null map value case
        if (isAutoGrowNestedPaths()) {
            int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
            getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
            propValue = setDefaultValue(getterTokens);
        } else {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + tokens.canonicalName + "': returned null");
        }
    }
    return propValue;
}

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

@SuppressWarnings("unchecked")
@Nullable/*  w  w  w.  ja v  a  2s  .c  om*/
protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyHandler ph = getLocalPropertyHandler(actualName);
    if (ph == null || !ph.isReadable()) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }
    try {
        Object value = ph.getValue();
        if (tokens.keys != null) {
            if (value == null) {
                if (isAutoGrowNestedPaths()) {
                    value = setDefaultValue(new PropertyTokenHolder(tokens.actualName));
                } else {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                }
            }
            String indexedPropertyName = tokens.actualName;
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];
                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    int index = Integer.parseInt(key);
                    value = growArrayIfNecessary(value, index, indexedPropertyName);
                    value = Array.get(value, index);
                } else if (value instanceof List) {
                    int index = Integer.parseInt(key);
                    List<Object> list = (List<Object>) value;
                    growCollectionIfNecessary(list, index, indexedPropertyName, ph, i + 1);
                    value = list.get(index);
                } else if (value instanceof Set) {
                    // Apply index to Iterator in case of a Set.
                    Set<Object> set = (Set<Object>) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'");
                    }
                    Iterator<Object> it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    Map<Object, Object> map = (Map<Object, Object>) value;
                    Class<?> mapKeyType = ph.getResolvableType().getNested(i + 1).asMap().resolveGeneric(0);
                    // 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);
                    value = map.get(convertedMapKey);
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
                indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX;
            }
        }
        return value;
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (TypeMismatchException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (Exception ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    }
}