Example usage for org.springframework.beans BeanWrapper setConversionService

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

Introduction

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

Prototype

void setConversionService(@Nullable ConversionService conversionService);

Source Link

Document

Specify a Spring 3.0 ConversionService to use for converting property values, as an alternative to JavaBeans PropertyEditors.

Usage

From source file:org.tangram.components.spring.TangramSpringServices.java

/**
 * create a bean wrapper instance from a bean object and prepare it with a conversion service if available.
 *
 * @param bean//from   www  .  j  a  va  2  s.c  o m
 * @return wrapper for the given bean
 */
public static BeanWrapper createWrapper(Object bean) {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    try {
        ConversionService converter = TangramSpringServices.getConversionService();
        if (converter != null) {
            wrapper.setConversionService(converter);
        } // if
        LOG.info("createWrapper() conversion service {}", wrapper.getConversionService());
    } catch (Exception e) {
        // This is not an error since conversion services are optional.
        LOG.warn("createWrapper()", e);
    } // try/catch
    return wrapper;
}

From source file:cherry.foundation.type.jdbc.CustomBeanPropertyRowMapper.java

@Override
protected void initBeanWrapper(BeanWrapper bw) {
    bw.setConversionService(conversionService);
}

From source file:pl.java.scalatech.monetary.DefaultFormattingConversionServiceTest.java

@Test
public void testJavaMoney() {
    BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
    beanWrapper.setConversionService(conversionService);
    beanWrapper.setPropertyValue("monetaryAmount", "USD 100,000");
    beanWrapper.setPropertyValue("currencyUnit", "USD");

    assertThat(bean.getMonetaryAmount().getNumber().intValue(), is(100));
    assertThat(bean.getMonetaryAmount().getCurrency().getCurrencyCode(), is("PLN"));
    assertThat(bean.getCurrencyUnit().getCurrencyCode(), is("USD"));

    String monetaryAmountString = (String) conversionService.convert(bean.getMonetaryAmount(),
            beanWrapper.getPropertyTypeDescriptor("monetaryAmount"), TypeDescriptor.valueOf(String.class));
    assertThat(monetaryAmountString, is("USD 100"));
    String currencyUnitString = (String) conversionService.convert(bean.getCurrencyUnit(),
            beanWrapper.getPropertyTypeDescriptor("currencyUnit"), TypeDescriptor.valueOf(String.class));
    assertThat(currencyUnitString, is("USD"));
}

From source file:uk.co.blackpepper.support.retrofit.jsoup.spring.AbstractBeanHtmlConverter.java

private BeanWrapper wrap(Object bean) {
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    beanWrapper.setConversionService(conversionService);
    return beanWrapper;
}

From source file:org.jdal.ui.bind.AbstractBinder.java

private BeanWrapper getBeanWrapper() {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(getModel());
    wrapper.setConversionService(getConversionService());
    wrapper.registerCustomEditor(Date.class,
            new CustomDateEditor(SimpleDateFormat.getDateTimeInstance(), true));

    return wrapper;
}

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

/**
 * Extract the values for all columns in the current row.
 * <p>/*from  w w  w. 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);
    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:org.springframework.jdbc.core.BeanPropertyRowMapper.java

/**
 * Initialize the given BeanWrapper to be used for row mapping.
 * To be called for each row.//from w  ww  . j  a  v  a 2s.c  om
 * <p>The default implementation applies the configured {@link ConversionService},
 * if any. Can be overridden in subclasses.
 * @param bw the BeanWrapper to initialize
 * @see #getConversionService()
 * @see BeanWrapper#setConversionService
 */
protected void initBeanWrapper(BeanWrapper bw) {
    ConversionService cs = getConversionService();
    if (cs != null) {
        bw.setConversionService(cs);
    }
}

From source file:org.springframework.springfaces.mvc.bind.ReverseDataBinder.java

/**
 * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will
 * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues}
 * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using
 * the property editors bound to the original dataBinder.
 * @return property values that could be re-bound using the data binder
 * @throws IllegalStateException if the target object values cannot be bound
 *///w  w w .  j  av  a2  s  .c  o  m
public PropertyValues reverseBind() {
    Assert.notNull(this.dataBinder.getTarget(),
            "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object");

    MutablePropertyValues rtn = new MutablePropertyValues();
    BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(this.dataBinder.getTarget());

    ConversionService conversionService = this.dataBinder.getConversionService();
    if (conversionService != null) {
        target.setConversionService(conversionService);
    }

    PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors();

    BeanWrapper defaultValues = null;
    if (this.skipDefaultValues) {
        defaultValues = newDefaultTargetValues(this.dataBinder.getTarget());
    }

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor property = propertyDescriptors[i];
        String propertyName = PropertyAccessorUtils.canonicalPropertyName(property.getName());
        Object propertyValue = target.getPropertyValue(propertyName);

        if (isSkippedProperty(property)) {
            continue;
        }

        if (!isMutableProperty(property)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods");
            }
            continue;
        }

        if (defaultValues != null
                && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping '" + propertyName + "' as property contains default value");
            }
            continue;
        }

        // Find a property editor
        PropertyEditorRegistrySupport propertyEditorRegistrySupport = null;
        if (target instanceof PropertyEditorRegistrySupport) {
            propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target;
        }

        PropertyEditor propertyEditor = findEditor(propertyName, propertyEditorRegistrySupport,
                target.getWrappedInstance(), target.getPropertyType(propertyName),
                target.getPropertyTypeDescriptor(propertyName));

        // Convert and store the value
        String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor);
        if (convertedPropertyValue != null) {
            rtn.addPropertyValue(propertyName, convertedPropertyValue);
        }
    }

    this.dataBinder.bind(rtn);
    BindingResult bindingResult = this.dataBinder.getBindingResult();
    if (bindingResult.hasErrors()) {
        throw new IllegalStateException("Unable to reverse bind from target '" + this.dataBinder.getObjectName()
                + "', the properties '" + rtn + "' will result in binding errors when re-bound "
                + bindingResult.getAllErrors());
    }
    return rtn;
}