Java Code Examples for org.springframework.core.convert.ConversionService#convert()

The following examples show how to use org.springframework.core.convert.ConversionService#convert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractPropertyResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Convert the given value to the specified target type, if necessary.
 * @param value the original property value
 * @param targetType the specified target type for property retrieval
 * @return the converted value, or the original value if no conversion
 * is necessary
 * @since 4.3.5
 */
@SuppressWarnings("unchecked")
@Nullable
protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
	if (targetType == null) {
		return (T) value;
	}
	ConversionService conversionServiceToUse = this.conversionService;
	if (conversionServiceToUse == null) {
		// Avoid initialization of shared DefaultConversionService if
		// no standard type conversion is needed in the first place...
		if (ClassUtils.isAssignableValue(targetType, value)) {
			return (T) value;
		}
		conversionServiceToUse = DefaultConversionService.getSharedInstance();
	}
	return conversionServiceToUse.convert(value, targetType);
}
 
Example 2
Source File: AbstractPropertyResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert the given value to the specified target type, if necessary.
 * @param value the original property value
 * @param targetType the specified target type for property retrieval
 * @return the converted value, or the original value if no conversion
 * is necessary
 * @since 4.3.5
 */
@SuppressWarnings("unchecked")
protected <T> T convertValueIfNecessary(Object value, Class<T> targetType) {
	if (targetType == null) {
		return (T) value;
	}
	ConversionService conversionServiceToUse = this.conversionService;
	if (conversionServiceToUse == null) {
		// Avoid initialization of shared DefaultConversionService if
		// no standard type conversion is needed in the first place...
		if (ClassUtils.isAssignableValue(targetType, value)) {
			return (T) value;
		}
		conversionServiceToUse = DefaultConversionService.getSharedInstance();
	}
	return conversionServiceToUse.convert(value, targetType);
}
 
Example 3
Source File: RequestParamMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
protected String formatUriValue(
		@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, @Nullable Object value) {

	if (value == null) {
		return null;
	}
	else if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 4
Source File: AbstractPropertyResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Convert the given value to the specified target type, if necessary.
 * @param value the original property value
 * @param targetType the specified target type for property retrieval
 * @return the converted value, or the original value if no conversion
 * is necessary
 * @since 4.3.5
 */
@SuppressWarnings("unchecked")
@Nullable
protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
	if (targetType == null) {
		return (T) value;
	}
	ConversionService conversionServiceToUse = this.conversionService;
	if (conversionServiceToUse == null) {
		// Avoid initialization of shared DefaultConversionService if
		// no standard type conversion is needed in the first place...
		if (ClassUtils.isAssignableValue(targetType, value)) {
			return (T) value;
		}
		conversionServiceToUse = DefaultConversionService.getSharedInstance();
	}
	return conversionServiceToUse.convert(value, targetType);
}
 
Example 5
Source File: ConvertedDatatablesData.java    From springlets with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> convert(Object value, ConversionService conversionService) {

    BeanWrapper bean = new BeanWrapperImpl(value);
    PropertyDescriptor[] properties = bean.getPropertyDescriptors();
    Map<String, Object> convertedValue = new HashMap<>(properties.length);

    for (int i = 0; i < properties.length; i++) {
      String name = properties[i].getName();
      Object propertyValue = bean.getPropertyValue(name);
      if (propertyValue != null
          && conversionService.canConvert(propertyValue.getClass(), String.class)) {
        TypeDescriptor source = bean.getPropertyTypeDescriptor(name);
        String convertedPropertyValue =
            (String) conversionService.convert(propertyValue, source, TYPE_STRING);
        convertedValue.put(name, convertedPropertyValue);
      }
    }

    return convertedValue;
  }
 
Example 6
Source File: ConvertedDatatablesData.java    From springlets with Apache License 2.0 6 votes vote down vote up
private static Object convertProperty(BeanWrapper parentBean, String property,
    ConversionService conversionService, String propertySeparator) {

  int dotIndex = property.indexOf(propertySeparator);
  if (dotIndex > 0) {
    String baseProperty = property.substring(0, dotIndex);
    String childProperty = property.substring(dotIndex + propertySeparator.length());

    BeanWrapper childBean = new BeanWrapperImpl(parentBean.getPropertyValue(baseProperty));
    return convertProperty(childBean, childProperty, conversionService, propertySeparator);
  } else {
    TypeDescriptor source = parentBean.getPropertyTypeDescriptor(property);
    Object propertyValue = parentBean.getPropertyValue(property);

    if (source.isAssignableTo(TYPE_STRING)) {
      return (String) propertyValue;
    } else {
      return (String) conversionService.convert(propertyValue, source, TYPE_STRING);
    }
  }
}
 
Example 7
Source File: SpringTypeConverter.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }
    
    // do not attempt to convert List -> Map. Ognl expression may use this converter as a fallback expecting null
    if (type.isAssignableFrom(Map.class) && isArrayOrCollection(value)) {
        return null;
    }

    TypeDescriptor sourceType = types.computeIfAbsent(value.getClass(), TypeDescriptor::valueOf);
    TypeDescriptor targetType = types.computeIfAbsent(type, TypeDescriptor::valueOf);

    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(sourceType, targetType)) {
            try {
                return (T)conversionService.convert(value, sourceType, targetType);
            } catch (ConversionFailedException e) {
                // if value is a collection or an array the check ConversionService::canConvert
                // may return true but then the conversion of specific objects may fail
                //
                // https://issues.apache.org/jira/browse/CAMEL-10548
                // https://jira.spring.io/browse/SPR-14971
                //
                if (e.getCause() instanceof ConverterNotFoundException && isArrayOrCollection(value)) {
                    return null;
                } else {
                    throw new TypeConversionException(value, type, e);
                }
            }
        }
    }

    return null;
}
 
Example 8
Source File: CompositeConversionService.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T convert(Object source, Class<T> targetType) {
    for (int i = 0; i < this.delegates.size() - 1; i++) {
        try {
            ConversionService delegate = this.delegates.get(i);
            if (delegate.canConvert(source.getClass(), targetType)) {
                return delegate.convert(source, targetType);
            }
        } catch (ConversionException e) {
            // ignored
        }
    }

    return this.delegates.get(this.delegates.size() - 1).convert(source, targetType);
}
 
Example 9
Source File: CompositeConversionService.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    for (int i = 0; i < this.delegates.size() - 1; i++) {
        try {
            ConversionService delegate = this.delegates.get(i);
            if (delegate.canConvert(sourceType, targetType)) {
                return delegate.convert(source, sourceType, targetType);
            }
        } catch (ConversionException e) {
            // ignored
        }
    }

    return this.delegates.get(this.delegates.size() - 1).convert(source, sourceType, targetType);
}
 
Example 10
Source File: PathVariableMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
protected String formatUriValue(@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, Object value) {
	if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 11
Source File: BindConverter.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType,
                      TypeDescriptor targetType) {
    for (int i = 0; i < this.delegates.size() - 1; i++) {
        try {
            ConversionService delegate = this.delegates.get(i);
            if (delegate.canConvert(sourceType, targetType)) {
                return delegate.convert(source, sourceType, targetType);
            }
        } catch (ConversionException ex) {
        }
    }
    return this.delegates.get(this.delegates.size() - 1).convert(source,
            sourceType, targetType);
}
 
Example 12
Source File: XmlNacosPropertySourceBuilder.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
private <T> T getAttribute(Element element, String name, T defaultValue) {
	ConversionService conversionService = environment.getConversionService();
	String value = element.getAttribute(name);
	String resolvedValue = environment.resolvePlaceholders(value);
	T attributeValue = StringUtils.hasText(resolvedValue)
			? (T) conversionService.convert(resolvedValue, defaultValue.getClass())
			: defaultValue;
	return attributeValue;
}
 
Example 13
Source File: PropertySourceConfigurationSource.java    From conf4j with MIT License 5 votes vote down vote up
private OptionalValue<String> getProperty(PropertySource<?> propertySource, String key) {
    Object value = propertySource.getProperty(key);
    if (value == null) {
        return propertySource.containsProperty(key) ? present(null) : absent();
    }

    ConversionService currentConversionService = (this.conversionService != null) ? this.conversionService : getDefaultConversionService();
    String stringValue = currentConversionService.convert(value, String.class);

    return present(stringValue);
}
 
Example 14
Source File: PathVariableMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
	if (value == null) {
		return null;
	}
	else if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 15
Source File: RequestParamMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
	if (value == null) {
		return null;
	}
	else if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 16
Source File: TypeConversionIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
void assertWrite(Object thing, String fieldName, ConversionService conversionService) {

		long id = (long) ReflectionTestUtils.getField(thing, "id");
		Object domainValue = ReflectionTestUtils.getField(thing, fieldName);

		Value driverValue;
		if (domainValue != null && Collection.class.isAssignableFrom(domainValue.getClass())) {
			Collection<?> sourceCollection = (Collection<?>) domainValue;
			Object[] targetCollection = (sourceCollection).stream().map(element ->
				conversionService.convert(element, Value.class)).toArray();
			driverValue = Values.value(targetCollection);
		} else {
			driverValue = conversionService.convert(domainValue, Value.class);
		}

		try (Session session = neo4jConnectionSupport.getDriver().session()) {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("id", id);
			parameters.put("attribute", fieldName);
			parameters.put("v", driverValue);

			long cnt = session
				.run("MATCH (n) WHERE id(n) = $id  AND n[$attribute] = $v RETURN COUNT(n) AS cnt",
					parameters)
				.single().get("cnt").asLong();
			assertThat(cnt).isEqualTo(1L);
		}
	}
 
Example 17
Source File: AbstractWxApiRequestContributor.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
/**
 * 把参数格式化成字符串用于拼接url
 *
 * @param cs
 * @param sourceType
 * @param value
 * @return the result
 */
protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
    if (value == null) {
        return null;
    } else if (value instanceof String) {
        return (String) value;
    } else if (value instanceof Enum) {
        // 枚举通过toString取值,conversionService默认从name取值
        return value.toString();
    } else if (cs != null) {
        return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
    } else {
        return value.toString();
    }
}
 
Example 18
Source File: PathVariableMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
	if (value == null) {
		return null;
	}
	else if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 19
Source File: RequestParamMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
	if (value == null) {
		return null;
	}
	else if (value instanceof String) {
		return (String) value;
	}
	else if (cs != null) {
		return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
	}
	else {
		return value.toString();
	}
}
 
Example 20
Source File: GrailsHibernateQueryUtils.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param entity The {@link org.grails.datastore.mapping.model.PersistentEntity} instance
 * @param query  The criteria instance
 * @param argMap The arguments map
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(
        PersistentEntity entity,
        Query query,
        Map argMap,
        ConversionService conversionService,
        boolean useDefaultMapping) {
    Integer maxParam = null;
    Integer offsetParam = null;
    if (argMap.containsKey(DynamicFinder.ARGUMENT_MAX)) {
        maxParam = conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_OFFSET)) {
        offsetParam = conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_FETCH_SIZE)) {
        query.setFetchSize(conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_TIMEOUT)) {
        query.setTimeout(conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_FLUSH_MODE)) {
        query.setHibernateFlushMode(convertFlushMode(argMap.get(DynamicFinder.ARGUMENT_FLUSH_MODE)));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_READ_ONLY)) {
        query.setReadOnly(ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_READ_ONLY, argMap));
    }

    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        query.setMaxResults(max);
    }
    if (offset > -1) {
        query.setFirstResult(offset);
    }
    if (ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_LOCK, argMap)) {
        query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
        query.setCacheable(false);
    } else {
        if (argMap.containsKey(DynamicFinder.ARGUMENT_CACHE)) {
            query.setCacheable(ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_CACHE, argMap));
        } else {
            cacheCriteriaByMapping(entity.getJavaClass(), query);
        }
    }

}