codahale/dropwizard — pull request #115 by nicktelford (2012-06-20 17:28:33+00:00)
Title: Add Min/Max Constraints for Duration and Size

`Duration` and `Size` are highly useful for `Configuration` classes, keeping them human-readable. However, they're limited to validating manually using `ValidationMethod` only.

Specifying an upper and/or lower bounds on such parameters is a very common case, so lets start with implementations for `@Min` and `@Max`.

Unfortunately, because both `Duration` and `Size` convey more information than just a scalar value (the _unit_ of the value), we cannot simply use `@Min` and `@Max`.

Duration
--------

`@MinDuration` and `@MaxDuration` constrain the upper and lower bounds of a `Duration` respectively:

```java
@MinDuration(value = 30, unit = TimeUnit.MINUTES)
@MaxDuration(value = 1, unit = TimeUnit.HOURS)
private Duration timeout = Duration.seconds(1);
```

The _unit_ defaults to `TimeUnit.SECONDS`, so you only need to name parameters if you're providing the unit explcitly:

```java
@MinDuration(30) // 30 seconds minimum
@MaxDuration(3600) // 3600 seconds (1 hour) minimum
private Duration timeout = Duration.seconds(30);
```

Even if you define all `@MinDuration` and `@MaxDuration` constraints in seconds, this allows Configuration files to define value in any time unit that `Duration` understands.

Size
----

`@MinSize` and `@MaxSize` work in much the same way as their sister constraints for `Duration` do, except they constrain a `Size`:

```java
@MinSize(value = 1, unit = SizeUnit.KILOBYTES)
@MaxSize(value = 1, unit = SizeUnit.MEGABYTES)
private Size receiveBuffer = Size.bytes(1024);
```

The default value for _unit_ here is `SizeUnit.BYTES`, allowing you to easily define everything as bytes:

```java
@MinSize(1024) // 1KB min
@MaxSize(10240) // 10KB max
private Size receiveBuffer = Size.bytes(1024);
```

Again, this allows `Confiuration` files to describe their properties using any unit that `Size` understands, whilst still being constrained correctly.

Tests included for happy merging. I was considering a `DurationRange` and `SizeRange` too, but I wanted to be sure this would be accepted before heading in too deep.