@Override public Object fromMessage(Message<?> message, Class<?> targetClass) { Object payload = message.getPayload(); if (targetClass == null) { return payload; } if (payload != null && this.conversionService.canConvert(payload.getClass(), targetClass)) { try { return this.conversionService.convert(payload, targetClass); } catch (ConversionException ex) { throw new MessageConversionException(message, "Failed to convert message payload '" + payload + "' to '" + targetClass.getName() + "'", ex); } } return (ClassUtils.isAssignableValue(targetClass, payload) ? payload : null); }
/** * @see javax.websocket.Decoder.Text#decode(String) * @see javax.websocket.Decoder.Binary#decode(ByteBuffer) */ @SuppressWarnings("unchecked") public T decode(M message) throws DecodeException { try { return (T) getConversionService().convert(message, getMessageType(), getType()); } catch (ConversionException ex) { if (message instanceof String) { throw new DecodeException((String) message, "Unable to decode websocket message using ConversionService", ex); } if (message instanceof ByteBuffer) { throw new DecodeException((ByteBuffer) message, "Unable to decode websocket message using ConversionService", ex); } throw ex; } }
/** * 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 * * @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; } }
protected <T> void inject(PageParameters targetParameters, ILinkParameterConversionService conversionService, String parameterName, T mappedValue) throws LinkParameterInjectionException { Args.notNull(targetParameters, "targetParameters"); Args.notNull(conversionService, "conversionService"); String parameterValue = null; if (mappedValue != null) { try { parameterValue = conversionService.convert(mappedValue, String.class); } catch (ConversionException e) { throw new LinkParameterInjectionException("Error converting the value of parameter " + parameterName, e); } if (parameterValue != null) { targetParameters.add(parameterName, parameterValue); } } }
protected <T> T extract(PageParameters sourceParameters, ILinkParameterConversionService conversionService, String parameterName, Class<? extends T> mappedType) throws LinkParameterExtractionException { Args.notNull(sourceParameters, "sourceParameters"); Args.notNull(conversionService, "conversionService"); String parameterValue = sourceParameters.get(parameterName).toString(); T mappedValue = null; if (parameterValue != null) { try { mappedValue = conversionService.convert(parameterValue, mappedType); } catch (ConversionException e) { throw new LinkParameterExtractionException("Error converting the value of parameter " + parameterName, e); } } return mappedValue; }
protected Object extract(PageParameters sourceParameters, ILinkParameterConversionService conversionService, String parameterName, TypeDescriptor mappedTypeDescriptor) throws LinkParameterExtractionException { Args.notNull(sourceParameters, "sourceParameters"); Args.notNull(conversionService, "conversionService"); String parameterValue = sourceParameters.get(parameterName).toString(); Object mappedValue = null; if (parameterValue != null) { try { mappedValue = conversionService.convert(parameterValue, TypeDescriptor.valueOf(String.class), mappedTypeDescriptor); } catch (ConversionException e) { throw new LinkParameterExtractionException("Error converting the value of parameter " + parameterName, e); } } return mappedValue; }
@Override public void extract(PageParameters sourceParameters, ILinkParameterConversionService conversionService) throws LinkParameterExtractionException { Args.notNull(sourceParameters, "sourceParameters"); Args.notNull(conversionService, "conversionService"); String groupId = sourceParameters.get(GROUP_ID_PARAMETER).toString(); String artifactId = sourceParameters.get(ARTIFACT_ID_PARAMETER).toString(); Artifact artifact = null; if (groupId != null && artifactId != null) { ArtifactKey artifactKey = new ArtifactKey(groupId, artifactId); try { artifact = conversionService.convert(artifactKey, Artifact.class); } catch (ConversionException e) { throw new LinkParameterExtractionException(e); } } artifactModel.setObject(artifact); }
@Override public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) { try { return this.conversionService.convert(value, sourceType, targetType); } catch (ConversionException ex) { throw new SpelEvaluationException( ex, SpelMessage.TYPE_CONVERSION_ERROR, sourceType.toString(), targetType.toString()); } }
@Test public void fromMessageWithFailedConversion() { Message<String> content = MessageBuilder.withPayload("test not a number").build(); thrown.expect(MessageConversionException.class); thrown.expectCause(isA(ConversionException.class)); converter.fromMessage(content, Integer.class); }
@Test(expected=ConversionException.class) public void getPropertyAsClass_withMismatchedTypeForValue() { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("some.class", "java.lang.String")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); resolver.getPropertyAsClass("some.class", SomeType.class); }
@Test(expected=ConversionException.class) public void getPropertyAsClass_withNonExistentClassForValue() { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("some.class", "some.bogus.Class")); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); resolver.getPropertyAsClass("some.class", SomeType.class); }
@Test(expected=ConversionException.class) public void getPropertyAsClass_withMismatchedObjectForValue() { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("some.class", new Integer(42))); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); resolver.getPropertyAsClass("some.class", SomeType.class); }
@Test(expected=ConversionException.class) public void getPropertyAsClass_withMismatchedRealClassForValue() { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new MockPropertySource().withProperty("some.class", Integer.class)); PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources); resolver.getPropertyAsClass("some.class", SomeType.class); }
/** * @see javax.websocket.Encoder.Text#encode(Object) * @see javax.websocket.Encoder.Binary#encode(Object) */ @SuppressWarnings("unchecked") public M encode(T object) throws EncodeException { try { return (M) getConversionService().convert(object, getType(), getMessageType()); } catch (ConversionException ex) { throw new EncodeException(object, "Unable to encode websocket message using ConversionService", ex); } }
/** * Return where clause expression for number properties by casting it to * string before check its value. * <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("%")); } }
/** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <T, N extends Number & Comparable<?>> BooleanExpression createNumberExpressionEqual( PathBuilder<T> entityPath, String fieldName, Class<N> fieldType, TypeDescriptor descriptor, String searchStr) { 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("%")); } }
@ExceptionHandler({ ServletRequestBindingException.class, HttpMessageConversionException.class, ConversionException.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorBean handleMissingParameterException(Exception exception, Locale locale) { return createErrorBean(extractExceptionName(exception), locale, exception); }
public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) { try { return this.conversionService.convert(value, sourceType, targetType); } catch (ConversionException ex) { throw new SpelEvaluationException( ex, SpelMessage.TYPE_CONVERSION_ERROR, sourceType.toString(), targetType.toString()); } }
private String convertToString(Object invalidValue) { if (invalidValue == null) { return null; } try { return conversionService.convert(invalidValue, String.class); } catch (ConversionException ex) { return invalidValue.toString(); } }
@ExceptionHandler(ConversionException.class) @ResponseStatus(BAD_REQUEST) public ErrorMessageResponse handleConversionException(ConversionException e) { LOG.info("", e); return new ErrorMessageResponse(new ErrorMessage(e.getMessage())); }
/** * Return where clause expression for number properties by casting it to * string before check its value. * <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; }
/** * {@inheritDoc} */ @Override public <T, N extends Number & Comparable<?>> BooleanExpression createNumberExpression( PathBuilder<T> entityPath, String fieldName, Class<N> fieldType, TypeDescriptor descriptor, String searchStr) { 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; }