List of usage examples for org.springframework.core.convert TypeDescriptor forObject
@Nullable public static TypeDescriptor forObject(@Nullable Object source)
From source file:org.focusns.common.web.widget.mvc.method.WidgetMethodArgumentResolver.java
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { ///*from w w w . j a va 2s . c o m*/ Object value = null; if (parameter.hasParameterAnnotation(WidgetAttribute.class)) { value = getWidgetAttributeValue(parameter, webRequest); } else if (parameter.hasParameterAnnotation(WidgetPref.class)) { value = getWidgetPrefValue(parameter, webRequest); } // if (value != null) { ConversionService conversionService = (ConversionService) webRequest .getAttribute(ConversionService.class.getName(), WebRequest.SCOPE_REQUEST); if (conversionService.canConvert(value.getClass(), parameter.getParameterType())) { value = conversionService.convert(value, parameter.getParameterType()); } else { throw new ConverterNotFoundException(TypeDescriptor.forObject(value), TypeDescriptor.valueOf(parameter.getParameterType())); } } // return value; }
From source file:com._4dconcept.springframework.data.marklogic.core.convert.MappingMarklogicConverter.java
@Override public <R> R read(Class<R> returnType, MarklogicContentHolder holder) { ResultItem resultItem = (ResultItem) holder.getContent(); if (String.class.equals(returnType)) { return returnType.cast(resultItem.asString()); }// w w w . j a v a 2 s .c o m R result = null; if (returnType.isPrimitive()) { try { Method method = MarklogicTypeUtils.primitiveMap.get(returnType).getMethod("valueOf", String.class); @SuppressWarnings("unchecked") R obj = (R) method.invoke(null, resultItem.asString()); result = obj; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOGGER.debug("Unable to generate primitive value for type " + returnType.getName()); } } if (result != null) { return result; } ConversionService conversionService = getConversionService(); if (conversionService.canConvert(resultItem.getClass(), returnType)) { R convert = conversionService.convert(resultItem, returnType); if (convert == null) { throw new ConversionFailedException(TypeDescriptor.forObject(resultItem), TypeDescriptor.valueOf(returnType), resultItem, new NullPointerException()); } return convert; } else { throw new ConverterNotFoundException(TypeDescriptor.forObject(resultItem), TypeDescriptor.valueOf(returnType)); } }
From source file:com.ryantenney.metrics.spring.reporter.AbstractReporterFactoryBean.java
@SuppressWarnings("unchecked") protected <V> V getProperty(String key, Class<V> requiredType, V defaultValue) { final String value = this.properties.get(key); if (value == null) { return defaultValue; }/*from w w w . j a v a 2 s .com*/ return (V) getConversionService().convert(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(requiredType)); }
From source file:com._4dconcept.springframework.data.marklogic.core.convert.MappingMarklogicConverter.java
@Override public void write(Object source, MarklogicContentHolder holder) { TypeDescriptor sourceDescriptor = TypeDescriptor.forObject(source); TypeDescriptor targetDescriptor = TypeDescriptor.valueOf(String.class); if (getConversionService().canConvert(sourceDescriptor, targetDescriptor)) { String content = getConversionService().convert(source, String.class); if (content == null) { throw new ConversionFailedException(sourceDescriptor, targetDescriptor, source, new NullPointerException("Conversion result is not e")); } else {//w ww . j av a 2 s . c om holder.setContent(content); } } else { throw new ConverterNotFoundException(sourceDescriptor, targetDescriptor); } }
From source file:com.p5solutions.core.jpa.orm.ConversionUtilityImpl.java
/** * @see com.p5solutions.core.jpa.orm.ConversionUtility#convert(java.lang.Object, * java.lang.Class)//ww w . j a v a 2s . com */ @Override public Object convert(Object value, Class<?> clazz) { if (value instanceof String && conversionService == null) { return convertString((String) value, clazz); } // if (value instanceof String && ReflectionUtility.isBasicClass(clazz)) { // return convertString((String) value, clazz); // } // Use the Spring Conversion service and try to map the // values TypeDescriptor sourceType = TypeDescriptor.forObject(value); // setup the type descriptor and pass it to the converter TypeDescriptor targetType = TypeDescriptor.valueOf(clazz); Class<?> fromClass = value.getClass(); //Boolean convertible = conversionService.canConvert(fromClass, clazz); Boolean convertible = conversionService.canConvert(sourceType, targetType); if (convertible) { return conversionService.convert(value, sourceType, targetType); } return value; }
From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), for the specified property. * //from w w w . jav a 2s. com * @param propertyName * name of the property * @param oldValue * the previous value, if available (may be <code>null</code>) * @param newValue * the proposed new value * @param requiredType * the type we must convert to (or <code>null</code> if not known, for example in case of a collection * element) * @param typeDescriptor * the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException * if type conversion failed */ @SuppressWarnings("unchecked") public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException { Object convertedValue = newValue; // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException firstAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); TypeDescriptor targetTypeDesc = typeDescriptor; if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) { try { return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc); } catch (ConversionFailedException ex) { // fallback to default conversion logic below firstAttemptEx = ex; } } } // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor(); if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor strCtor = requiredType.getConstructor(String.class); return (T) BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (firstAttemptEx != null) { throw firstAttemptEx; } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type [") .append(ClassUtils.getDescriptiveType(convertedValue)).append("]"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (firstAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && !Object.class.equals(requiredType)) { throw firstAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", firstAttemptEx); } return (T) convertedValue; }
From source file:org.kmnet.com.fw.web.el.Functions.java
/** * build query string from map with the specified {@link BeanWrapper}. * <p>/* w w w . j a v a 2s.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:org.terasoluna.gfw.web.el.Functions.java
/** * build query string from map with the specified {@link BeanWrapper}. * <p>/* ww w .ja v a 2 s . c om*/ * 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&name2=value&... * @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:com.drillmap.crm.repository.extensions.invoker.ReflectionRepositoryInvoker.java
private Object[] prepareParameters(Method method, Map<String, String[]> rawParameters, Pageable pageable, Sort sort) {/*from w w w . j a v a 2s .c o m*/ List<MethodParameter> parameters = new MethodParameters(method, PARAM_ANNOTATION).getParameters(); if (parameters.isEmpty()) { return new Object[0]; } Object[] result = new Object[parameters.size()]; Sort sortToUse = pageable == null ? sort : pageable.getSort(); for (int i = 0; i < result.length; i++) { MethodParameter param = parameters.get(i); Class<?> targetType = param.getParameterType(); if (Pageable.class.isAssignableFrom(targetType)) { result[i] = pageable; } else if (Sort.class.isAssignableFrom(targetType)) { result[i] = sortToUse; } else { String parameterName = param.getParameterName(); if (!StringUtils.hasText(parameterName)) { throw new IllegalArgumentException("No @Param annotation found on query method " + method.getName() + " for parameter " + parameterName); } String[] parameterValue = rawParameters.get(parameterName); Object value = parameterValue == null ? null : parameterValue.length == 1 ? parameterValue[0] : parameterValue; result[i] = conversionService.convert(value, TypeDescriptor.forObject(value), new TypeDescriptor(param)); } } return result; }
From source file:org.terasoluna.gfw.web.el.ObjectToMapConverter.java
/** * Add the pair of the given name and value to the given map. The value is flattened if required to be available in query * params. <br>/*from w ww . j ava2 s. c o m*/ * Return whether the value is flattened. The value is flattened in the case of the following types: * <ul> * <li>Array (unless the name is empty)</li> * <li>Iterable (unless the name is empty)</li> * <li>Map</li> * <li>{@link BeanUtils#isSimpleProperty(java.lang.Class)}</li> * <li>if {@link #conversionService} can convert</li> * </ul> * <p> * The value is formatted using {@link FormattingConversionService} is possible. If the value of a property is {@code null}, * the value is converted to an empty string and the key is prefixed with {@code "_"}. Request parameter that start with * {@code "_"} is reset parameter provided by Spring Web MVC. If a reset parameter is specified, Spring Web MVC bind * {@code null} to a property value. * </p> * @param map map to add * @param prefix prefix of the key * @param name name of the value * @param value value to convert * @param sourceType {@link TypeDescriptor} to use * @return flatten map */ private boolean flatten(Map<String, String> map, String prefix, String name, Object value, TypeDescriptor sourceType) { String key = StringUtils.isEmpty(prefix) ? name : prefix + "." + name; if (value == null) { String resetKey = "_" + key; map.put(resetKey, ""); // the value has been flatten return true; } Class<?> clazz = value.getClass(); if (value instanceof Iterable) { if (StringUtils.isEmpty(name)) { // skip flatten return true; } Iterable iterable = (Iterable) value; map.putAll(this.convert(key, iterable)); } else if (clazz.isArray()) { if (StringUtils.isEmpty(name)) { // skip flatten return true; } map.putAll(this.convert(key, arrayObjectToList(value))); } else if (value instanceof Map) { Map m = (Map) value; map.putAll(this.convert(key, m)); } else { TypeDescriptor descriptor = (sourceType != null) ? sourceType : TypeDescriptor.forObject(value); if (BeanUtils.isSimpleProperty(clazz) || conversionService.canConvert(descriptor, STRING_DESC)) { map.put(key, conversionService.convert(value, descriptor, STRING_DESC).toString()); } else { // the value is Java Bean? return false; } } // the value has been flatten return true; }