Example usage for org.springframework.beans BeanWrapper setPropertyValue

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

Introduction

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

Prototype

void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;

Source Link

Document

Set the specified value as current property value.

Usage

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData//from   w w  w .  j a va2s .  com
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
        String column = lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    return mappedObject;
}

From source file:com.clican.pluto.common.support.spring.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>// w  w w. j a  va  2s .c o  m
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.emc.ecs.sync.config.ConfigWrapper.java

public C parse(CommandLine commandLine, String prefix) {
    try {/*from   w w w  .  j av  a 2s. c  o m*/
        C object = getTargetClass().newInstance();
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);

        for (String name : propertyNames()) {
            ConfigPropertyWrapper propertyWrapper = getPropertyWrapper(name);
            if (!propertyWrapper.isCliOption())
                continue;

            org.apache.commons.cli.Option option = propertyWrapper.getCliOption(prefix);

            if (commandLine.hasOption(option.getLongOpt())) {

                Object value = commandLine.getOptionValue(option.getLongOpt());
                if (propertyWrapper.getDescriptor().getPropertyType().isArray())
                    value = commandLine.getOptionValues(option.getLongOpt());

                if (Boolean.class == propertyWrapper.getDescriptor().getPropertyType()
                        || "boolean".equals(propertyWrapper.getDescriptor().getPropertyType().getName()))
                    value = Boolean.toString(!propertyWrapper.isCliInverted());

                beanWrapper.setPropertyValue(name, value);
            }
        }

        return object;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gzj.tulip.jade.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>/*  w ww . j  a v a  2  s .  co m*/
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // jade's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    Object mappedObject = instantiateClass(this.mappedClass);
    BeanWrapper bw = new BeanWrapperImpl(mappedObject);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    boolean warnEnabled = logger.isWarnEnabled();
    boolean debugEnabled = logger.isDebugEnabled();
    Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
                if (debugEnabled && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        } else {
            if (checkColumns) {
                throw new InvalidDataAccessApiUsageException("Unable to map column '" + column
                        + "' to any properties of bean " + this.mappedClass.getName());
            }
            if (warnEnabled && rowNumber == 0) {
                logger.warn("Unable to map column '" + column + "' to any properties of bean "
                        + this.mappedClass.getName());
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.mx.core.dao.BeanPropRowMap.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData//from   w  w w.  j  a  va  2 s .  c o m
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    //logger.debug("Mapping column '" + column + "' to property '" +
                    //      pd.getName() + "' of type " + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.sinosoft.one.data.jade.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>/*from  ww  w .  j  a va 2 s .  c o  m*/
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // jade's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    Object mappedObject = instantiateClass(this.mappedClass);
    BeanWrapper bw = new BeanWrapperImpl(mappedObject);
    bw.setConversionService(this.conversionService);
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    boolean warnEnabled = logger.isWarnEnabled();
    boolean debugEnabled = logger.isDebugEnabled();
    Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
                if (debugEnabled && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        } else {
            if (checkColumns) {
                throw new InvalidDataAccessApiUsageException("Unable to map column '" + column
                        + "' to any properties of bean " + this.mappedClass.getName());
            }
            if (warnEnabled && rowNumber == 0) {
                logger.warn("Unable to map column '" + column + "' to any properties of bean "
                        + this.mappedClass.getName());
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from   ww w  . j a  v  a 2  s. c  o m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from  w w w  . j a  v a  2  s. c o  m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = this.mappedFields.get(field);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (rowNumber == 0 && logger.isDebugEnabled()) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type ["
                            + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]");
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException ex) {
                    if (value == null && this.primitivesDefaultedForNullValue) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Intercepted TypeMismatchException for row " + rowNumber
                                    + " and column '" + column + "' with null value when setting property '"
                                    + pd.getName() + "' of type ["
                                    + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: "
                                    + mappedObject, ex);
                        }
                    } else {
                        throw ex;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
            }
        } else {
            // No PropertyDescriptor found
            if (rowNumber == 0 && logger.isDebugEnabled()) {
                logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException(
                "Given ResultSet does not contain all fields " + "necessary to populate object of class ["
                        + this.mappedClass.getName() + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Populate JavaBean properties via XPath extraction.
 * /*w ww  .j ava2 s . c om*/
 * <p>
 * This method will call {@link #registerCustomEditors(BeanWrapper)} so
 * custom editors can be registered if desired.
 * </p>
 * 
 * @param obj
 *        the object to set properties on, or a BeanWrapper
 * @param xml
 *        the XML
 * @param xpathMap
 *        the mapping of JavaBean property names to XPaths
 */
protected void extractBeanDataFromXml(Object obj, Node xml, Map<String, XPathExpression> xpathMap) {
    BeanWrapper bean;
    if (obj instanceof BeanWrapper) {
        bean = (BeanWrapper) obj;
    } else {
        bean = PropertyAccessorFactory.forBeanPropertyAccess(obj);
    }
    registerCustomEditors(bean);
    for (Map.Entry<String, XPathExpression> me : xpathMap.entrySet()) {
        try {
            String val = (String) me.getValue().evaluate(xml, XPathConstants.STRING);
            if (val != null && !"".equals(val)) {
                bean.setPropertyValue(me.getKey(), val);
            }
        } catch (XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.lightadmin.core.persistence.support.DynamicDomainObjectMerger.java

/**
 * Merges the given target object into the source one.
 *
 * @param from       can be {@literal null}.
 * @param target     can be {@literal null}.
 * @param nullPolicy how to handle {@literal null} values in the source object.
 *///from   ww w.  j  a v a 2  s.  c o m
@Override
public void merge(final Object from, final Object target, final NullHandlingPolicy nullPolicy) {
    if (from == null || target == null) {
        return;
    }

    final BeanWrapper fromWrapper = beanWrapper(from);
    final BeanWrapper targetWrapper = beanWrapper(target);

    final DomainTypeAdministrationConfiguration domainTypeAdministrationConfiguration = configuration
            .forManagedDomainType(target.getClass());
    final PersistentEntity<?, ?> entity = domainTypeAdministrationConfiguration.getPersistentEntity();

    entity.doWithProperties(new SimplePropertyHandler() {
        @Override
        public void doWithPersistentProperty(PersistentProperty<?> persistentProperty) {
            Object sourceValue = fromWrapper.getPropertyValue(persistentProperty.getName());
            Object targetValue = targetWrapper.getPropertyValue(persistentProperty.getName());

            if (entity.isIdProperty(persistentProperty)) {
                return;
            }

            if (nullSafeEquals(sourceValue, targetValue)) {
                return;
            }

            if (propertyIsHiddenInFormView(persistentProperty, domainTypeAdministrationConfiguration)) {
                return;
            }

            if (nullPolicy == APPLY_NULLS || sourceValue != null) {
                targetWrapper.setPropertyValue(persistentProperty.getName(), sourceValue);
            }
        }
    });

    entity.doWithAssociations(new SimpleAssociationHandler() {
        @Override
        @SuppressWarnings("unchecked")
        public void doWithAssociation(Association<? extends PersistentProperty<?>> association) {
            PersistentProperty<?> persistentProperty = association.getInverse();

            Object fromValue = fromWrapper.getPropertyValue(persistentProperty.getName());
            Object targetValue = targetWrapper.getPropertyValue(persistentProperty.getName());

            if (propertyIsHiddenInFormView(persistentProperty, domainTypeAdministrationConfiguration)) {
                return;
            }

            if ((fromValue == null && nullPolicy == APPLY_NULLS)) {
                targetWrapper.setPropertyValue(persistentProperty.getName(), fromValue);
            }

            if (persistentProperty.isCollectionLike()) {
                Collection<Object> sourceCollection = (Collection) fromValue;
                Collection<Object> targetCollection = (Collection) targetValue;

                Collection<Object> candidatesForAddition = candidatesForAddition(sourceCollection,
                        targetCollection, persistentProperty);
                Collection<Object> candidatesForRemoval = candidatesForRemoval(sourceCollection,
                        targetCollection, persistentProperty);

                removeReferencedItems(targetCollection, candidatesForRemoval);

                addReferencedItems(targetCollection, candidatesForAddition);

                return;
            }

            if (!nullSafeEquals(fromValue, targetWrapper.getPropertyValue(persistentProperty.getName()))) {
                targetWrapper.setPropertyValue(persistentProperty.getName(), fromValue);
            }
        }
    });
}