DurationConverter implements PropertyConverter<Duration> { @Override public Duration convert(String value, ConversionContext ctx) { ctx.addSupportedFormats(getClass(), Duration.of(1234, ChronoUnit.SECONDS).toString()); if(value==null){ return null; } try { return Duration.parse(value); }catch(Exception e){ LOG.log(Level.FINEST, e, () -> "Cannot parse Duration: " + value); return null; } }  @Override Duration convert(String value, ConversionContext ctx); @Override boolean equals(Object o); @Override int hashCode();  }
@Test public void convert() throws Exception { DurationConverter conv = new DurationConverter(); Duration duration = conv.convert("PT20.345S", context); assertThat(duration).isEqualTo(Duration.parse("PT20.345S")); duration = conv.convert("PT15M", context); assertThat(duration).isEqualTo(Duration.parse("PT15M")); duration = conv.convert("PT10H", context); assertThat(duration).isEqualTo(Duration.parse("PT10H")); duration = conv.convert("P2D", context); assertThat(duration).isEqualTo(Duration.parse("P2D")); duration = conv.convert("P2DT3H4M", context); assertThat(duration).isEqualTo(Duration.parse("P2DT3H4M")); duration = conv.convert("foo", context); assertThat(duration).isNull(); }
@Test public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception { ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Duration.class)).build(); DurationConverter converter = new DurationConverter(); converter.convert("", context); assertThat(context.getSupportedFormats()).contains("PT20M34S (DurationConverter)"); }