Skip to content

Commit 8710100

Browse files
committed
Added Java 8 InstantParam with test.
1 parent cebf1d6 commit 8710100

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package io.dropwizard.jersey.params;
2+
3+
import java.time.Instant;
4+
5+
/**
6+
* A parameter encapsulating date/time values. All non-parsable values will return a {@code 400 Bad Request} response.
7+
*/
8+
public class InstantParam extends AbstractParam<Instant> {
9+
public InstantParam(final String input) {
10+
super(input);
11+
}
12+
13+
public InstantParam(final String input, final String parameterName) {
14+
super(input, parameterName);
15+
}
16+
17+
@Override
18+
protected String errorMessage(Exception e) {
19+
return "%s must be in a ISO-8601 format.";
20+
}
21+
22+
@Override
23+
protected Instant parse(final String input) throws Exception {
24+
return Instant.parse(input);
25+
}
26+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package io.dropwizard.jersey.params;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
5+
6+
import io.dropwizard.jersey.errors.ErrorMessage;
7+
import org.junit.Test;
8+
9+
import java.time.Instant;
10+
import java.time.ZoneOffset;
11+
import java.time.LocalDateTime;
12+
import javax.ws.rs.WebApplicationException;
13+
import javax.ws.rs.core.Response;
14+
15+
public class InstantParamTest {
16+
@Test
17+
public void parsesDateTimes() throws Exception {
18+
final InstantParam param = new InstantParam("2012-11-19T00:00:00Z");
19+
Instant instant = LocalDateTime.of(2012, 11, 19, 0, 0)
20+
.toInstant(ZoneOffset.UTC);
21+
22+
assertThat(param.get())
23+
.isEqualTo(instant);
24+
}
25+
26+
@Test
27+
public void nullThrowsAnException() throws Exception {
28+
try {
29+
new InstantParam(null);
30+
failBecauseExceptionWasNotThrown(WebApplicationException.class);
31+
} catch (WebApplicationException e) {
32+
final Response response = e.getResponse();
33+
34+
assertThat(response.getStatus())
35+
.isEqualTo(400);
36+
37+
ErrorMessage entity = (ErrorMessage) response.getEntity();
38+
assertThat(entity.getCode()).isEqualTo(400);
39+
assertThat(entity.getMessage())
40+
.isEqualTo("Parameter must be in a ISO-8601 format.");
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)