Example usage for org.springframework.beans BeanWrapper getPropertyValue

List of usage examples for org.springframework.beans BeanWrapper getPropertyValue

Introduction

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

Prototype

@Nullable
Object getPropertyValue(String propertyName) throws BeansException;

Source Link

Document

Get the current value of the specified property.

Usage

From source file:org.jdal.vaadin.ui.FormUtils.java

/**
 * Add a link on primary and dependent ComboBoxes by property name. 
 * When selection changes on primary use propertyName to get a Collection and fill dependent ComboBox with it
 * @param primary ComboBox when selection changes
 * @param dependent ComboBox that are filled with collection   
 * @param propertyName the property name for get the collection from primary selected item
 * @param addNull if true, add a null as first combobox item
 *//*from   w w w  . java2  s . c  o m*/
@SuppressWarnings("rawtypes")
public static void link(final ComboBox primary, final ComboBox dependent, final String propertyName,
        final boolean addNull) {

    primary.addValueChangeListener(new ValueChangeListener() {

        public void valueChange(ValueChangeEvent event) {
            Object selected = event.getProperty().getValue();
            if (selected != null) {
                BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(selected);
                if (wrapper.isReadableProperty(propertyName)) {
                    Collection items = (Collection) wrapper.getPropertyValue(propertyName);
                    dependent.removeAllItems();

                    if (addNull)
                        dependent.addItem(null);

                    for (Object item : items)
                        dependent.addItem(item);
                } else {
                    log.error("Can't write on propety '" + propertyName + "' of class: '" + selected.getClass()
                            + "'");
                }
            }

        }
    });
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * /*  w  ww . ja  v  a2s  .  c o  m*/
 * @param o
 *        the object to inspect
 * @param ignore
 *        a set of property names to ignore (optional)
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = new BeanWrapperImpl(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:hu.petabyte.redflags.engine.util.MappingUtils.java

/**
 * Sets the value of a bean's property, using the given wrapper. The
 * property can be a deeper one, e.g. "a.b.c.d". If any of a, b or c
 * properties is null, the method will call an empty constructor for its
 * static type. If any error occurs, setDeepProperty will write it to the
 * LOG and returns false.//from ww w  .  ja v  a 2  s .co m
 *
 * @param wrapper
 *            Wrapper of the root object.
 * @param property
 *            The property needs to be set.
 * @param value
 *            The new value of the property.
 * @return True if property setting was successful, false on error.
 */
public static synchronized boolean setDeepProperty(BeanWrapper wrapper, String property, Object value) {
    try {
        // this will help calling a constructor:
        ExpressionParser parser = new SpelExpressionParser();

        // go thru property path elements:
        int offset = 0;
        while ((offset = property.indexOf(".", offset + 1)) > -1) {
            String currentProperty = property.substring(0, offset);

            // if current property is null:
            if (null == wrapper.getPropertyValue(currentProperty)) {
                String className = wrapper.getPropertyType(currentProperty).getName();

                // build up a constructor call:
                Expression exp = parser.parseExpression(String.format("new %s()", className));

                // LIMITATIONS:
                // 1) uses static type
                // 2) needs defined empty constructor

                // run it:
                Object newObject = exp.getValue();

                // and set the property:
                wrapper.setPropertyValue(currentProperty, newObject);
            }
        }

        // finally, set the destination property:
        wrapper.setPropertyValue(property, value);
        return true;
    } catch (Exception ex) {
        LOG.error("Could not set property '{}'", property);
        LOG.debug("Exception: ", ex);
        return false;
    }
}

From source file:org.kmnet.com.fw.web.el.Functions.java

/**
 * build query string from map or bean./*from   w w w.ja  va2 s. c o m*/
 * <p>
 * query string is encoded with "UTF-8".
 * </p>
 * @param params map or bean
 * @return query string. returns empty string if <code>params</code> is <code>null</code> or empty string or
 *         {@link Iterable} or {@link BeanUtils#isSimpleValueType(Class)}.
 */
@SuppressWarnings("unchecked")
public static String query(Object params) {
    if (params == null) {
        return "";
    }
    Class<?> clazz = params.getClass();
    if (clazz.isArray() || params instanceof Iterable || BeanUtils.isSimpleValueType(clazz)) {
        return "";
    }

    String query;
    if (params instanceof Map) {
        query = mapToQuery((Map<String, Object>) params);
    } else {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(params);
        PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
        for (PropertyDescriptor pd : pds) {
            String name = pd.getName();
            if (!"class".equals(name)) {
                Object value = beanWrapper.getPropertyValue(name);
                map.put(name, value);
            }
        }
        query = mapToQuery(map, beanWrapper);
    }
    return query;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //ww w. j a va 2  s.  co  m
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //ww w  .j a v  a2  s.c om
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @param serializeIgnore if <em>true</em> test for the {@link SerializeIgnore}
 * annotation for ignoring properties
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore, boolean serializeIgnore) {
    if (o == null) {
        return null;
    }
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        if (serializeIgnore) {
            Method getter = prop.getReadMethod();
            if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                continue;
            }
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * search String variavle inside the given object, if Empty then change it to Null.
 * /*from  ww  w .ja va  2  s.  c o  m*/
 * @param obj
 *            = this object will not be changed, it will be close.
 * @return
 */
public static Object changeEmptyStrToNull(Object obj) {
    Object newObj = obj;
    // J.printLine(getAllExProperties(obj, " ", ".vo."));
    // try {
    // newObj = BeanUtils.cloneBean(obj);
    // } catch (Exception e1) {
    // e1.printStackTrace();
    // }
    //
    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());
            if (propertyValueO1 instanceof String && StringUtils.isEmpty((String) propertyValueO1)) {
                // password is null. it will not come in because it is not
                // instance of String
                // J.printNegetif(proDescriptorsO1[i].getName()+"..."+(String)propertyValueO1);
                beanO1.setPropertyValue(proDescriptorsO1[i].getName(), null);

            }
        } catch (Exception e) {
            // [exec] java.lang.IllegalAccessException: Class
            // org.apache.commons.beanutils.BeanUtilsBean can not
            // access a member of class
            // com.foremobile.gateway.usermgmt.vo.User with modifiers
            // "private"
            // [exec] at sun.reflect.Reflection.ensureMemberAccess(Unknown
            // Source)
        }
    }

    return newObj;
}

From source file:org.shept.util.BeanUtilsExtended.java

/**
 * Find all occurrences of targetClass in targetObject.
 * Be careful. This stuff may be recursive !
 * Should be improved to prevent endless recursive loops.
 * //from www  .j a  v a 2 s.  c o m
 * @param
 * @return
 *
 * @param targetObject
 * @param targetClass
 * @param nestedPath
 * @return
 * @throws Exception 
 */
public static Map<String, ?> findNestedPaths(Object targetObject, Class<?> targetClass, String nestedPath,
        List<String> ignoreList, Set<Object> visited, int maxDepth) throws Exception {

    Assert.notNull(targetObject);
    Assert.notNull(targetClass);
    Assert.notNull(ignoreList);
    HashMap<String, Object> nestedPaths = new HashMap<String, Object>();
    if (maxDepth <= 0) {
        return nestedPaths;
    }

    nestedPath = (nestedPath == null ? "" : nestedPath);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    PropertyDescriptor[] props = bw.getPropertyDescriptors();

    for (PropertyDescriptor pd : props) {
        Class<?> clazz = pd.getPropertyType();
        if (clazz != null && !clazz.equals(Class.class) && !clazz.isAnnotation() && !clazz.isPrimitive()) {
            Object value = null;
            String pathName = pd.getName();
            if (!ignoreList.contains(pathName)) {
                try {
                    value = bw.getPropertyValue(pathName);
                } catch (Exception e) {
                } // ignore any exceptions here
                if (StringUtils.hasText(nestedPath)) {
                    pathName = nestedPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + pathName;
                }
                // TODO break up this stuff into checking and excecution a la ReflectionUtils
                if (targetClass.isAssignableFrom(clazz)) {
                    nestedPaths.put(pathName, value);
                }
                // exclude objects already visited from further inspection to prevent circular references
                // unfortunately this stuff isn't fool proof as there are ConcurrentModificationExceptions
                // when adding objects to the visited list
                if (value != null && !isInstanceVisited(visited, value)) {
                    nestedPaths.putAll(
                            findNestedPaths(value, targetClass, pathName, ignoreList, visited, maxDepth - 1));
                }
            }
        }
    }
    return nestedPaths;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Copy non-null bean properties from one object to another.
 * //from   w ww  .j  a  v a2s. c o  m
 * @param src the object to copy values from
 * @param dest the object to copy values to
 * @param ignore a set of property names to ignore (optional)
 * @param emptyStringToNull if <em>true</em> then String values that 
 * are empty or contain only whitespace will be treated as if they
 * where <em>null</em>
 */
public static void copyBeanProperties(Object src, Object dest, Set<String> ignore, boolean emptyStringToNull) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper to = PropertyAccessorFactory.forBeanPropertyAccess(dest);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null || (emptyStringToNull && (propValue instanceof String)
                && !StringUtils.hasText((String) propValue))) {
            continue;
        }
        if (to.isWritableProperty(propName)) {
            to.setPropertyValue(propName, propValue);
        }
    }
}

From source file:com.aw.support.beans.BeanUtils.java

public static Object copyProperties(Object source, Object target, String[] propertyNamesToIgnore,
        boolean ignoreProxy, boolean ignoreCollections) {
    List<String> propertyNamesToIgnoreList = propertyNamesToIgnore == null ? Collections.EMPTY_LIST
            : Arrays.asList(propertyNamesToIgnore);
    BeanWrapper sourceWrap = new BeanWrapperImpl(source);
    BeanWrapper targetWrap = new BeanWrapperImpl(target);
    for (PropertyDescriptor propDescriptor : sourceWrap.getPropertyDescriptors()) {
        String propName = propDescriptor.getName();
        //chequear que no esta en la lista a ignorar
        if (propertyNamesToIgnoreList.contains(propName))
            continue;
        //chequear que se puede leer
        if (!sourceWrap.isReadableProperty(propName))
            continue;
        //chequear que se puede escribir
        if (!targetWrap.isWritableProperty(propName))
            continue;

        Object sourceValue = sourceWrap.getPropertyValue(propName);

        //chequear que objeto no es un proxy
        if (ignoreProxy && sourceValue != null && Proxy.isProxyClass(sourceValue.getClass()))
            continue;

        //chequear que objeto no una collection
        if (ignoreCollections && sourceValue instanceof Collection)
            continue;

        targetWrap.setPropertyValue(propName, sourceValue);
    }/*from   w w w .  j  a  v  a  2s. c o m*/
    return target;
}