Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/org/hisp/dhis/response/HttpStatus.java
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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.
*
Expand Down
17 changes: 17 additions & 0 deletions src/test/java/org/hisp/dhis/response/HttpStatusTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}
Loading