Example usage for org.springframework.beans BeanWrapper getPropertyDescriptor

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

Introduction

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

Prototype

PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException;

Source Link

Document

Obtain the property descriptor for a specific property of the wrapped object.

Usage

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

private static Object processForNumber(Object object, String propertyName, Object propValue) {
    BeanWrapper wrapper = new BeanWrapperImpl(object);
    PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(propertyName);
    Method method = descriptor.getReadMethod();
    TypeConversion typeConversion = method.getAnnotation(TypeConversion.class);
    if (typeConversion != null) {
        String convertor = typeConversion.converter();
        if (convertor.equalsIgnoreCase(FrameworkConst.STRUTS_DECIMAL_CONVERTER)) {
            DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
            return df.format(propValue);
        } else {/*from   w ww  .ja v  a 2s  .co  m*/
            return propValue;
        }
    } else {
        if (propValue instanceof Double || propValue instanceof Float) {
            DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
            return df.format(propValue);
        } else {
            return propValue;
        }
    }
}

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

/**
 * /*w  w  w.j a v a  2 s.co  m*/
 * @param obj
 * @param propertyName
 * @return null if not found
 */
public static PropertyDescriptor getPropertyDescriptor(Object obj, String propertyName) {
    PropertyDescriptor descriptor = null;
    BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
    try {
        descriptor = beanWrapper.getPropertyDescriptor(propertyName);
    } catch (Exception e) {
    }
    return descriptor;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Retrieves a property of the given class of the specified name and type
 * @param clazz The class to retrieve the property from
 * @param propertyName The name of the property
 * @param propertyType The type of the property
 *
 * @return A PropertyDescriptor instance or null if none exists
 *///from   w  w w .j av  a2 s.  c o m
public static PropertyDescriptor getProperty(Class clazz, String propertyName, Class propertyType) {
    if (clazz == null || propertyName == null || propertyType == null)
        return null;

    try {
        BeanWrapper wrapper = new BeanWrapperImpl(clazz.newInstance());
        PropertyDescriptor pd = wrapper.getPropertyDescriptor(propertyName);
        if (pd.getPropertyType().equals(propertyType)) {
            return pd;
        } else {
            return null;
        }
    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return null;
    }
}

From source file:org.grails.datastore.mapping.query.order.ManualEntityOrdering.java

public List applyOrder(List results, Query.Order order) {
    final String name = order.getProperty();

    @SuppressWarnings("hiding")
    final PersistentEntity entity = getEntity();
    PersistentProperty property = entity.getPropertyByName(name);
    if (property == null) {
        final PersistentProperty identity = entity.getIdentity();
        if (name.equals(identity.getName())) {
            property = identity;/*from  w  ww .java  2s. c  om*/
        }
    }

    if (property != null) {
        final PersistentProperty finalProperty = property;
        Collections.sort(results, new Comparator() {

            public int compare(Object o1, Object o2) {

                if (entity.isInstance(o1) && entity.isInstance(o2)) {
                    final String propertyName = finalProperty.getName();
                    Method readMethod = cachedReadMethods.get(propertyName);
                    if (readMethod == null) {
                        BeanWrapper b = PropertyAccessorFactory.forBeanPropertyAccess(o1);
                        final PropertyDescriptor pd = b.getPropertyDescriptor(propertyName);
                        if (pd != null) {
                            readMethod = pd.getReadMethod();
                            if (readMethod != null) {
                                ReflectionUtils.makeAccessible(readMethod);
                                cachedReadMethods.put(propertyName, readMethod);
                            }
                        }
                    }

                    if (readMethod != null) {
                        final Class<?> declaringClass = readMethod.getDeclaringClass();
                        if (declaringClass.isInstance(o1) && declaringClass.isInstance(o2)) {
                            Object left = ReflectionUtils.invokeMethod(readMethod, o1);
                            Object right = ReflectionUtils.invokeMethod(readMethod, o2);

                            if (left == null && right == null)
                                return 0;
                            if (left != null && right == null)
                                return 1;
                            if (left == null)
                                return -1;
                            if ((left instanceof Comparable) && (right instanceof Comparable)) {
                                return ((Comparable) left).compareTo(right);
                            }
                        }
                    }
                }
                return 0;
            }
        });
    }

    if (order.getDirection() == Query.Order.Direction.DESC) {
        results = reverse(results);
    }

    return results;
}

From source file:com.alibaba.citrus.service.form.impl.GroupImpl.java

/**
 * group/*w w  w .j  ava 2s  .  c  om*/
 * <p>
 * <code>isValidated()</code><code>false</code>group
 * </p>
 */
public void setProperties(Object object) {
    if (!isValidated() || object == null) {
        return;
    }

    if (isValid()) {
        if (log.isDebugEnabled()) {
            log.debug("Set validated properties of group \"" + getName() + "\" to object "
                    + ObjectUtil.identityToString(object));
        }

        BeanWrapper bean = new BeanWrapperImpl(object);
        getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

        for (Field field : getFields()) {
            String propertyName = field.getFieldConfig().getPropertyName();

            if (bean.isWritableProperty(propertyName)) {
                PropertyDescriptor pd = bean.getPropertyDescriptor(propertyName);
                MethodParameter mp = BeanUtils.getWriteMethodParameter(pd);
                Object value = field.getValueOfType(pd.getPropertyType(), mp, null);

                bean.setPropertyValue(propertyName, value);
            } else {
                log.debug("No writable property \"{}\" found in type {}", propertyName,
                        object.getClass().getName());
            }
        }
    } else {
        throw new InvalidGroupStateException("Attempted to call setProperties from an invalid input");
    }
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Overwrites the values of the bean in parameter with the form values
  * @param source/*www.ja va 2s.c  o m*/
  * @return
  */
public <R> void mergeInto(R source) {

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(source);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in source");
        }
    }
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * Creates a Bean of the given class type from the form values
 * @param cls class of the result bean//w ww. j  a va  2  s .c  o m
 * @param <R> type of the bean
 * @return
 */
public <R> R deriveBean(Class<R> cls) {

    R result = null;
    try {
        result = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        logger.log(Level.WARNING, "Could not instantiate derived bean", e);
        return null;
    }

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(result);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in bean");
        }

    }

    return result;
}

From source file:com.seovic.core.DynamicObject.java

/**
 * Update specified target from this object.
 *
 * @param target  target object to update
 *///from  w w  w .jav a2  s. c o m
public void update(Object target) {
    if (target == null) {
        throw new IllegalArgumentException("Target to update cannot be null");
    }

    BeanWrapper bw = new BeanWrapperImpl(target);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    for (Map.Entry<String, Object> property : m_properties.entrySet()) {
        String propertyName = property.getKey();
        Object value = property.getValue();

        if (value instanceof Map) {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) {
                value = new DynamicObject((Map<String, Object>) value);
            }
        }

        if (value instanceof DynamicObject) {
            ((DynamicObject) value).update(bw.getPropertyValue(propertyName));
        } else {
            bw.setPropertyValue(propertyName, value);
        }
    }
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Creates a Bean with the given class from the from values
  * @param object Source object we're taking the values from
  * @return this object//from w ww  .ja va  2s .  c om
  */
public Form<T> fillFromBean(Object object) {

    BeanWrapper beanWrapper = new BeanWrapperImpl(object);
    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);
                String strPropValue = propertyValue != null ? propertyValue.toString() : null;

                // If the field hasn't got a value already, clear the potential errors as they will be meaningless
                // and the set the field value
                if (field.value() == null) {
                    field.value(strPropValue);
                    field.errors().clear();
                }
            }
        } catch (InvalidPropertyException e) {
            logger.log(Level.WARNING,
                    "Could not find property " + fieldName + " for bean " + object.getClass().getName(), e);
            continue;
        }

    }
    return this;
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * bind all or only the specified properties of the object to this Form. 
 * Validation is automatically performed after the binding, validating all or only the specified properties. 
 * The result of the validation is available by calling form.hasErrors() and/or field.hasErrors() 
 * /*  w w  w. j av  a2  s  .  co  m*/
 * @param object
 * @param properties
 * @return
 */
public Form<T> bindObject(T object, String... properties) {
    if (object != null) {
        this.object = object;
        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
        for (Field field : fields()) {
            // if applicable, remove the fieldPrefix to get the bean field name 
            String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length())
                    : field.name();
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);

                String strPropValue = propertyValue != null
                        ? (propertyValue instanceof java.time.Instant
                                ? format((java.time.Instant) propertyValue)
                                : propertyValue.toString())
                        : null;
                field.value(strPropValue);
            }
        }
    }
    return this;
}