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:org.springframework.beans.BeanWrapperTests.java

@Test
public void testGenericEnum() {
    EnumConsumer consumer = new EnumConsumer();
    BeanWrapper bw = new BeanWrapperImpl(consumer);
    bw.setPropertyValue("enumValue", TestEnum.class.getName() + ".TEST_VALUE");
    assertEquals(TestEnum.TEST_VALUE, consumer.getEnumValue());
}

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

@Test
public void testWildcardedGenericEnum() {
    WildcardEnumConsumer consumer = new WildcardEnumConsumer();
    BeanWrapper bw = new BeanWrapperImpl(consumer);
    bw.setPropertyValue("enumValue", TestEnum.class.getName() + ".TEST_VALUE");
    assertEquals(TestEnum.TEST_VALUE, consumer.getEnumValue());
}

From source file:org.springframework.data.jdbc.support.oracle.BeanPropertyStructMapper.java

/**
* Extract the values for all attributes in the struct.
* <p>Utilizes public setters and result set metadata.
* @see java.sql.ResultSetMetaData/*from w w w .j  a va2  s.  co m*/
*/
public T fromStruct(STRUCT struct) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = struct.getDescriptor().getMetaData();
    Object[] attr = struct.getAttributes();
    int columnCount = rsmd.getColumnCount();
    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 = attr[index - 1];
                if (logger.isDebugEnabled()) {
                    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:org.springframework.flex.core.MessageBrokerFactoryBean.java

private void setupExternalPathResolver() {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(this.messageBroker);
    wrapper.setPropertyValue("externalPathResolver", new MessageBroker.InternalPathResolver() {

        public InputStream resolve(String filename) throws IOException {

            try {
                Resource resource = MessageBrokerFactoryBean.this.resourceLoader.getResource(filename);
                if (resource.exists()) {
                    return resource.getInputStream();
                } else {
                    return null;
                }//from   ww  w .ja v a2 s  . c  om
            } catch (IOException e) {
                throw new IllegalStateException("Could not resolve Flex internal resource at: " + filename);
            }

        }
    });
}

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;// w  w  w  .  java  2s  . c  o  m
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.springframework.jdbc.core.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 va  2 s . c o m*/
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T 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<>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = (this.mappedFields != null ? this.mappedFields.get(field) : null);
        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:org.springframework.jms.listener.endpoint.DefaultJmsActivationSpecFactory.java

/**
 * This implementation supports Spring's extended "maxConcurrency"
 * and "prefetchSize" settings through detecting corresponding
 * ActivationSpec properties: "maxSessions"/"maxNumberOfWorks" and
 * "maxMessagesPerSessions"/"maxMessages", respectively
 * (following ActiveMQ's and JORAM's naming conventions).
 *///from   www  . j ava2  s  .c om
@Override
protected void populateActivationSpecProperties(BeanWrapper bw, JmsActivationSpecConfig config) {
    super.populateActivationSpecProperties(bw, config);
    if (config.getMaxConcurrency() > 0) {
        if (bw.isWritableProperty("maxSessions")) {
            // ActiveMQ
            bw.setPropertyValue("maxSessions", Integer.toString(config.getMaxConcurrency()));
        } else if (bw.isWritableProperty("maxNumberOfWorks")) {
            // JORAM
            bw.setPropertyValue("maxNumberOfWorks", Integer.toString(config.getMaxConcurrency()));
        } else if (bw.isWritableProperty("maxConcurrency")) {
            // WebSphere
            bw.setPropertyValue("maxConcurrency", Integer.toString(config.getMaxConcurrency()));
        }
    }
    if (config.getPrefetchSize() > 0) {
        if (bw.isWritableProperty("maxMessagesPerSessions")) {
            // ActiveMQ
            bw.setPropertyValue("maxMessagesPerSessions", Integer.toString(config.getPrefetchSize()));
        } else if (bw.isWritableProperty("maxMessages")) {
            // JORAM
            bw.setPropertyValue("maxMessages", Integer.toString(config.getPrefetchSize()));
        } else if (bw.isWritableProperty("maxBatchSize")) {
            // WebSphere
            bw.setPropertyValue("maxBatchSize", Integer.toString(config.getPrefetchSize()));
        }
    }
}

From source file:org.springframework.jms.listener.endpoint.DefaultJmsActivationSpecFactory.java

/**
 * This implementation maps {@code SESSION_TRANSACTED} onto an
 * ActivationSpec property named "useRAManagedTransaction", if available
 * (following ActiveMQ's naming conventions).
 *///from w  w w  .j  a  v  a  2  s . c  o m
@Override
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
    if (ackMode == Session.SESSION_TRANSACTED && bw.isWritableProperty("useRAManagedTransaction")) {
        // ActiveMQ
        bw.setPropertyValue("useRAManagedTransaction", "true");
    } else {
        super.applyAcknowledgeMode(bw, ackMode);
    }
}