Skip to content

Commit

Permalink
more flexible json-deserializaton via jsoncreator and String
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian Strandenæs committed Mar 25, 2020
1 parent 4b20f27 commit 7beb89c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
23 changes: 20 additions & 3 deletions src/main/java/no/digipost/api/datatypes/types/proof/Period.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package no.digipost.api.datatypes.types.proof;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
Expand All @@ -14,6 +16,9 @@
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;

@XmlType
@Value
Expand All @@ -32,9 +37,21 @@ public class Period {
LocalDateTime to;

@Deprecated
public Period(ZonedDateTime from, ZonedDateTime to) {
this(from != null ? from.withZoneSameInstant(ZoneId.of("Europe/Oslo")).toLocalDateTime() : null,
to != null ? to.withZoneSameInstant(ZoneId.of("Europe/Oslo")).toLocalDateTime() : null);
@JsonCreator
public Period(@JsonProperty("from") String from, @JsonProperty("to") String to) {
this(localDate(from), localDate(to));
}

private static LocalDateTime localDate(String datetime) {
if (datetime == null) {
return null;
}
final TemporalAccessor parsed = DateTimeFormatter.ISO_DATE_TIME.parse(datetime);
if (parsed.isSupported(ChronoField.OFFSET_SECONDS)) {
return ZonedDateTime.from(parsed).withZoneSameInstant(ZoneId.of("Europe/Oslo")).toLocalDateTime();
} else {
return LocalDateTime.from(parsed);
}
}

public static Period EXAMPLE = new Period(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
Expand Down Expand Up @@ -57,8 +58,8 @@ void period() {
@Test
void deprecated_constructor_period_should_give_correct_norwegian_time() {
Period period = new Period(
ZonedDateTime.of(2019, 8, 1, 0, 0, 0, 0, ZoneId.of("+02:00")),
ZonedDateTime.of(2022, 8, 1, 0, 0, 0, 0, ZoneId.of("+02:00"))
DateTimeFormatter.ISO_DATE_TIME.format(ZonedDateTime.of(2019, 8, 1, 0, 0, 0, 0, ZoneId.of("+02:00"))),
DateTimeFormatter.ISO_DATE_TIME.format(ZonedDateTime.of(2022, 8, 1, 0, 0, 0, 0, ZoneId.of("+02:00")))
);

assertThat(period.getISO8601(), equalTo("2019-08-01T00:00/2022-08-01T00:00"));
Expand Down

0 comments on commit 7beb89c

Please sign in to comment.