diff --git a/src/main/java/org/hisp/dhis/response/HttpStatus.java b/src/main/java/org/hisp/dhis/response/HttpStatus.java index 47aee787..c934c5fd 100644 --- a/src/main/java/org/hisp/dhis/response/HttpStatus.java +++ b/src/main/java/org/hisp/dhis/response/HttpStatus.java @@ -27,6 +27,7 @@ */ package org.hisp.dhis.response; +import com.fasterxml.jackson.annotation.JsonCreator; import org.hisp.dhis.model.exception.IllegalArgumentFormatException; /** Enumeration of HTTP status codes. */ @@ -208,6 +209,22 @@ public static HttpStatus valueOf(int statusCode) { return status; } + /** + * Return the enum constant of this type with the specified name. + * + * @param name the enum name of the enum to be returned + * @return the enum constant with the specified name + * @throws IllegalArgumentException if this enum has no constant for the specified name + */ + @JsonCreator + public static HttpStatus fromName(String name) { + try { + return Enum.valueOf(HttpStatus.class, name); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentFormatException("No matching name for status code: {}", name); + } + } + /** * Resolve the given status code to an {@code HttpStatus}, if possible. * diff --git a/src/test/java/org/hisp/dhis/response/HttpStatusTest.java b/src/test/java/org/hisp/dhis/response/HttpStatusTest.java index 34191e28..a4521f45 100644 --- a/src/test/java/org/hisp/dhis/response/HttpStatusTest.java +++ b/src/test/java/org/hisp/dhis/response/HttpStatusTest.java @@ -54,4 +54,21 @@ void testValueOfNotFound() { assertNotNull(exception); assertEquals("No matching constant for status code: 999", exception.getMessage()); } + + @Test + void testFromName() { + assertEquals(HttpStatus.OK, HttpStatus.fromName(HttpStatus.OK.name())); + assertEquals(HttpStatus.CONFLICT, HttpStatus.fromName(HttpStatus.CONFLICT.name())); + assertEquals(HttpStatus.UNKNOWN_STATUS, HttpStatus.fromName(HttpStatus.UNKNOWN_STATUS.name())); + assertEquals(HttpStatus.NO_STATUS, HttpStatus.fromName(HttpStatus.NO_STATUS.name())); + } + + @Test + void testFromNameNotFound() { + IllegalArgumentFormatException exception = + assertThrows(IllegalArgumentFormatException.class, () -> HttpStatus.fromName("INVALID")); + + assertNotNull(exception); + assertEquals("No matching name for status code: INVALID", exception.getMessage()); + } }