smallrye-config icon indicating copy to clipboard operation
smallrye-config copied to clipboard

Add 3 bundled converters for DateTimeFormatter, DateFormat, CharSequence

Open magicprinc opened this issue 1 year ago • 3 comments

.withConverter(DateFormat.class, 100, SimpleDateFormat::new)
.withConverter(DateTimeFormatter.class, 100, DateTimeFormatter::ofPattern)
.withConverter(CharSequence.class, 100, Object::toString)

magicprinc avatar Jan 15 '24 20:01 magicprinc

And probably Locale… Current Locale conversion is quite bad.

How about:

.withConverter(Locale.class, 101, s->{
  if (s == null || s.isBlank()){
    return null;
  } else if (found(s.indexOf('-'))){
    return Locale.forLanguageTag(trim(s));// de-DE
  } else {// uses Guava, because it is a copy-paste of real code. Can be replaced with String.split
    List<String> elements = Splitter.on('_').limit(3).trimResults().splitToList(s);
    return elements.size() == 1 ? new Locale(elements.get(0)) // de
      : elements.size() == 2 ? new Locale(elements.get(0), elements.get(1)) // de_DE
        : new Locale(elements.get(0), elements.get(1), elements.get(2));
  }
})

magicprinc avatar Jan 23 '24 21:01 magicprinc

We don't provide a specific Locale converter. In cases where there isn't one, an implicit Converter is determined by a lookup of static methods of, valueOf, parse, and String constructor (which matches how a Locale is converted).

This may be inconvenient in some cases, but it does cover a big spectrum of combinations. Feel free to provide a PR to improve it. Thank you!

radcortez avatar Jan 24 '24 11:01 radcortez

Example application. Shows

  1. Spring / Spring Boot integration (2/3 steps: SmallRyeConfig bean, integration into Environment/@Value; × @ConfigProperty)
  2. useful one line converters: DateFormat, DateTimeFormatter, CharSequence, Charset, Locale

https://github.com/magicprinc/SmallRyeConfig-SpringBoot

magicprinc avatar Mar 23 '24 22:03 magicprinc