Skip to content

Commit a19018a

Browse files
committed
Merged all response handling methods into one
1 parent b20ccd5 commit a19018a

20 files changed

+58
-61
lines changed

build.gradle

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ dependencies {
2323
// implementation('com.google.code.gson:gson:2.10.1')
2424

2525
compileOnly('org.jetbrains:annotations:23.0.0')
26+
testCompileOnly('org.jetbrains:annotations:23.0.0')
2627
}
2728

2829
jar {

src/main/java/dev/latvian/apps/tinyserver/HTTPServer.java

+12-13
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import dev.latvian.apps.tinyserver.http.HTTPRequest;
99
import dev.latvian.apps.tinyserver.http.Header;
1010
import dev.latvian.apps.tinyserver.http.response.HTTPPayload;
11+
import dev.latvian.apps.tinyserver.http.response.HTTPResponse;
1112
import dev.latvian.apps.tinyserver.http.response.HTTPStatus;
1213
import dev.latvian.apps.tinyserver.ws.WSEndpointHandler;
1314
import dev.latvian.apps.tinyserver.ws.WSHandler;
@@ -385,23 +386,21 @@ private void handleClient(Socket socket) {
385386
}
386387

387388
public HTTPPayload createBuilder(REQ req, @Nullable HTTPHandler<REQ> handler) {
388-
var payload = new HTTPPayload();
389-
390-
if (serverName != null && !serverName.isEmpty()) {
391-
payload.addHeader("Server", serverName);
392-
}
393-
394-
payload.addHeader("Date", HTTPPayload.DATE_TIME_FORMATTER.format(Instant.now()));
389+
var payload = new HTTPPayload(serverName, Instant.now());
395390

396391
if (handler != null) {
392+
HTTPResponse response;
393+
Throwable error;
394+
397395
try {
398-
var response = handler.handle(req);
399-
req.beforeResponse(payload, response);
400-
payload.setResponse(response);
401-
} catch (Throwable error) {
402-
payload.setStatus(HTTPStatus.INTERNAL_ERROR);
403-
req.handlePayloadError(payload, error);
396+
response = handler.handle(req);
397+
error = null;
398+
} catch (Throwable error1) {
399+
response = HTTPStatus.INTERNAL_ERROR;
400+
error = error1;
404401
}
402+
403+
payload.setResponse(req.handleResponse(payload, response, error));
405404
}
406405

407406
return payload;

src/main/java/dev/latvian/apps/tinyserver/http/HTTPRequest.java

+5-7
Original file line numberDiff line numberDiff line change
@@ -232,13 +232,11 @@ public String userAgent() {
232232
return header("User-Agent");
233233
}
234234

235-
public void beforeResponse(HTTPPayload payload, HTTPResponse response) {
236-
}
237-
238-
public void afterResponse(HTTPPayload payload, HTTPResponse response) {
239-
}
235+
public HTTPResponse handleResponse(HTTPPayload payload, HTTPResponse response, @Nullable Throwable error) {
236+
if (error != null) {
237+
error.printStackTrace();
238+
}
240239

241-
public void handlePayloadError(HTTPPayload payload, Throwable error) {
242-
error.printStackTrace();
240+
return response;
243241
}
244242
}

src/main/java/dev/latvian/apps/tinyserver/http/response/ContentResponse.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
public record ContentResponse(HTTPResponse original, ResponseContent body) implements HTTPResponse {
66
@Override
7-
public void build(HTTPPayload payload) throws Exception {
7+
public void build(HTTPPayload payload) {
88
original.build(payload);
99
payload.setBody(body);
1010
}

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPPayload.java

+16-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import java.io.OutputStream;
1212
import java.nio.charset.StandardCharsets;
13+
import java.time.Instant;
1314
import java.time.ZoneId;
1415
import java.time.format.DateTimeFormatter;
1516
import java.util.ArrayList;
@@ -22,6 +23,8 @@ public class HTTPPayload {
2223
public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).withZone(ZoneId.of("GMT"));
2324
private static final byte[] CRLF = "\r\n".getBytes(StandardCharsets.UTF_8);
2425

26+
private final String serverName;
27+
private final Instant serverTime;
2528
private HTTPStatus status = HTTPStatus.NO_CONTENT;
2629
private final List<Header> headers = new ArrayList<>();
2730
private String cacheControl = "";
@@ -30,6 +33,11 @@ public class HTTPPayload {
3033
private WSSession<?> wsSession = null;
3134
private List<ResponseContentEncoding> encodings;
3235

36+
public HTTPPayload(String serverName, Instant serverTime) {
37+
this.serverName = serverName;
38+
this.serverTime = serverTime;
39+
}
40+
3341
public void setStatus(HTTPStatus status) {
3442
this.status = status;
3543
}
@@ -111,7 +119,7 @@ public void addEncoding(ResponseContentEncoding encoding) {
111119
encodings.add(encoding);
112120
}
113121

114-
public void setResponse(HTTPResponse response) throws Exception {
122+
public void setResponse(HTTPResponse response) {
115123
response.build(this);
116124

117125
if (response instanceof WSResponse res) {
@@ -124,6 +132,13 @@ public void write(HTTPRequest req, OutputStream out, boolean writeBody) throws E
124132
out.write(CRLF);
125133

126134
var actualHeaders = new ArrayList<Header>(headers.size() + (cookies == null ? 0 : cookies.size()) + (cacheControl.isEmpty() ? 0 : 1));
135+
136+
if (serverName != null && !serverName.isEmpty()) {
137+
actualHeaders.add(new Header("Server", serverName));
138+
}
139+
140+
actualHeaders.add(new Header("Date", HTTPPayload.DATE_TIME_FORMATTER.format(serverTime)));
141+
127142
actualHeaders.addAll(headers);
128143

129144
if (cookies != null) {

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPResponse.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ static HTTPResponse redirectPermanently(String location) {
4646
return new RedirectResponse(EmptyResponse.INSTANCE, HTTPStatus.PERMANENT_REDIRECT, location);
4747
}
4848

49-
void build(HTTPPayload payload) throws Exception;
49+
void build(HTTPPayload payload);
5050

5151
default HTTPResponse header(String header, Object value) {
5252
return new HTTPResponseWithHeader(this, header, String.valueOf(value));

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPResponseWithCacheControl.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public HTTPResponseWithCacheControl(HTTPResponse original, boolean isPublic, Dur
88
}
99

1010
@Override
11-
public void build(HTTPPayload payload) throws Exception {
11+
public void build(HTTPPayload payload) {
1212
payload.setCacheControl(value);
1313
original.build(payload);
1414
}

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPResponseWithCookie.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public HTTPResponseWithCookie(HTTPResponse original, String key, String value) {
7171
}
7272

7373
@Override
74-
public void build(HTTPPayload payload) throws Exception {
74+
public void build(HTTPPayload payload) {
7575
var sb = new StringBuilder();
7676
sb.append(value);
7777

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPResponseWithEncoding.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
public record HTTPResponseWithEncoding(HTTPResponse original, ResponseContentEncoding encoding) implements HTTPResponse {
66
@Override
7-
public void build(HTTPPayload payload) throws Exception {
7+
public void build(HTTPPayload payload) {
88
payload.addEncoding(encoding);
99
original.build(payload);
1010
}

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPResponseWithHeader.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public record HTTPResponseWithHeader(HTTPResponse original, String header, String value) implements HTTPResponse {
44
@Override
5-
public void build(HTTPPayload payload) throws Exception {
5+
public void build(HTTPPayload payload) {
66
payload.addHeader(header, value);
77
original.build(payload);
88
}

src/main/java/dev/latvian/apps/tinyserver/http/response/RedirectResponse.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public record RedirectResponse(HTTPResponse original, HTTPStatus status, String location) implements HTTPResponse {
44
@Override
5-
public void build(HTTPPayload payload) throws Exception {
5+
public void build(HTTPPayload payload) {
66
original.build(payload);
77
payload.setStatus(status);
88
payload.setHeader("Location", location);

src/main/java/dev/latvian/apps/tinyserver/http/response/error/BadRequestError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public BadRequestError(String message) {
1010
public BadRequestError(String message, Throwable cause) {
1111
super(HTTPStatus.BAD_REQUEST, message, cause);
1212
}
13-
14-
public BadRequestError(Throwable cause) {
15-
super(HTTPStatus.BAD_REQUEST, cause);
16-
}
1713
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/ForbiddenError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public ForbiddenError(String message) {
1010
public ForbiddenError(String message, Throwable cause) {
1111
super(HTTPStatus.FORBIDDEN, message, cause);
1212
}
13-
14-
public ForbiddenError(Throwable cause) {
15-
super(HTTPStatus.FORBIDDEN, cause);
16-
}
1713
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/HTTPError.java

-5
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,6 @@ public HTTPError(HTTPStatus status, String message, Throwable cause) {
1616
this.status = status;
1717
}
1818

19-
public HTTPError(HTTPStatus status, Throwable cause) {
20-
super(cause);
21-
this.status = status;
22-
}
23-
2419
public HTTPStatus getStatus() {
2520
return status;
2621
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/InternalError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public InternalError(String message) {
1010
public InternalError(String message, Throwable cause) {
1111
super(HTTPStatus.INTERNAL_ERROR, message, cause);
1212
}
13-
14-
public InternalError(Throwable cause) {
15-
super(HTTPStatus.INTERNAL_ERROR, cause);
16-
}
1713
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/NotFoundError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public NotFoundError(String message) {
1010
public NotFoundError(String message, Throwable cause) {
1111
super(HTTPStatus.NOT_FOUND, message, cause);
1212
}
13-
14-
public NotFoundError(Throwable cause) {
15-
super(HTTPStatus.NOT_FOUND, cause);
16-
}
1713
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/NotImplementedError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public NotImplementedError(String message) {
1010
public NotImplementedError(String message, Throwable cause) {
1111
super(HTTPStatus.NOT_IMPLEMENTED, message, cause);
1212
}
13-
14-
public NotImplementedError(Throwable cause) {
15-
super(HTTPStatus.NOT_IMPLEMENTED, cause);
16-
}
1713
}

src/main/java/dev/latvian/apps/tinyserver/http/response/error/UnauthorizedError.java

-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,4 @@ public UnauthorizedError(String message) {
1010
public UnauthorizedError(String message, Throwable cause) {
1111
super(HTTPStatus.UNAUTHORIZED, message, cause);
1212
}
13-
14-
public UnauthorizedError(Throwable cause) {
15-
super(HTTPStatus.UNAUTHORIZED, cause);
16-
}
1713
}

src/test/java/dev/latvian/apps/tinyserver/test/TestRequest.java

+11-4
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,27 @@
33
import dev.latvian.apps.tinyserver.http.HTTPRequest;
44
import dev.latvian.apps.tinyserver.http.response.HTTPPayload;
55
import dev.latvian.apps.tinyserver.http.response.HTTPResponse;
6+
import dev.latvian.apps.tinyserver.http.response.HTTPStatus;
7+
import dev.latvian.apps.tinyserver.http.response.error.HTTPError;
8+
import org.jetbrains.annotations.Nullable;
69

710
public class TestRequest extends HTTPRequest {
811
@Override
9-
public void beforeResponse(HTTPPayload payload, HTTPResponse response) {
12+
public HTTPResponse handleResponse(HTTPPayload payload, HTTPResponse response, @Nullable Throwable error) {
1013
payload.setCacheControl("no-cache, no-store, must-revalidate, max-age=0");
11-
}
1214

13-
@Override
14-
public void afterResponse(HTTPPayload payload, HTTPResponse response) {
1515
System.out.println(method() + " /" + fullPath() + " " + payload.getStatus() + ", " + (System.currentTimeMillis() - startTime()) + " ms");
1616
System.out.println("- Cookies: " + cookies());
1717
System.out.println("- Headers: " + headers());
1818
System.out.println("- Query: " + query());
1919
System.out.println("- Accept Encodings: " + acceptedEncodings());
20+
System.out.println("- Error: " + error);
2021
System.out.println();
22+
23+
if (error != null) {
24+
return (error instanceof HTTPError e ? e.getStatus() : HTTPStatus.INTERNAL_ERROR).text(error.toString());
25+
}
26+
27+
return response;
2128
}
2229
}

src/test/java/dev/latvian/apps/tinyserver/test/TinyServerTest.java

+6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import dev.latvian.apps.tinyserver.HTTPServer;
44
import dev.latvian.apps.tinyserver.http.response.HTTPResponse;
5+
import dev.latvian.apps.tinyserver.http.response.error.UnauthorizedError;
56
import dev.latvian.apps.tinyserver.ws.WSHandler;
67

78
import java.io.IOException;
@@ -27,6 +28,7 @@ public static void main(String[] args) {
2728
server.get("/redirect", TinyServerTest::redirect);
2829
server.post("/console", TinyServerTest::console);
2930
server.get("/stop", TinyServerTest::stop);
31+
server.get("/error", TinyServerTest::error);
3032

3133
server.get("/form", TinyServerTest::form);
3234
server.get("/form-submit", TinyServerTest::formSubmit);
@@ -71,6 +73,10 @@ private static HTTPResponse stop(TestRequest req) {
7173
return HTTPResponse.noContent();
7274
}
7375

76+
private static HTTPResponse error(TestRequest req) {
77+
throw new UnauthorizedError(null);
78+
}
79+
7480
private static HTTPResponse form(TestRequest req) {
7581
return HTTPResponse.ok().html("""
7682
<form action="/form-submit" method="get" accept-charset="utf-8">

0 commit comments

Comments
 (0)