org.springframework.core.convert.ConversionFailedException Java Examples

The following examples show how to use org.springframework.core.convert.ConversionFailedException. 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: MyExceptionHandler.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #2
Source File: FormattingConversionServiceFactoryBeanTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #3
Source File: CollectionToCollectionConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
}
 
Example #4
Source File: MapToMapConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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));
}
 
Example #5
Source File: MapToMapConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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));
}
 
Example #6
Source File: MapToMapConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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));
}
 
Example #7
Source File: PrometheusAlertRequestConverter.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: FormattingConversionServiceFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #9
Source File: CollectionToCollectionConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #10
Source File: MapToMapConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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));
}
 
Example #11
Source File: ConverterAwareMappingSpannerEntityReaderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: FormattingConversionServiceFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #13
Source File: CollectionToCollectionConverterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #14
Source File: MapToMapConverterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #15
Source File: MapToMapConverterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #16
Source File: MapToMapConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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));
}
 
Example #17
Source File: MyExceptionHandler.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: MapToMapConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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));
}
 
Example #19
Source File: MapToJsonByteArrayConverter.java    From spring-integration-zmq with Apache License 2.0 5 votes vote down vote up
public byte[] convert(Map<Object, Object> map) {
	try {
		return mapper.writeValueAsBytes(map);
	} catch (IOException e) {
		throw new ConversionFailedException(
				TypeDescriptor.valueOf(Map.class), 
				TypeDescriptor.valueOf(byte[].class), 
				map, e);
	}
}
 
Example #20
Source File: MsgpackContainerToByteArrayConverter.java    From spring-integration-zmq with Apache License 2.0 5 votes vote down vote up
public byte[] convert(MsgpackContainer container) {
	try {
		return msgpack.write(container);
	} catch (IOException e) {
		throw new ConversionFailedException(
				TypeDescriptor.valueOf(MsgpackContainer.class), 
				TypeDescriptor.valueOf(byte[].class), 
				container, e);
	}
}
 
Example #21
Source File: StreamConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void convertFromStreamToArrayNoConverter() throws NoSuchFieldException {
	Stream<Integer> stream = Arrays.asList(1, 2, 3).stream();
	TypeDescriptor arrayOfLongs = new TypeDescriptor(Types.class.getField("arrayOfLongs")); ;

	thrown.expect(ConversionFailedException.class);
	thrown.expectCause(is(instanceOf(ConverterNotFoundException.class)));
	this.conversionService.convert(stream, arrayOfLongs);
}
 
Example #22
Source File: CollectionToCollectionConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = ConversionFailedException.class)
public void nothingInCommon() throws Exception {
	List<Object> resources = new ArrayList<Object>();
	resources.add(new ClassPathResource("test"));
	resources.add(3);
	TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
	assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
}
 
Example #23
Source File: MessageReceivingTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void receiveAndConvertFailed() {
	Message<?> expected = new GenericMessage<Object>("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);
}
 
Example #24
Source File: JacksonObjectToJsonConverter.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given {@link Object} into {@link String JSON}.
 *
 * @param source {@link Object} to convert into {@link String JSON}.
 * @return {@link String JSON} generated from the given {@link Object} using Jackson's {@link ObjectMapper}.
 * @throws IllegalArgumentException if {@link Object source} is {@literal null}.
 * @throws ConversionFailedException if a {@link JsonProcessingException} is thrown or another error occurs
 * while trying to convert the given {@link Object} to {@link String JSON}.
 * @see com.fasterxml.jackson.databind.ObjectMapper
 * @see #convertObjectToJson(Object)
 */
@Override
public @NonNull String convert(@NonNull Object source) {

	Assert.notNull(source, "Source object to convert must not be null");

	try {
		return convertObjectToJson(source);
	}
	catch (JsonProcessingException cause) {
		throw new ConversionFailedException(TypeDescriptor.forObject(source), TypeDescriptor.valueOf(String.class),
			source, cause);
	}
}
 
Example #25
Source File: DefaultDatastoreEntityConverterTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testMismatchedLongIdStringProperty() {
	this.thrown.expect(ConversionFailedException.class);
	this.thrown.expectMessage(
			"The given key doesn't have a String name value but a conversion to String was attempted");
	ENTITY_CONVERTER.read(StringIdEntity.class,
			Entity.newBuilder(this.datastore.newKeyFactory().setKind("aKind").newKey(1)).build());
}
 
Example #26
Source File: StreamConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example #27
Source File: StringGenericConverter.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    if (ObjectUtils.isEmpty(source)){
        return defaultValue;
    }
    try {
        return doConvert(source.toString().trim());
    } catch (Exception e){
        throw new ConversionFailedException(TypeDescriptor.forObject(source),
                TypeDescriptor.valueOf(this.targetType),source,e);
    }
}
 
Example #28
Source File: AbstractPropertyAccessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setPropertyIntermediateListIsNullWithBadConversionService() {
	Foo target = new Foo();
	AbstractPropertyAccessor accessor = createAccessor(target);
	accessor.setConversionService(new GenericConversionService() {
		@Override
		public Object convert(@Nullable Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
			throw new ConversionFailedException(sourceType, targetType, source, null);
		}
	});
	accessor.setAutoGrowNestedPaths(true);
	accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9");
	assertEquals("9", target.listOfMaps.get(0).get("luckyNumber"));
}
 
Example #29
Source File: DefaultNeo4jConverterTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: CloudbreakConversionServiceFactoryBean.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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);
    }
}