|
5 | 5 |
|
6 | 6 | import java.nio.ByteBuffer; |
7 | 7 | import java.nio.charset.StandardCharsets; |
| 8 | +import java.util.List; |
8 | 9 |
|
9 | 10 | public enum HTTPStatus implements HTTPResponse { |
10 | 11 | // 1xx - Informational |
@@ -64,28 +65,39 @@ public enum HTTPStatus implements HTTPResponse { |
64 | 65 | ; |
65 | 66 |
|
66 | 67 | private static final HTTPStatus[] VALUES = values(); |
| 68 | + public static final List<HTTPStatus> ALL = List.of(VALUES); |
| 69 | + public static final List<HTTPStatus> INFORMATIONAL = List.copyOf(ALL.stream().filter(HTTPStatus::informational).toList()); |
| 70 | + public static final List<HTTPStatus> SUCCESS = List.copyOf(ALL.stream().filter(HTTPStatus::success).toList()); |
| 71 | + public static final List<HTTPStatus> REDIRECT = List.copyOf(ALL.stream().filter(HTTPStatus::redirect).toList()); |
| 72 | + public static final List<HTTPStatus> CLIENT_ERROR = List.copyOf(ALL.stream().filter(HTTPStatus::clientError).toList()); |
| 73 | + public static final List<HTTPStatus> SERVER_ERROR = List.copyOf(ALL.stream().filter(HTTPStatus::serverError).toList()); |
| 74 | + public static final List<List<HTTPStatus>> LOOKUP = List.of(INFORMATIONAL, SUCCESS, REDIRECT, CLIENT_ERROR, SERVER_ERROR); |
67 | 75 |
|
68 | 76 | @Nullable |
69 | 77 | public static HTTPStatus fromCode(int code) { |
70 | 78 | if (code < 100 || code > 599) { |
71 | 79 | return null; |
72 | 80 | } |
73 | 81 |
|
74 | | - for (var status : VALUES) { |
75 | | - if (status.statusCode.code() == code) { |
| 82 | + for (var status : LOOKUP.get(code / 100 - 1)) { |
| 83 | + if (status.code == code) { |
76 | 84 | return status; |
77 | 85 | } |
78 | 86 | } |
79 | 87 |
|
80 | 88 | return null; |
81 | 89 | } |
82 | 90 |
|
| 91 | + private final int code; |
83 | 92 | private final StatusCode statusCode; |
84 | 93 | private final ByteBuffer responseBuffer; |
| 94 | + private final String string; |
85 | 95 |
|
86 | 96 | HTTPStatus(int code, String message) { |
| 97 | + this.code = code; |
87 | 98 | this.statusCode = new StatusCode(code, message); |
88 | 99 | this.responseBuffer = ByteBuffer.wrap(("HTTP/1.1 " + statusCode.code() + " " + statusCode.message() + "\r\n").getBytes(StandardCharsets.UTF_8)); |
| 100 | + this.string = Integer.toString(code); |
89 | 101 | } |
90 | 102 |
|
91 | 103 | @Override |
@@ -128,4 +140,13 @@ public boolean serverError() { |
128 | 140 | public boolean error() { |
129 | 141 | return statusCode.code() >= 400; |
130 | 142 | } |
| 143 | + |
| 144 | + public int code() { |
| 145 | + return code; |
| 146 | + } |
| 147 | + |
| 148 | + @Override |
| 149 | + public String toString() { |
| 150 | + return string; |
| 151 | + } |
131 | 152 | } |
0 commit comments