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.jdto.spring.BeanWrapperBeanModifier.java

/**
 * Set a property using the property path invoking a spring framework {@link BeanWrapper}.
 * @param propertyPath/*w  ww.j av  a2s.  c o m*/
 * @param value
 * @param instance 
 */
@Override
public void doWritePropertyValue(String propertyPath, Object value, Object instance) {
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);

    //check and make up for missing association parts.
    StringBuilder builder = new StringBuilder();

    String[] subProps = StringUtils.split(propertyPath, '.');

    //go through all the parts but one
    for (int i = 0; i < subProps.length - 1; i++) {
        String prop = subProps[i];

        if (i > 0) {
            builder.append(".");
        }

        builder.append(prop);

        Object partialValue = beanWrapper.getPropertyValue(builder.toString());
        if (partialValue == null) {
            //make up for it
            Class propCls = beanWrapper.getPropertyType(builder.toString());
            Object madeUpValue = BeanClassUtils.createInstance(propCls);
            if (madeUpValue != null) {
                if (beanWrapper.isWritableProperty(builder.toString())) {
                    beanWrapper.setPropertyValue(builder.toString(), madeUpValue);
                }
            }
        }
    }

    if (!beanWrapper.isWritableProperty(propertyPath)) {
        logger.info("Cannot write property path " + propertyPath + " of bean", instance);
        return;
    }

    //this can be improved by registering property editors on the bean wrapper
    //at moment this approach is not so simple as the current functionality.
    //nevertheless on the future this situation may change.
    Class expectedType = beanWrapper.getPropertyType(propertyPath);
    value = ValueConversionHelper.applyCompatibilityLogic(expectedType, value);

    beanWrapper.setPropertyValue(propertyPath, value);
}

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

/**
 * fields//from   w w  w. j a va 2 s.  c  o m
 * <p>
 * <code>isValidated()</code><code>true</code>group
 * </p>
 */
public void mapTo(Object object) {
    if (isValidated() || object == null) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Mapping properties to fields: group=\"{}\", object={}", getName(),
                ObjectUtil.identityToString(object));
    }

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

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

        if (bean.isReadableProperty(propertyName)) {
            Object propertyValue = bean.getPropertyValue(propertyName);
            Class<?> propertyType = bean.getPropertyType(propertyName);
            PropertyEditor editor = bean.findCustomEditor(propertyType, propertyName);

            if (editor == null) {
                editor = BeanUtils.findEditorByConvention(propertyType);
            }

            if (editor == null) {
                if (propertyType.isArray() || CollectionFactory.isApproximableCollectionType(propertyType)) {
                    field.setValues((String[]) bean.convertIfNecessary(propertyValue, String[].class));
                } else {
                    field.setValue(bean.convertIfNecessary(propertyValue, String.class));
                }
            } else {
                editor.setValue(propertyValue);
                field.setValue(editor.getAsText());
            }
        } else {
            log.debug("No readable property \"{}\" found in type {}", propertyName,
                    object.getClass().getName());
        }
    }
}

From source file:org.obiba.onyx.core.domain.participant.Participant.java

/**
 * Returns the value of an essential participant attribute.
 * @param attributeName The attribute name.
 * @return The value of the specified attribute (or <code>null</code> if none assigned).
 * @throws IllegalArgumentException if <code>attributeName</code> is <code>null</code>
 *///from w  w w. ja va 2 s  .  c  o m
public Data getEssentialAttributeValue(String attributeName) {
    Assert.notNull("Null attribute name", attributeName);

    BeanWrapper participantBean = new BeanWrapperImpl(this);
    String essentialAttributeFieldName = getEssentialAttributeDataFieldName(attributeName);
    if (essentialAttributeFieldName != null) {
        return (Data) participantBean.getPropertyValue(essentialAttributeFieldName);
    }
    return null;

}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public String getNotNullNonPrimaryKeyEqualFieldComma(Object object) {
    StringBuilder sb = new StringBuilder();
    BeanWrapper bean = new BeanWrapperImpl(object);
    for (Field field : getColumnFields()) {
        Column column = field.getAnnotation(Column.class);
        if (!column.primaryKey()) {
            Object value = bean.getPropertyValue(field.getName());
            if (value != null) {
                if (sb.length() > 0)
                    sb.append(", ");
                // sb.append(ColumnAnnotation.getName(field, column)).append(" = ").append(" #{").append(field.getName()).append("}");
                sb.append(TokenMaker.fieldEqual(field, column));
            }/*from ww  w .j  a  va 2s. c  om*/
        }
    }
    return sb.toString();
}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public FieldList getNotNullNonAutoIncrementFieldList(Object object) {
    FieldList fieldList = new FieldList();
    BeanWrapper bean = new BeanWrapperImpl(object);
    for (Field field : getColumnFields()) {
        Column column = field.getAnnotation(Column.class);
        if (!column.autoIncrement()) {
            Object value = bean.getPropertyValue(field.getName());
            if (value != null) {
                fieldList.add(field.getName(), ColumnAnnotation.getName(field, column));
            }//from  w ww.  j  av  a2  s  .c  om
        }
    }
    return fieldList;
}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public String getNotNullNonPrimaryKeyEqualPlusFieldComma(Object object) {
    String columnName = null;/*from w  ww. j  ava  2s .  co m*/
    StringBuilder sb = new StringBuilder();
    BeanWrapper bean = new BeanWrapperImpl(object);
    for (Field field : getColumnFields()) {
        Column column = field.getAnnotation(Column.class);
        if (!column.primaryKey()) {
            Object value = bean.getPropertyValue(field.getName());
            if (value != null) {
                if (sb.length() > 0)
                    sb.append(", ");
                columnName = ColumnAnnotation.getName(field, column);
                // sb.append(columnName).append(" = ").append(columnName).append(" + #{").append(field.getName()).append("}");
                sb.append(columnName).append(" = ").append(columnName).append(" + ")
                        .append(TokenMaker.mybatisToken(field));
            }
        }
    }
    return sb.toString();
}

From source file:org.ambraproject.user.service.UserServiceImpl.java

@Override
public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) {
    UserProfile display = new UserProfile();
    copyFields(userProfile, display);//  ww w . jav  a  2s .  co  m
    if (!showPrivateFields) {
        log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName());
        display.setOrganizationName(null);
        display.setOrganizationType(null);
        display.setPostalAddress(null);
        display.setPositionType(null);
    }

    //escape html in all string fields
    BeanWrapper wrapper = new BeanWrapperImpl(display);
    for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) {
        if (String.class.isAssignableFrom(property.getPropertyType())) {
            String name = property.getName();
            wrapper.setPropertyValue(name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name)));
        }
    }

    return display;
}

From source file:ru.ilb.common.jpa.tools.DescriptorUtils.java

public void fixInverseLinks(Object entity) {
    final BeanWrapper src = new BeanWrapperImpl(entity);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    ClassDescriptor cd = entityManager.unwrap(Session.class).getDescriptor(entity);
    if (cd == null) {
        return;//from  w  w w.  j a va2 s  .  c o m
    }
    for (java.beans.PropertyDescriptor pd : pds) {
        DatabaseMapping dm = cd.getMappingForAttributeName(pd.getName());
        if (dm != null) {
            if (dm instanceof OneToManyMapping) {
                OneToManyMapping dmOtM = (OneToManyMapping) dm;
                if (dmOtM.getMappedBy() != null) {
                    List srcValue = (List) src.getPropertyValue(pd.getName());
                    if (srcValue != null) {
                        for (Object v : srcValue) {
                            final BeanWrapper srcv = new BeanWrapperImpl(v);
                            srcv.setPropertyValue(dmOtM.getMappedBy(), entity);
                            fixInverseLinks(v);
                        }
                    }

                }
            }
            if (dm instanceof OneToOneMapping) {
                OneToOneMapping dmOtO = (OneToOneMapping) dm;
                if (dmOtO.getMappedBy() != null) {
                    Object srcValue = src.getPropertyValue(pd.getName());
                    if (srcValue != null) {
                        final BeanWrapper srcv = new BeanWrapperImpl(srcValue);
                        srcv.setPropertyValue(dmOtO.getMappedBy(), entity);
                        fixInverseLinks(srcValue);
                    }

                }
            }
        }

    }
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java

@Test
public void testGenericMapElement() {
    GenericBean<?> gb = new GenericBean<Object>();
    gb.setShortMap(new HashMap<Short, Integer>());
    BeanWrapper bw = new JuffrouSpringBeanWrapper(gb);
    bw.setPropertyValue("shortMap[4]", "5");
    assertEquals(new Integer(5), bw.getPropertyValue("shortMap[4]"));
    assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java

@Test
public void testGenericListOfMapsWithElementConversion() throws MalformedURLException {
    GenericBean<String> gb = new GenericBean<String>();
    List<Map<Integer, Long>> list = new LinkedList<Map<Integer, Long>>();
    list.add(new HashMap<Integer, Long>());
    gb.setListOfMaps(list);//w  w  w. jav a 2 s .  com
    BeanWrapper bw = new JuffrouSpringBeanWrapper(gb);
    bw.setPropertyValue("listOfMaps[0][10]", "5");
    assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]"));
    assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10));
}