diff --git a/jackson-datatype-problem/pom.xml b/jackson-datatype-problem/pom.xml index 8e4962f..d4af726 100644 --- a/jackson-datatype-problem/pom.xml +++ b/jackson-datatype-problem/pom.xml @@ -15,7 +15,7 @@ scm:git:git@github.com:zalando/problem.git - 2.9.8 + 2.9.9 diff --git a/problem/pom.xml b/problem/pom.xml index bc653c8..397a8f4 100644 --- a/problem/pom.xml +++ b/problem/pom.xml @@ -43,6 +43,12 @@ ${junit-jupiter.version} test + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + org.hamcrest java-hamcrest diff --git a/problem/src/main/java/org/zalando/problem/Status.java b/problem/src/main/java/org/zalando/problem/Status.java index 23cc6ab..a48facb 100644 --- a/problem/src/main/java/org/zalando/problem/Status.java +++ b/problem/src/main/java/org/zalando/problem/Status.java @@ -3,6 +3,7 @@ import org.apiguardian.api.API; import javax.annotation.Nonnull; +import java.util.Arrays; import static org.apiguardian.api.API.Status.MAINTAINED; @@ -268,6 +269,20 @@ public enum Status implements StatusType { this.reason = reasonPhrase; } + /** + * Creates a Status instance from the given code. + * + * @param code the HTTP code as a number + * @return the correct enum value for this status code. + * @throws IllegalArgumentException if the given code does not correspond to a known HTTP status. + */ + public static Status ofCode(int code) { + return Arrays.stream(Status.values()) + .filter(status -> status.getStatusCode() == code) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("There is no known status for this code (" + code + ").")); + } + /** * Get the associated status code. * diff --git a/problem/src/test/java/org/zalando/problem/StatusTest.java b/problem/src/test/java/org/zalando/problem/StatusTest.java index 3ea505d..455d509 100644 --- a/problem/src/test/java/org/zalando/problem/StatusTest.java +++ b/problem/src/test/java/org/zalando/problem/StatusTest.java @@ -1,6 +1,9 @@ package org.zalando.problem; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.util.stream.Stream; @@ -26,4 +29,25 @@ void shouldHaveMeaningfulToString() { assertThat(notFound.toString(), equalTo("404 Not Found")); } + + @ParameterizedTest + @CsvSource({ + "409, Conflict", + "404, Not Found", + "200, OK", + "500, Internal Server Error" + }) + void shouldHaveCorrectValueFromCode(int code, String line) { + Status statusFromCode = Status.ofCode(code); + + assertThat(statusFromCode.getStatusCode(), equalTo(code)); + assertThat(statusFromCode.getReasonPhrase(), equalTo(line)); + } + + @Test + void shouldThrowOnNonExistingCode() { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + Status.ofCode(111); + }); + } }