List of usage examples for org.springframework.core.convert ConversionService convert
@Nullable Object convert(@Nullable Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType);
From source file:org.gvnix.web.datatables.util.QuerydslUtils.java
/** * Check if a string is valid for a type <br/> * If conversion service is not provided try to check by apache commons * utilities. <b>TODO</b> in this (no-conversionService) case just * implemented for numerics//w ww . j a v a 2 s . c o m * * @param string * @param typeDescriptor * @param conversionService (optional) * @return */ private static boolean isValidValueFor(String string, TypeDescriptor typeDescriptor, ConversionService conversionService) { if (conversionService != null) { try { conversionService.convert(string, STRING_TYPE_DESCRIPTOR, typeDescriptor); } catch (ConversionException e) { return false; } return true; } else { Class<?> fieldType = typeDescriptor.getType(); if (Number.class.isAssignableFrom(fieldType) || NUMBER_PRIMITIVES.contains(fieldType)) { return NumberUtils.isNumber(string); } // TODO implement other types return true; } }
From source file:org.gvnix.web.datatables.util.QuerydslUtils.java
/** * Return where clause expression for number properties by casting it to * string before check its value./*from w w w. j ava 2 s . c o m*/ * <p/> * Querydsl Expr: * {@code entityPath.fieldName.stringValue() like ('%' + searchStr + '%')} * Database operation: * {@code str(entity.fieldName) like ('%' + searchStr + '%')} * <p/> * Like operation is case sensitive. * * @param entityPath Full path to entity and associations. For example: * {@code Pet} , {@code Pet.owner} * @param fieldName Property name in the given entity path. For example: * {@code weight} in {@code Pet} entity, {@code age} in * {@code Pet.owner} entity. * @param searchStr the value to find, may be null * @return PredicateOperation */ public static <T, N extends java.lang.Number & java.lang.Comparable<?>> BooleanExpression createNumberExpression( PathBuilder<T> entityPath, String fieldName, Class<N> fieldType, TypeDescriptor descriptor, String searchStr, ConversionService conversionService) { if (StringUtils.isBlank(searchStr)) { return null; } NumberPath<N> numberExpression = entityPath.getNumber(fieldName, fieldType); BooleanExpression expression = null; if (conversionService != null) { try { Object number = conversionService.convert(searchStr, STRING_TYPE_DESCRIPTOR, descriptor); if (number == null) { expression = numberExpression.stringValue().like("%".concat(searchStr).concat("%")); } else { String toSearch = number.toString(); if (number instanceof BigDecimal && ((BigDecimal) number).scale() > 1) { // For bigDecimal trim 0 in decimal part toSearch = StringUtils.stripEnd(toSearch, "0"); if (StringUtils.endsWith(toSearch, ".")) { // prevent "#." strings toSearch = toSearch.concat("0"); } } expression = numberExpression.stringValue().like("%".concat(toSearch).concat("%")); } } catch (ConversionException e) { expression = numberExpression.stringValue().like("%".concat(searchStr).concat("%")); } } else { expression = numberExpression.stringValue().like("%".concat(searchStr).concat("%")); } return expression; }
From source file:org.gvnix.web.datatables.util.QuerydslUtils.java
/** * Return where clause expression for number properties by casting it to * string before check its value.//from w ww .jav a2s. c o m * <p/> * Querydsl Expr: * {@code entityPath.fieldName.stringValue() eq searchStr * Database operation: * {@code str(entity.fieldName) = searchStr * <p/> * Like operation is case sensitive. * * @param entityPath Full path to entity and associations. For example: * {@code Pet} , {@code Pet.owner} * @param fieldName Property name in the given entity path. For example: * {@code weight} in {@code Pet} entity, {@code age} in * {@code Pet.owner} entity. * @param searchStr the value to find, may be null * @return PredicateOperation */ @SuppressWarnings("unchecked") public static <T, N extends java.lang.Number & java.lang.Comparable<?>> BooleanExpression createNumberExpressionEqual( PathBuilder<T> entityPath, String fieldName, Class<N> fieldType, TypeDescriptor descriptor, String searchStr, ConversionService conversionService) { if (StringUtils.isEmpty(searchStr)) { return null; } NumberPath<N> numberExpression = entityPath.getNumber(fieldName, fieldType); TypeDescriptor strDesc = STRING_TYPE_DESCRIPTOR; if (conversionService != null) { try { return numberExpression.eq((N) conversionService.convert(searchStr, strDesc, descriptor)); } catch (ConversionException ex) { return numberExpression.stringValue().like("%".concat(searchStr).concat("%")); } } else { return numberExpression.stringValue().like("%".concat(searchStr).concat("%")); } }
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. * // www . j av a 2 s .c om * @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.gvnix.web.datatables.util.QuerydslUtils.java
/** * This method returns the query expression based on String expression * user-written./*ww w. j a v a 2 s . co m*/ * * Expression can be "=", ">", "<", ">=", "<=", "<>", "!=", * "ENTRENUMERO(n1;n2)" * * @param searchStr * @return */ @SuppressWarnings("unchecked") public static <T, N extends java.lang.Number & java.lang.Comparable<?>> BooleanExpression getNumericFilterExpression( PathBuilder<T> entityPath, String fieldName, Class<N> fieldType, TypeDescriptor descriptor, String searchStr, ConversionService conversionService, MessageSource messageSource) { if (StringUtils.isEmpty(searchStr)) { return null; } TypeDescriptor strDesc = STRING_TYPE_DESCRIPTOR; NumberPath<N> numberExpression = entityPath.getNumber(fieldName, fieldType); // If written expression is a symbol operation expression // Getting expressions with symbols Pattern symbolOperator = Pattern.compile("([!=><][=>]?)([-]?[\\d.,]*)"); Matcher symbolMatcher = symbolOperator.matcher(searchStr); if (symbolMatcher.matches()) { String symbolExpression = symbolMatcher.group(1); String value = symbolMatcher.group(2); if (!StringUtils.isBlank(value)) { Object valueConverted = conversionService.convert(value, strDesc, descriptor); if (symbolExpression.equals("=") || symbolExpression.equals("==")) { return numberExpression.eq((N) valueConverted); } else if (symbolExpression.equals(">") || symbolExpression.equals(">>")) { return numberExpression.gt((N) valueConverted); } else if (symbolExpression.equals("<")) { return numberExpression.lt((N) valueConverted); } else if (symbolExpression.equals(">=")) { return numberExpression.goe((N) valueConverted); } else if (symbolExpression.equals("<=")) { return numberExpression.loe((N) valueConverted); } else if (symbolExpression.equals("!=") || symbolExpression.equals("<>")) { return numberExpression.ne((N) valueConverted); } } } // Get all operations String isNullOperation = OPERATOR_ISNULL; String isNotNullOperation = OPERATOR_NOTNULL; String betweenOperation = "BETWEEN"; if (messageSource != null) { isNullOperation = messageSource.getMessage(G_FIL_OPE_ISNULL, null, LocaleContextHolder.getLocale()); isNotNullOperation = messageSource.getMessage(G_FIL_OPE_NOTNULL, null, LocaleContextHolder.getLocale()); betweenOperation = messageSource.getMessage("global.filters.operations.number.between", null, LocaleContextHolder.getLocale()); } // If written function is BETWEEN function Pattern betweenFunctionOperator = Pattern .compile(String.format("%s[(]([-]?[\\d.,]*);([-]?[\\d.,]*)[)]", betweenOperation)); Matcher betweenFunctionMatcher = betweenFunctionOperator.matcher(searchStr); if (betweenFunctionMatcher.matches()) { // Getting valueFrom and valueTo String valueFrom = betweenFunctionMatcher.group(1); String valueTo = betweenFunctionMatcher.group(2); Object valueFromConverted = conversionService.convert(valueFrom, strDesc, descriptor); Object valueToConverted = conversionService.convert(valueTo, strDesc, descriptor); if (!StringUtils.isBlank(valueFrom) && !StringUtils.isBlank(valueTo)) { return numberExpression.between((N) valueFromConverted, (N) valueToConverted); } } // If written expression is ISNULL operation Pattern isNullOperator = Pattern.compile(String.format("%s", isNullOperation)); Matcher isNullMatcher = isNullOperator.matcher(searchStr); if (isNullMatcher.matches()) { return numberExpression.isNull(); } // If written expression is ISNOTNULL operation Pattern isNotNullOperator = Pattern.compile(String.format("%s", isNotNullOperation)); Matcher isNotNullMatcher = isNotNullOperator.matcher(searchStr); if (isNotNullMatcher.matches()) { return numberExpression.isNotNull(); } return null; }
From source file:org.gvnix.web.datatables.util.DatatablesUtils.java
/** * Convert a field value to string/*from ww w.j a v a 2 s. com*/ * * @param datePatterns * @param dateFormatters * @param conversionService * @param entityBean * @param entity * @param fieldName * @param unescapedFieldName * @return */ private static <T> String convertFieldValueToString(Map<String, Object> datePatterns, Map<String, SimpleDateFormat> dateFormatters, ConversionService conversionService, BeanWrapperImpl entityBean, T entity, String fieldName, String unescapedFieldName) { try { Object value = null; TypeDescriptor fieldDesc = entityBean.getPropertyTypeDescriptor(unescapedFieldName); TypeDescriptor strDesc = TypeDescriptor.valueOf(String.class); value = entityBean.getPropertyValue(unescapedFieldName); if (value == null) { return ""; } // For dates if (Date.class.isAssignableFrom(value.getClass()) || Calendar.class.isAssignableFrom(value.getClass())) { SimpleDateFormat formatter = getDateFormatter(datePatterns, dateFormatters, entityBean.getWrappedClass(), unescapedFieldName); if (formatter != null) { if (Calendar.class.isAssignableFrom(value.getClass())) { // Gets Date instance as SimpleDateFormat // doesn't works with Calendar value = ((Calendar) value).getTime(); } return formatter.format(value); } } String stringValue; // Try to use conversion service (uses field descrition // to handle field format annotations) if (conversionService.canConvert(fieldDesc, strDesc)) { stringValue = (String) conversionService.convert(value, fieldDesc, strDesc); if (stringValue == null) { stringValue = ""; } } else { stringValue = ObjectUtils.getDisplayString(value); } return stringValue; } catch (Exception ex) { LOGGER.error(String.format("Error getting value of property [%s] in bean %s [%s]", unescapedFieldName, entity.getClass().getSimpleName(), org.apache.commons.lang3.ObjectUtils.firstNonNull(entity.toString(), "{unknow}")), ex); return ""; } }
From source file:org.springframework.beans.TypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property.//from www. j a v a 2s . c om * @param propertyName name of the property * @param oldValue the previous value, if available (may be {@code null}) * @param newValue the proposed new value * @param requiredType the type we must convert to * (or {@code null} 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") @Nullable public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor) throws IllegalArgumentException { // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException conversionAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { try { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } catch (ConversionFailedException ex) { // fallback to default conversion logic below conversionAttemptEx = ex; } } } Object convertedValue = newValue; // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor(); if (elementTypeDesc != null) { Class<?> elementType = elementTypeDesc.getType(); if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) { 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 (Object.class == requiredType) { return (T) convertedValue; } else 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 == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor<T> strCtor = requiredType.getConstructor(String.class); return 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; } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) { convertedValue = NumberUtils.convertNumberToTargetClass((Number) convertedValue, (Class<Number>) requiredType); standardConversion = true; } } else { // convertedValue == null if (requiredType == Optional.class) { convertedValue = Optional.empty(); } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (conversionAttemptEx != null) { // Original exception from former ConversionService call above... throw conversionAttemptEx; } else if (conversionService != null && typeDescriptor != null) { // ConversionService not tried before, probably custom editor found // but editor couldn't produce the required type... TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } } // 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 (conversionAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) { throw conversionAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", conversionAttemptEx); } return (T) convertedValue; }