Working with Durations - advantageous/konf GitHub Wiki

Konf, the type safe Java configuration library, has a way to configure java.time.Duration. You use the getDuration(path) and getDurationList(path) method to read a duration from a location.

Different way to configure duration

var config = {
  tenSeconds: seconds(10),
  tenDays: days(10),
  tenMinutes: minutes(10),
  tenHours: hours(10),
  tenMillis: millis(10),
  tenMilliseconds: milliseconds(10),
  fifteenMinutes: "PT15M",
  tenSeconds2: "10 seconds",
  tenMinutes2: "10m",
  tenHours2: "10 h",
  tenDays2: "10 day",
  tenMillis2: "10ms"
};

TypeSafe Config style

Duration can be specified with time (type safe config style).

You can postFix the type value in a string with any of these prefixes.

Typesafe config style postfixes

ns, nano, nanos, nanosecond, nanoseconds
us, micro, micros, microsecond, microseconds
ms, milli, millis, millisecond, milliseconds
s, second, seconds
m, minute, minutes
h, hour, hours
d, day, days

ISO-8601 Duration

Konf also supports ISO-8601 duration format, i.e., PT15M.

Built-in functions for Duration

There are also built-in functions for durations using seconds(5), minutes(5), etc.

Example usage

First we load the config.

Load the config

    private Config config;

    @Before
    public void setUp() throws Exception {
        config = ConfigLoader.load("test-config.js");
    }

Then we use getDuration(path) to read the Duration values.


        assertEquals(Duration.ofMillis(10), 
               config.getDuration("tenMillis"));

        assertEquals(Duration.ofMillis(10), 
                  config.getDuration("tenMilliseconds"));

        assertEquals(Duration.ofSeconds(10), config.getDuration("tenSeconds"));
        assertEquals(Duration.ofMinutes(10), config.getDuration("tenMinutes"));
        assertEquals(Duration.ofHours(10), config.getDuration("tenHours"));
        assertEquals(Duration.ofDays(10), config.getDuration("tenDays"));

        assertEquals(Duration.ofMinutes(15), 
                                 config.getDuration("fifteenMinutes"));

        assertEquals(Duration.ofSeconds(10), config.getDuration("tenSeconds2"));
        assertEquals(Duration.ofMinutes(10), config.getDuration("tenMinutes2"));
        assertEquals(Duration.ofHours(10), config.getDuration("tenHours2"));
        assertEquals(Duration.ofDays(10), config.getDuration("tenDays2"));
        assertEquals(Duration.ofMillis(10), config.getDuration("tenMillis2"));
        assertEquals(Duration.ofMillis(10), config.getDuration("tenMilliseconds2"));