JodaTimeSingleFieldPeriodConverter extends AbstractConverter { @Override public Object convert(Object source, TypeToken<?> targetTypeToken) { if (!canHandle(source, targetTypeToken)) { throw new ConverterException(source, targetTypeToken.getRawType()); } Integer period = null; if (source instanceof Number) { period = (Integer) numberToNumberConverter.convert(source, TypeToken.of(Integer.class)); } else if (source instanceof String) { period = (Integer) stringToNumberConverter.convert(source, TypeToken.of(Integer.class)); } Type targetType = targetTypeToken.getType(); if (targetType.equals(Seconds.class)) { return Seconds.seconds(period); } else if (targetType.equals(Minutes.class)) { return Minutes.minutes(period); } else if (targetType.equals(Hours.class)) { return Hours.hours(period); } else if (targetType.equals(Days.class)) { return Days.days(period); } else if (targetType.equals(Weeks.class)) { return Weeks.weeks(period); } else if (targetType.equals(Months.class)) { return Months.months(period); } else if (targetType.equals(Years.class)) { return Years.years(period); } throw new ConverterException(source, targetTypeToken.getRawType()); }  @Override Object convert(Object source, TypeToken<?> targetTypeToken); @Override boolean canHandle(Object source, TypeToken<?> targetTypeToken);  }
@Test public void convert() throws Exception { Integer period = 5; Seconds seconds = (Seconds) converter.convert(period, TypeToken.of(Seconds.class)); assertEquals(5, seconds.getSeconds()); Minutes minutes = (Minutes) converter.convert(period, TypeToken.of(Minutes.class)); assertEquals(5, minutes.getMinutes()); Hours hours = (Hours) converter.convert(period, TypeToken.of(Hours.class)); assertEquals(5, hours.getHours()); Days days = (Days) converter.convert(period, TypeToken.of(Days.class)); assertEquals(5, days.getDays()); Weeks weeks = (Weeks) converter.convert(period, TypeToken.of(Weeks.class)); assertEquals(5, weeks.getWeeks()); Months months = (Months) converter.convert(period, TypeToken.of(Months.class)); assertEquals(5, months.getMonths()); Years years = (Years) converter.convert(period, TypeToken.of(Years.class)); assertEquals(5, years.getYears()); }
@Test(expected = ConverterException.class) public void testConvertExceptionBySource() { converter.convert(new Date(), TypeToken.of(Hours.class)); }
@Test(expected = ConverterException.class) public void testConvertExceptionByDest() { converter.convert(5, TypeToken.of(Duration.class)); }