下面列出了怎么用org.springframework.core.convert.ConversionFailedException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testDefaultFormattersOff() throws Exception {
FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
factory.setRegisterDefaultFormatters(false);
factory.afterPropertiesSet();
FormattingConversionService fcs = factory.getObject();
TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern"));
try {
fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor);
fail("This format should not be parseable");
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof NumberFormatException);
}
}
@Test
public void scalarList() throws Exception {
List<String> list = new ArrayList<>();
list.add("9");
list.add("37");
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(list, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
List<Integer> result = (List<Integer>) conversionService.convert(list, sourceType, targetType);
assertFalse(list.equals(result));
assertEquals(9, result.get(0).intValue());
assertEquals(37, result.get(1).intValue());
}
@Test
public void scalarMap() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("1", "9");
map.put("2", "37");
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
}
@Test
public void scalarMapNotGenericSourceField() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("1", "9");
map.put("2", "37");
TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("notGenericMapSource"));
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
}
@Test
public void collectionMap() throws Exception {
Map<String, List<String>> map = new HashMap<>();
map.put("1", Arrays.asList("9", "12"));
map.put("2", Arrays.asList("37", "23"));
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals(Arrays.asList(9, 12), result.get(1));
assertEquals(Arrays.asList(37, 23), result.get(2));
}
@Override
public PrometheusAlert convert(PrometheusAlertRequest source) {
PrometheusAlert alert = new PrometheusAlert();
alert.setName(source.getAlertName());
alert.setDescription(source.getDescription());
alert.setPeriod(source.getPeriod());
alert.setAlertState(source.getAlertState() != null ? source.getAlertState() : CRITICAL);
double threshold = source.getThreshold();
String alertRuleName = source.getAlertRuleName();
try {
AlertOperator alertOperator = source.getAlertOperator() != null ? source.getAlertOperator() : AlertOperator.MORE_THAN;
String operator = alertOperator.getOperator();
String alertRule = templateService.createAlert(alertRuleName, alert.getName(), String.valueOf(threshold), alert.getPeriod(), operator);
alert.setAlertRule(alertRule);
alert.setParameters(createParametersFrom(threshold, alertOperator));
} catch (Exception e) {
throw new ConversionFailedException(
TypeDescriptor.valueOf(PrometheusAlertRequest.class),
TypeDescriptor.valueOf(PrometheusAlert.class),
source.toString(),
e);
}
return alert;
}
@Test
public void testDefaultFormattersOff() throws Exception {
FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
factory.setRegisterDefaultFormatters(false);
factory.afterPropertiesSet();
FormattingConversionService fcs = factory.getObject();
TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern"));
try {
fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor);
fail("This format should not be parseable");
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof NumberFormatException);
}
}
@Test
public void scalarList() throws Exception {
List<String> list = new ArrayList<>();
list.add("9");
list.add("37");
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(list, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
List<Integer> result = (List<Integer>) conversionService.convert(list, sourceType, targetType);
assertFalse(list.equals(result));
assertEquals(9, result.get(0).intValue());
assertEquals(37, result.get(1).intValue());
}
@Test
public void scalarMap() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("1", "9");
map.put("2", "37");
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
}
@Test
public void scalarMapNotGenericSourceField() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("1", "9");
map.put("2", "37");
TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("notGenericMapSource"));
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
}
@Test
public void collectionMap() throws Exception {
Map<String, List<String>> map = new HashMap<>();
map.put("1", Arrays.asList("9", "12"));
map.put("2", Arrays.asList("37", "23"));
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals(Arrays.asList(9, 12), result.get(1));
assertEquals(Arrays.asList(37, 23), result.get(2));
}
@Test
public void readUnconvertableValueTest() {
this.expectedEx.expect(ConversionFailedException.class);
this.expectedEx.expectMessage("Failed to convert from type [java.lang.String] to type " +
"[java.lang.Double] for value 'UNCONVERTABLE VALUE'; nested exception is " +
"java.lang.NumberFormatException: For input string: \"UNCONVERTABLEVALUE\"");
Struct struct = Struct.newBuilder().set("id").to(Value.string("key1")).set("id2")
.to(Value.string("key2")).set("id3").to(Value.string("key3")).set("id4")
.to(Value.string("key4")).set("intField2").to(Value.int64(333L))
.set("custom_col").to(Value.string("WHITE")).set("booleanField")
.to(Value.bool(true)).set("longField").to(Value.int64(3L))
.set("doubleField").to(Value.string("UNCONVERTABLE VALUE"))
.set("doubleArray")
.to(Value.float64Array(new double[] { 3.33, 3.33, 3.33 }))
.set("dateField").to(Value.date(Date.fromYearMonthDay(2018, 11, 22)))
.set("timestampField")
.to(Value.timestamp(Timestamp.ofTimeMicroseconds(333))).set("bytes")
.to(Value.bytes(ByteArray.copyFrom("string1"))).build();
this.spannerEntityReader.read(TestEntity.class, struct);
}
@Test
public void testDefaultFormattersOff() throws Exception {
FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
factory.setRegisterDefaultFormatters(false);
factory.afterPropertiesSet();
FormattingConversionService fcs = factory.getObject();
TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern"));
try {
fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor);
fail("This format should not be parseable");
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof NumberFormatException);
}
}
@Test
public void scalarList() throws Exception {
List<String> list = new ArrayList<String>();
list.add("9");
list.add("37");
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(list, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
List<String> result = (List<String>) conversionService.convert(list, sourceType, targetType);
assertFalse(list.equals(result));
assertEquals(9, result.get(0));
assertEquals(37, result.get(1));
}
@Test
public void scalarMap() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "9");
map.put("2", "37");
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
} catch (ConversionFailedException e) {
assertTrue(e.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
}
@Test
public void collectionMap() throws Exception {
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("1", Arrays.asList("9", "12"));
map.put("2", Arrays.asList("37", "23"));
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
} catch (ConversionFailedException e) {
assertTrue(e.getCause() instanceof ConverterNotFoundException);
}
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
@SuppressWarnings("unchecked")
Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals(Arrays.asList(9, 12), result.get(1));
assertEquals(Arrays.asList(37, 23), result.get(2));
}
/**
* TypeMismatchException中获取到参数错误类型
*
* @param e
*/
private ModelAndView getParamErrors(TypeMismatchException e) {
Throwable t = e.getCause();
if (t instanceof ConversionFailedException) {
ConversionFailedException x = (ConversionFailedException) t;
TypeDescriptor type = x.getTargetType();
Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
Map<String, String> errors = new HashMap<String, String>();
for (Annotation a : annotations) {
if (a instanceof RequestParam) {
errors.put(((RequestParam) a).value(), "parameter type error!");
}
}
if (errors.size() > 0) {
return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
}
}
JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
/**
* TypeMismatchException中获取到参数错误类型
*
* @param e
*/
private ModelAndView getParamErrors(TypeMismatchException e) {
Throwable t = e.getCause();
if (t instanceof ConversionFailedException) {
ConversionFailedException x = (ConversionFailedException) t;
TypeDescriptor type = x.getTargetType();
Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
Map<String, String> errors = new HashMap<String, String>();
for (Annotation a : annotations) {
if (a instanceof RequestParam) {
errors.put(((RequestParam) a).value(), "parameter type error!");
}
}
if (errors.size() > 0) {
return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
}
}
JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
@Test
void shouldCatchConversionErrors() {
Value value = Values.value("Das funktioniert nicht.");
assertThatExceptionOfType(TypeMismatchDataAccessException.class)
.isThrownBy(() -> defaultNeo4jConverter.readValueForProperty(value, ClassTypeInformation.from(Date.class)))
.withMessageStartingWith("Could not convert \"Das funktioniert nicht.\" into java.util.Date;")
.withCauseInstanceOf(ConversionFailedException.class)
.withRootCauseInstanceOf(DateTimeParseException.class);
}
@Test
void shouldCatchUncoercibleErrors() {
Value value = Values.value("Das funktioniert nicht.");
assertThatExceptionOfType(TypeMismatchDataAccessException.class)
.isThrownBy(() -> defaultNeo4jConverter.readValueForProperty(value, ClassTypeInformation.from(LocalDate.class)))
.withMessageStartingWith("Could not convert \"Das funktioniert nicht.\" into java.time.LocalDate;")
.withCauseInstanceOf(ConversionFailedException.class)
.withRootCauseInstanceOf(Uncoercible.class);
}
@Test
void shouldCheckReturnType() {
when(record.size()).thenReturn(1);
when(record.get(0)).thenReturn(Values.value("Guten Tag."));
SingleValueMappingFunction<Period> mappingFunction = new SingleValueMappingFunction<>(conversionService, Period.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> mappingFunction.apply(typeSystem, record))
.withMessageStartingWith("Failed to convert from type [org.neo4j.driver.internal.value.StringValue] to type [java.time.Period] for value '\"Guten Tag.\"'");
}
@Test
public void receiveAndConvertFailed() {
Message<?> expected = new GenericMessage<>("not a number test");
this.template.setReceiveMessage(expected);
this.template.setMessageConverter(new GenericMessageConverter());
assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() ->
this.template.receiveAndConvert("somewhere", Integer.class))
.withCauseInstanceOf(ConversionFailedException.class);
}
@Test
public void convertListOfNonStringifiable() {
List<Object> list = Arrays.asList(new TestEntity(1L), new TestEntity(2L));
assertTrue(conversionService.canConvert(list.getClass(), String.class));
try {
conversionService.convert(list, String.class);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getMessage().contains(list.getClass().getName()));
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
assertTrue(ex.getCause().getMessage().contains(TestEntity.class.getName()));
}
}
@Test(expected = ConversionFailedException.class)
public void nothingInCommon() throws Exception {
List<Object> resources = new ArrayList<>();
resources.add(new ClassPathResource("test"));
resources.add(3);
TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
}
@Test
public void convertFromStreamToArrayNoConverter() throws NoSuchFieldException {
Stream<Integer> stream = Arrays.asList(1, 2, 3).stream();
TypeDescriptor arrayOfLongs = new TypeDescriptor(Types.class.getField("arrayOfLongs"));
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
this.conversionService.convert(stream, arrayOfLongs))
.withCauseInstanceOf(ConverterNotFoundException.class);
}
@Override
public <T> T convert(Object source, Class<T> targetType) {
try {
return super.convert(source, targetType);
} catch (ConversionFailedException ex) {
String errorMessage = String.format("Failed to convert from type [%s] to type [%s] %s", source.getClass().getName(),
targetType.getName(), ex.getCause().getMessage());
LOGGER.error(errorMessage, ex);
if (ex.getCause() instanceof BadRequestException) {
throw new BadRequestException(ex.getCause().getMessage(), ex.getCause());
}
throw new BadRequestException(errorMessage, ex);
}
}
@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;
}
@Override
public PrometheusAlert convert(PrometheusAlertResponse source) {
PrometheusAlert alert = new PrometheusAlert();
alert.setName(source.getAlertName());
alert.setDescription(source.getDescription());
alert.setPeriod(source.getPeriod());
alert.setAlertState(source.getAlertState() != null ? source.getAlertState() : CRITICAL);
double threshold = source.getThreshold();
String alertRuleName = source.getAlertRuleName();
try {
AlertOperator alertOperator = source.getAlertOperator() != null ? source.getAlertOperator() : AlertOperator.MORE_THAN;
String operator = alertOperator.getOperator();
String alertRule = templateService.createAlert(alertRuleName, alert.getName(), String.valueOf(threshold), alert.getPeriod(), operator);
alert.setAlertRule(alertRule);
alert.setParameters(createParametersFrom(threshold, alertOperator));
if (source.getScalingPolicy() != null) {
ScalingPolicy scalingPolicy = scalingPolicyRequestConverter.convert(source.getScalingPolicy());
scalingPolicy.setAlert(alert);
alert.setScalingPolicy(scalingPolicy);
}
} catch (Exception e) {
throw new ConversionFailedException(
TypeDescriptor.valueOf(PrometheusAlertRequest.class),
TypeDescriptor.valueOf(PrometheusAlert.class),
source.toString(),
e);
}
return alert;
}
@Test
public void receiveAndConvertFailed() {
Message<?> expected = new GenericMessage<>("not a number test");
this.template.setReceiveMessage(expected);
this.template.setMessageConverter(new GenericMessageConverter());
thrown.expect(MessageConversionException.class);
thrown.expectCause(isA(ConversionFailedException.class));
this.template.receiveAndConvert("somewhere", Integer.class);
}
@Test
public void convertListOfNonStringifiable() {
List<Object> list = Arrays.asList(new TestEntity(1L), new TestEntity(2L));
assertTrue(conversionService.canConvert(list.getClass(), String.class));
try {
conversionService.convert(list, String.class);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getMessage().contains(list.getClass().getName()));
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
assertTrue(ex.getCause().getMessage().contains(TestEntity.class.getName()));
}
}