use of org.springframework.beans.ConfigurablePropertyAccessor in project spring-framework by spring-projects.
the class FormattingConversionServiceTests method doTestFormatFieldForAnnotation.
@SuppressWarnings("unchecked")
private void doTestFormatFieldForAnnotation(Class<?> modelClass, boolean directFieldAccess) throws Exception {
formattingService.addConverter(new Converter<Date, Long>() {
@Override
public Long convert(Date source) {
return source.getTime();
}
});
formattingService.addConverter(new Converter<DateTime, Date>() {
@Override
public Date convert(DateTime source) {
return source.toDate();
}
});
String formatted = (String) formattingService.convert(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime().toDate(), new TypeDescriptor(modelClass.getField("date")), TypeDescriptor.valueOf(String.class));
assertEquals("10/31/09", formatted);
LocalDate date = new LocalDate(formattingService.convert("10/31/09", TypeDescriptor.valueOf(String.class), new TypeDescriptor(modelClass.getField("date"))));
assertEquals(new LocalDate(2009, 10, 31), date);
List<Date> dates = new ArrayList<>();
dates.add(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime().toDate());
dates.add(new LocalDate(2009, 11, 1).toDateTimeAtCurrentTime().toDate());
dates.add(new LocalDate(2009, 11, 2).toDateTimeAtCurrentTime().toDate());
formatted = (String) formattingService.convert(dates, new TypeDescriptor(modelClass.getField("dates")), TypeDescriptor.valueOf(String.class));
assertEquals("10-31-09,11-1-09,11-2-09", formatted);
dates = (List<Date>) formattingService.convert("10-31-09,11-1-09,11-2-09", TypeDescriptor.valueOf(String.class), new TypeDescriptor(modelClass.getField("dates")));
assertEquals(new LocalDate(2009, 10, 31), new LocalDate(dates.get(0)));
assertEquals(new LocalDate(2009, 11, 1), new LocalDate(dates.get(1)));
assertEquals(new LocalDate(2009, 11, 2), new LocalDate(dates.get(2)));
Object model = modelClass.newInstance();
ConfigurablePropertyAccessor accessor = directFieldAccess ? PropertyAccessorFactory.forDirectFieldAccess(model) : PropertyAccessorFactory.forBeanPropertyAccess(model);
accessor.setConversionService(formattingService);
accessor.setPropertyValue("dates", "10-31-09,11-1-09,11-2-09");
dates = (List<Date>) accessor.getPropertyValue("dates");
assertEquals(new LocalDate(2009, 10, 31), new LocalDate(dates.get(0)));
assertEquals(new LocalDate(2009, 11, 1), new LocalDate(dates.get(1)));
assertEquals(new LocalDate(2009, 11, 2), new LocalDate(dates.get(2)));
if (!directFieldAccess) {
accessor.setPropertyValue("dates[0]", "10-30-09");
accessor.setPropertyValue("dates[1]", "10-1-09");
accessor.setPropertyValue("dates[2]", "10-2-09");
dates = (List<Date>) accessor.getPropertyValue("dates");
assertEquals(new LocalDate(2009, 10, 30), new LocalDate(dates.get(0)));
assertEquals(new LocalDate(2009, 10, 1), new LocalDate(dates.get(1)));
assertEquals(new LocalDate(2009, 10, 2), new LocalDate(dates.get(2)));
}
}
Aggregations