001/*
002 * Copyright 2022-2025 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet.core;
018
019import javax.annotation.Nonnull;
020import java.util.Collections;
021import java.util.HashMap;
022import java.util.Map;
023import java.util.Optional;
024
025import static java.lang.String.format;
026import static java.util.Objects.requireNonNull;
027
028/**
029 * Formal enumeration of valid HTTP status codes.
030 * <p>
031 * See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">https://developer.mozilla.org/en-US/docs/Web/HTTP/Status</a> for details.
032 *
033 * @author <a href="https://www.revetkn.com">Mark Allen</a>
034 */
035public enum StatusCode {
036        /**
037         * This interim response indicates that the client should continue the request or ignore the response if the request is already finished.
038         */
039        HTTP_100(100, "Continue"),
040        /**
041         * This code is sent in response to an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade">Upgrade</a> request header from the client and indicates the protocol the server is switching to.
042         */
043        HTTP_101(101, "Switching Protocols"),
044        /**
045         * This code was used in <a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a> contexts to indicate that a request has been received by the server, but no status was available at the time of the response.
046         */
047        HTTP_102(102, "Processing"),
048        /**
049         * This status code is primarily intended to be used with the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link">Link</a> header, letting the user agent start <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preload">preloading</a> resources while the server prepares a response or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preconnect">preconnect</a> to an origin from which the page will need resources.
050         */
051        HTTP_103(103, "Early Hints"),
052        /**
053         * The request succeeded. The result and meaning of "success" depends on the HTTP method:
054         * <p>
055         * <ul>
056         * <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET</a>: The resource has been fetched and transmitted in the message body.</li>
057         * <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD">HEAD</a>: Representation headers are included in the response without any message body.</li>
058         * <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">PUT</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a>: The resource describing the result of the action is transmitted in the message body.</li>
059         * <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE">TRACE</a>: The message body contains the request as received by the server.</li>
060         * </ul>
061         */
062        HTTP_200(200, "OK"),
063        /**
064         * The request succeeded, and a new resource was created as a result.
065         * <p>
066         * This is typically the response sent after <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a> requests, or some <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">PUT</a> requests.
067         */
068        HTTP_201(201, "Created"),
069        /**
070         * The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request.
071         * <p>
072         * It is intended for cases where another process or server handles the request, or for batch processing.
073         */
074        HTTP_202(202, "Accepted"),
075        /**
076         * This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy.
077         * <p>
078         * This is mostly used for mirrors or backups of another resource. Except for that specific case, the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200">200 OK</a> response is preferred to this status.
079         */
080        HTTP_203(203, "Non-Authoritative Information"),
081        /**
082         * There is no content to send for this request, but the headers are useful.
083         * <p>
084         * The user agent may update its cached headers for this resource with the new ones.
085         */
086        HTTP_204(204, "No Content"),
087        /**
088         * Tells the user agent to reset the document which sent this request.
089         */
090        HTTP_205(205, "Reset Content"),
091        /**
092         * This response code is used in response to a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests">range request</a> when the client has requested a part or parts of a resource.
093         * <p>
094         * Soklet does not currently support <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests">range requests</a> out-of-the-box.
095         */
096        HTTP_206(206, "Partial Content"),
097        /**
098         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
099         */
100        HTTP_207(207, "Multi-Status"),
101        /**
102         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) Used inside a {@code <dav:propstat>} response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
103         */
104        HTTP_208(208, "Already Reported"),
105        /**
106         * (<a href="https://datatracker.ietf.org/doc/html/rfc3229">HTTP Delta encoding</a>) The server has fulfilled a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET</a> request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
107         */
108        HTTP_226(226, "IM Used"),
109        /**
110         * In <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation#agent-driven_negotiation">agent-driven content negotiation</a>, the request has more than one possible response and the user agent or user should choose one of them.
111         * <p>
112         * There is no standardized way for clients to automatically choose one of the responses, so this is rarely used.
113         */
114        HTTP_300(300, "Multiple Choices"),
115        /**
116         * The URL of the requested resource has been changed permanently.
117         * <p>
118         * The new URL is given in the response.
119         */
120        HTTP_301(301, "Moved Permanently"),
121        /**
122         * This response code means that the URI of requested resource has been changed <em>temporarily</em>.
123         * <p>
124         * Further changes in the URI might be made in the future, so the same URI should be used by the client in future requests.
125         */
126        HTTP_302(302, "Found"),
127        /**
128         * The server sent this response to direct the client to get the requested resource at another URI with a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET</a> request.
129         */
130        HTTP_303(303, "See Other"),
131        /**
132         * This is used for caching purposes.
133         * <p>
134         * It tells the client that the response has not been modified, so the client can continue to use the same <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching">cached</a> version of the response.
135         */
136        HTTP_304(304, "Not Modified"),
137        /**
138         * Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy.
139         * <p>
140         * It has been deprecated due to security concerns regarding in-band configuration of a proxy.
141         */
142        @Deprecated
143        HTTP_305(305, "Use Proxy"),
144        /**
145         * This response code is no longer used; but is reserved.
146         * <p>
147         * It was used in a previous version of the HTTP/1.1 specification.
148         */
149        @Deprecated
150        HTTP_306(306, "Unused"),
151        /**
152         * The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request.
153         * <p>
154         * This has the same semantics as the {@code 302 Found} response code, with the exception that the user agent <em>must not</em> change the HTTP method used: if a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a> was used in the first request, a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a> must be used in the redirected request.
155         */
156        HTTP_307(307, "Temporary Redirect"),
157        /**
158         * This means that the resource is now permanently located at another URI, specified by the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location">Location</a> response header.
159         * <p>
160         * This has the same semantics as the {@code 301 Moved Permanently} HTTP response code, with the exception that the user agent <em>must not</em> change the HTTP method used: if a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a> was used in the first request, a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a> must be used in the second request.
161         */
162        HTTP_308(308, "Permanent Redirect"),
163        /**
164         * The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
165         */
166        HTTP_400(400, "Bad Request"),
167        /**
168         * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated".
169         * <p>
170         * That is, the client must authenticate itself to get the requested response.
171         */
172        HTTP_401(401, "Unauthorized"),
173        /**
174         * The initial purpose of this code was for digital payment systems, however this status code is rarely used and no standard convention exists.
175         */
176        HTTP_402(402, "Payment Required"),
177        /**
178         * The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource.
179         * <p>
180         * Unlike {@code 401 Unauthorized}, the client's identity is known to the server.
181         */
182        HTTP_403(403, "Forbidden"),
183        /**
184         * The server cannot find the requested resource.
185         * <p>
186         * In the browser, this means the URL is not recognized.
187         * In an API, this can also mean that the endpoint is valid but the resource itself does not exist.
188         * Servers may also send this response instead of {@code 403 Forbidden} to hide the existence of a resource from an unauthorized client.
189         * This response code is probably the most well known due to its frequent occurrence on the web.
190         */
191        HTTP_404(404, "Not Found"),
192        /**
193         * The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">request method</a> is known by the server but is not supported by the target resource.
194         * <p>
195         * For example, an API may not allow {@code DELETE} on a resource, or the {@code TRACE} method entirely.
196         */
197        HTTP_405(405, "Method Not Allowed"),
198        /**
199         * This response is sent when the web server, after performing <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation#server-driven_content_negotiation">server-driven content negotiation</a>, doesn't find any content that conforms to the criteria given by the user agent.
200         */
201        HTTP_406(406, "Not Acceptable"),
202        /**
203         * This is similar to {@code 401 Unauthorized} but authentication is needed to be done by a proxy.
204         */
205        HTTP_407(407, "Proxy Authentication Required"),
206        /**
207         * This response is sent on an idle connection by some servers, even without any previous request by the client.
208         * <p>
209         * It means that the server would like to shut down this unused connection. This response is used much more since some browsers use HTTP pre-connection mechanisms to speed up browsing. Some servers may shut down a connection without sending this message.
210         */
211        HTTP_408(408, "Request Timeout"),
212        /**
213         * This response is sent when a request conflicts with the current state of the server.
214         * <p>
215         * In <a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a> remote web authoring, {@code 409} responses are errors sent to the client so that a user might be able to resolve a conflict and resubmit the request.
216         */
217        HTTP_409(409, "Conflict"),
218        /**
219         * This response is sent when the requested content has been permanently deleted from server, with no forwarding address.
220         * <p>
221         * Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
222         */
223        HTTP_410(410, "Gone"),
224        /**
225         * Server rejected the request because the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length">Content-Length</a> header field is not defined and the server requires it.
226         */
227        HTTP_411(411, "Length Required"),
228        /**
229         * In <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests">conditional requests</a>, the client has indicated preconditions in its headers which the server does not meet.
230         */
231        HTTP_412(412, "Precondition Failed"),
232        /**
233         * The request body is larger than limits defined by server.
234         * <p>
235         * The server might close the connection or return a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After">Retry-After</a> header field.
236         */
237        HTTP_413(413, "Content Too Large"),
238        /**
239         * The URI requested by the client is longer than the server is willing to interpret.
240         */
241        HTTP_414(414, "URI Too Long"),
242        /**
243         * The media format of the requested data is not supported by the server, so the server is rejecting the request.
244         */
245        HTTP_415(415, "Unsupported Media Type"),
246        /**
247         * The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests">ranges</a> specified by the {@code Range} header field in the request cannot be fulfilled.
248         * <p>
249         * It's possible that the range is outside the size of the target resource's data.
250         */
251        HTTP_416(416, "Range Not Satisfiable"),
252        /**
253         * This response code means the expectation indicated by the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect">Expect</a> request header field cannot be met by the server.
254         */
255        HTTP_417(417, "Expectation Failed"),
256        /**
257         * The server refuses the attempt to brew coffee with a teapot.
258         */
259        HTTP_418(418, "I'm a Teapot"),
260        /**
261         * The request was directed at a server that is not able to produce a response.
262         * <p>
263         * This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
264         */
265        HTTP_421(421, "Misdirected Request"),
266        /**
267         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) The request was well-formed but was unable to be followed due to semantic errors.
268         */
269        HTTP_422(422, "Unprocessable Content"),
270        /**
271         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) The resource that is being accessed is locked.
272         */
273        HTTP_423(423, "Locked"),
274        /**
275         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) The request failed due to failure of a previous request.
276         */
277        HTTP_424(424, "Failed Dependency"),
278        /**
279         * Indicates that the server is unwilling to risk processing a request that might be replayed.
280         */
281        HTTP_425(425, "Too Early"),
282        /**
283         * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
284         * <p>
285         * The server sends an <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade">Upgrade</a> header in a 426 response to indicate the required protocol(s).
286         */
287        HTTP_426(426, "Upgrade Required"),
288        /**
289         * The origin server requires the request to be <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests">conditional</a>.
290         * <p>
291         * This response is intended to prevent the 'lost update' problem, where a client <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET</a>s a resource's state, modifies it and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">PUT</a>s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
292         */
293        HTTP_428(428, "Precondition Required"),
294        /**
295         * The user has sent too many requests in a given amount of time (<a href="https://developer.mozilla.org/en-US/docs/Glossary/Rate_limit">rate limiting</a>).
296         */
297        HTTP_429(429, "Too Many Requests"),
298        /**
299         * The server is unwilling to process the request because its header fields are too large.
300         * <p>
301         * The request may be resubmitted after reducing the size of the request header fields.
302         */
303        HTTP_431(431, "Request Header Fields Too Large"),
304        /**
305         * The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
306         */
307        HTTP_451(451, "Unavailable For Legal Reasons"),
308        /**
309         * The server has encountered a situation it does not know how to handle.
310         * <p>
311         * This error is generic, indicating that the server cannot find a more appropriate {@code 5XX} status code to respond with.
312         */
313        HTTP_500(500, "Internal Server Error"),
314        /**
315         * The request method is not supported by the server and cannot be handled.
316         * <p>
317         * The only methods that servers are required to support (and therefore that must not return this code) are <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET">GET</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD">HEAD</a>.
318         */
319        HTTP_501(501, "Not Implemented"),
320        /**
321         * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
322         */
323        HTTP_502(502, "Bad Gateway"),
324        /**
325         * The server is not ready to handle the request.
326         * <p>
327         * Common causes are a server that is down for maintenance or that is overloaded.
328         * <p>
329         * Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After">Retry-After</a> HTTP header should, if possible, contain the estimated time before the recovery of the service.
330         * <p>
331         * The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
332         */
333        HTTP_503(503, "Service Unavailable"),
334        /**
335         * This error response is given when the server is acting as a gateway and cannot get a response in time.
336         */
337        HTTP_504(504, "Gateway Timeout"),
338        /**
339         * The HTTP version used in the request is not supported by the server.
340         */
341        HTTP_505(505, "HTTP Version Not supported"),
342        /**
343         * The server has an internal configuration error: during content negotiation, the chosen variant is configured to engage in content negotiation itself, which results in circular references when creating responses.
344         */
345        HTTP_506(506, "Variant Also Negotiates"),
346        /**
347         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
348         */
349        HTTP_507(507, "Insufficient Storage"),
350        /**
351         * (<a href="https://developer.mozilla.org/en-US/docs/Glossary/WebDAV">WebDAV</a>) The server detected an infinite loop while processing the request.
352         */
353        HTTP_508(508, "Loop Detected"),
354        /**
355         * The client request declares an HTTP Extension (<a href="https://datatracker.ietf.org/doc/html/rfc2774">RFC 2774</a>) that should be used to process the request, but the extension is not supported.
356         */
357        HTTP_510(510, "Not Extended"),
358        /**
359         * Indicates that the client needs to authenticate to gain network access.
360         */
361        HTTP_511(511, "Network Authentication Required");
362
363        @Nonnull
364        private static final Map<Integer, StatusCode> STATUS_CODES_BY_NUMBER;
365
366        static {
367                Map<Integer, StatusCode> statusCodesByNumber = new HashMap<>();
368
369                for (StatusCode statusCode : StatusCode.values())
370                        statusCodesByNumber.put(statusCode.getStatusCode(), statusCode);
371
372                STATUS_CODES_BY_NUMBER = Collections.unmodifiableMap(statusCodesByNumber);
373        }
374
375        @Nonnull
376        private final Integer statusCode;
377        @Nonnull
378        private final String reasonPhrase;
379
380        StatusCode(@Nonnull Integer statusCode,
381                                                 @Nonnull String reasonPhrase) {
382                requireNonNull(statusCode);
383                requireNonNull(reasonPhrase);
384
385                this.statusCode = statusCode;
386                this.reasonPhrase = reasonPhrase;
387        }
388
389        /**
390         * Given an HTTP status code, return the corresponding enum value.
391         *
392         * @param statusCode the HTTP status code
393         * @return the enum value that corresponds to the provided HTTP status code, or {@link Optional#empty()} if none exists
394         */
395        @Nonnull
396        public static Optional<StatusCode> fromStatusCode(@Nonnull Integer statusCode) {
397                return Optional.ofNullable(STATUS_CODES_BY_NUMBER.get(statusCode));
398        }
399
400        @Override
401        public String toString() {
402                return format("%s.%s{statusCode=%s, reasonPhrase=%s}", getClass().getSimpleName(), name(), getStatusCode(), getReasonPhrase());
403        }
404
405        /**
406         * The HTTP status code that corresponds to this enum value.
407         *
408         * @return the HTTP status code
409         */
410        @Nonnull
411        public Integer getStatusCode() {
412                return this.statusCode;
413        }
414
415        /**
416         * An English-language description for this HTTP status code.
417         * <p>
418         * For example, {@link StatusCode#HTTP_404} has reason phrase {@code Not Found}.
419         *
420         * @return English description for this HTTP status code
421         */
422        @Nonnull
423        public String getReasonPhrase() {
424                return this.reasonPhrase;
425        }
426}