org.springframework.core.convert.ConversionException Java Examples

The following examples show how to use org.springframework.core.convert.ConversionException. 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: ArtifactLinkParameterMappingEntry.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: GenericMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: ConvertingEncoderDecoderSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Decode the a message into an object.
 * @see javax.websocket.Decoder.Text#decode(String)
 * @see javax.websocket.Decoder.Binary#decode(ByteBuffer)
 */
@SuppressWarnings("unchecked")
@Nullable
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;
	}
}
 
Example #4
Source File: ConvertingEncoderDecoderSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
	}
}
 
Example #5
Source File: DataConverter.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** @throws ConversionException if convertion failed or no converter was found */
@SuppressWarnings("unchecked")
@Nullable
@CheckForNull
private static <T> T convert(@Nullable @CheckForNull Object source, Class<T> targetType) {
  if (source == null) {
    return null;
  }

  if (targetType.isAssignableFrom(source.getClass())) {
    return (T) source;
  }

  try {
    return getConversionService().convert(source, targetType);
  } catch (ConversionException e) {
    throw new DataConversionException(e);
  }
}
 
Example #6
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #7
Source File: ConvertingEncoderDecoderSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Decode the a message into an object.
 * @see javax.websocket.Decoder.Text#decode(String)
 * @see javax.websocket.Decoder.Binary#decode(ByteBuffer)
 */
@SuppressWarnings("unchecked")
@Nullable
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;
	}
}
 
Example #8
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #9
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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("%"));
    }
}
 
Example #10
Source File: ConstraintViolationExceptionHandler.java    From spring-rest-exception-handler with Apache License 2.0 5 votes vote down vote up
private String convertToString(Object invalidValue) {

        if (invalidValue == null) {
            return null;
        }
        try {
            return conversionService.convert(invalidValue, String.class);

        } catch (ConversionException ex) {
            return invalidValue.toString();
        }
    }
 
Example #11
Source File: ConvertingEncoderDecoderSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * @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);
	}
}
 
Example #12
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@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("%"));
    }
}
 
Example #13
Source File: StandardTypeConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
	}
}
 
Example #14
Source File: PropertySourcesPropertyResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: PropertySourcesPropertyResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: PropertySourcesPropertyResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: PropertySourcesPropertyResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: GenericMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object fromMessage(Message<?> message, Class<?> targetClass) {
	Object payload = message.getPayload();
	if (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);
}
 
Example #19
Source File: GenericMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object fromMessage(Message<?> message, Class<?> targetClass) {
	Object payload = message.getPayload();
	if (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);
}
 
Example #20
Source File: GenericMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void fromMessageWithFailedConversion() {
	Message<String> content = MessageBuilder.withPayload("test not a number").build();
	assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() ->
			converter.fromMessage(content, Integer.class))
		.withCauseInstanceOf(ConversionException.class);
}
 
Example #21
Source File: StandardTypeConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object convertValue(@Nullable Object value, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
	try {
		return this.conversionService.convert(value, sourceType, targetType);
	}
	catch (ConversionException ex) {
		throw new SpelEvaluationException(ex, SpelMessage.TYPE_CONVERSION_ERROR,
				(sourceType != null ? sourceType.toString() : (value != null ? value.getClass().getName() : "null")),
				targetType.toString());
	}
}
 
Example #22
Source File: ConvertingEncoderDecoderSupport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Encode an object to a message.
 * @see javax.websocket.Encoder.Text#encode(Object)
 * @see javax.websocket.Encoder.Binary#encode(Object)
 */
@SuppressWarnings("unchecked")
@Nullable
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);
	}
}
 
Example #23
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 #24
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 #25
Source File: GenericMessageConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: GenericMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #27
Source File: StandardTypeConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object convertValue(@Nullable Object value, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
	try {
		return this.conversionService.convert(value, sourceType, targetType);
	}
	catch (ConversionException ex) {
		throw new SpelEvaluationException(ex, SpelMessage.TYPE_CONVERSION_ERROR,
				(sourceType != null ? sourceType.toString() : (value != null ? value.getClass().getName() : "null")),
				targetType.toString());
	}
}
 
Example #28
Source File: ConvertingEncoderDecoderSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Encode an object to a message.
 * @see javax.websocket.Encoder.Text#encode(Object)
 * @see javax.websocket.Encoder.Binary#encode(Object)
 */
@SuppressWarnings("unchecked")
@Nullable
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);
	}
}
 
Example #29
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 #30
Source File: StandardTypeConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 != null ? sourceType.toString() : (value != null ? value.getClass().getName() : "null")),
				targetType.toString());
	}
}