Example usage for org.springframework.beans BeanWrapper getPropertyTypeDescriptor

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

Introduction

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

Prototype

@Nullable
TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException;

Source Link

Document

Return a type descriptor for the specified property: preferably from the read method, falling back to the write method.

Usage

From source file:org.terasoluna.gfw.web.el.Functions.java

/**
 * build query string from map with the specified {@link BeanWrapper}.
 * <p>//from w  w w  . ja  v  a2  s.c o  m
 * query string is encoded with "UTF-8".<br>
 * <strong>Use {@link #mapToQuery(Map)} instead of this method.</strong>
 * </p>
 * @see ObjectToMapConverter
 * @param map map
 * @param beanWrapper beanWrapper which has the definition of each field.
 * @return query string. if map is not empty, return query string. ex) name1=value&amp;name2=value&amp;...
 * @deprecated (since 5.0.1, to support nested fields in f:query, Use {@link #mapToQuery(Map)} instead of this method.)
 */
@Deprecated
public static String mapToQuery(Map<String, Object> map, BeanWrapper beanWrapper) {
    if (map == null || map.isEmpty()) {
        return "";
    }
    UriComponentsBuilder builder = UriComponentsBuilder.fromPath("");
    for (Map.Entry<String, Object> e : map.entrySet()) {
        String name = e.getKey();
        Object value = e.getValue();
        TypeDescriptor sourceType;
        if (beanWrapper != null) {
            sourceType = beanWrapper.getPropertyTypeDescriptor(name);
        } else {
            sourceType = TypeDescriptor.forObject(value);
        }
        builder.queryParam(name, CONVERSION_SERVICE.convert(value, sourceType, STRING_DESC));
    }
    String query = builder.build().encode().toString();
    // remove the beginning symbol character('?') of the query string.
    return query.substring(1);
}

From source file:org.kmnet.com.fw.web.el.Functions.java

/**
 * build query string from map with the specified {@link BeanWrapper}.
 * <p>//from   w w  w.ja  v a 2  s  . c o  m
 * query string is encoded with "UTF-8".
 * </p>
 * @param map map
 * @param beanWrapper beanWrapper which has the definition of each field.
 * @return query string. if map is not empty, return query string. ex) name1=value&name2=value&...
 */
public static String mapToQuery(Map<String, Object> map, BeanWrapper beanWrapper) {
    if (map == null || map.isEmpty()) {
        return "";
    }
    UriComponentsBuilder builder = UriComponentsBuilder.fromPath("");
    Map<String, Object> uriVariables = new HashMap<String, Object>();
    for (Map.Entry<String, Object> e : map.entrySet()) {
        String name = e.getKey();
        Object value = e.getValue();
        builder.queryParam(name, "{" + name + "}");
        TypeDescriptor sourceType;
        if (beanWrapper != null) {
            sourceType = beanWrapper.getPropertyTypeDescriptor(name);
        } else {
            sourceType = TypeDescriptor.forObject(value);
        }
        uriVariables.put(name, CONVERSION_SERVICE.convert(value, sourceType, STRING_DESC));
    }
    String query = builder.buildAndExpand(uriVariables).encode().toString();
    // remove the beginning symbol character('?') of the query string.
    return query.substring(1);
}

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

private void setAsText(Object bean, String propertyName, String text) throws ConversionException {
    BeanWrapper beanWrapper = wrap(bean);
    TypeDescriptor typeDescriptor = beanWrapper.getPropertyTypeDescriptor(propertyName);

    Object value;// w  w  w . j a v a  2  s . c o m
    try {
        value = conversionService.convert(text, TypeDescriptor.valueOf(String.class), typeDescriptor);
    } catch (TypeMismatchException exception) {
        String message = String.format("Error converting from '%s' to type '%s' for property '%s'", text,
                typeDescriptor, propertyName);
        throw new ConversionException(message, exception);
    }

    try {
        beanWrapper.setPropertyValue(propertyName, value);
    } catch (BeansException exception) {
        String message = String.format("Error setting bean property '%s' to: %s", propertyName, value);
        throw new ConversionException(message, exception);
    }
}

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

private String getAsText(Object bean, String propertyName) {
    BeanWrapper beanWrapper = wrap(bean);
    Object value = beanWrapper.getPropertyValue(propertyName);
    TypeDescriptor typeDescriptor = beanWrapper.getPropertyTypeDescriptor(propertyName);
    return (String) conversionService.convert(value, typeDescriptor, TypeDescriptor.valueOf(String.class));
}

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:org.terasoluna.gfw.web.el.ObjectToMapConverter.java

/**
 * Convert the given object to the flattened map.
 * <p>//ww  w.  java2 s .  c  o m
 * Return empty map if the object is null.
 * </p>
 * @param prefix prefix of the key
 * @param object object to convert
 * @return converted map. all keys are prefixed with the given key
 * @see ObjectToMapConverter
 */
public Map<String, String> convert(String prefix, Object object) {
    Map<String, String> map = new LinkedHashMap<String, String>();

    // at first, try to flatten the given object
    if (flatten(map, "", prefix, object, null)) {
        return map;
    }

    // the given object is a Java Bean
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
    PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();

    // flatten properties in the given object
    for (PropertyDescriptor pd : pds) {
        String name = pd.getName();
        if ("class".equals(name) || !beanWrapper.isReadableProperty(name)) {
            continue;
        }
        Object value = beanWrapper.getPropertyValue(name);
        TypeDescriptor sourceType = beanWrapper.getPropertyTypeDescriptor(name);

        if (!flatten(map, prefix, name, value, sourceType)) {
            // the property can be a Java Bean
            // convert recursively
            Map<String, String> subMap = this.convert(name, value);
            map.putAll(subMap);
        }
    }

    return map;
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Obtains the descriptor of the filtered field
 * /*from w  ww  .  j  a v a 2  s  .  c o  m*/
 * @param fieldName
 * @param entityType
 * @return
 */
public static <T> TypeDescriptor getTypeDescriptor(String fieldName, Class<T> entityType) {
    String fieldNameToFindType = fieldName;
    BeanWrapper beanWrapper = getBeanWrapper(entityType);

    TypeDescriptor fieldDescriptor = null;
    Class<?> propType = null;
    // Find recursive the las beanWrapper
    if (fieldName.contains(SEPARATOR_FIELDS)) {
        String[] fieldNameSplitted = StringUtils.split(fieldName, SEPARATOR_FIELDS);
        for (int i = 0; i < fieldNameSplitted.length - 1; i++) {
            propType = beanWrapper.getPropertyType(fieldNameSplitted[i]);
            if (propType == null) {
                throw new IllegalArgumentException(String.format("Property %s not found in %s (request %s.%s)",
                        fieldNameSplitted[i], beanWrapper.getWrappedClass(), entityType, fieldName));
            }
            beanWrapper = getBeanWrapper(propType);
        }
        fieldNameToFindType = fieldNameSplitted[fieldNameSplitted.length - 1];
    }
    fieldDescriptor = beanWrapper.getPropertyTypeDescriptor(fieldNameToFindType);

    return fieldDescriptor;
}

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
 *///from  ww w .  j  a va2  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;
}