-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandlers.java
More file actions
124 lines (115 loc) · 4.92 KB
/
Copy pathHandlers.java
File metadata and controls
124 lines (115 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.retailsvc.http;
import static com.retailsvc.http.spec.HttpMethod.GET;
import static com.retailsvc.http.spec.HttpMethod.HEAD;
import static java.net.HttpURLConnection.HTTP_BAD_METHOD;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.retailsvc.http.internal.ClasspathResourceHandler;
import com.retailsvc.http.internal.HealthRenderer;
import com.retailsvc.http.internal.ProblemDetail;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Handlers {
private static final Logger LOG = LoggerFactory.getLogger(Handlers.class);
private Handlers() {}
public static ExceptionHandler defaultExceptionHandler(TypeMapper jsonMapper) {
Objects.requireNonNull(jsonMapper, "jsonMapper must not be null");
return t ->
switch (t) {
case ValidationException ve ->
Response.bytes(
HTTP_BAD_REQUEST,
jsonMapper.writeTo(ProblemDetail.forValidation(ve.error())),
"application/problem+json");
case BadRequestException bre ->
Response.bytes(
bre.status(),
jsonMapper.writeTo(ProblemDetail.forBadRequest(bre)),
"application/problem+json");
case NotFoundException _ -> Response.notFound();
case MethodNotAllowedException mna ->
Response.status(HTTP_BAD_METHOD)
.withHeader(
"Allow",
mna.allowed().stream().map(Enum::name).collect(Collectors.joining(", ")));
default -> {
LOG.error("Unhandled exception in handler", t);
yield Response.status(HTTP_INTERNAL_ERROR);
}
};
}
/** Returns 204 No Content on GET/HEAD; 405 with {@code Allow: GET, HEAD} otherwise. */
public static RequestHandler aliveHandler() {
return req ->
switch (req.method()) {
case GET, HEAD -> Response.empty();
default -> Response.status(HTTP_BAD_METHOD).withHeader("Allow", "GET, HEAD");
};
}
/**
* Health endpoint handler. Accepts GET and HEAD; returns 200 with {@code application/json} body
* when the supplied probe reports up (all dependencies up, or no dependencies), and 503 with the
* same body shape otherwise. A probe that throws a {@link RuntimeException} or returns {@code
* null} is mapped to a {@code Down} response with an empty dependency list (and 503); the failure
* is never propagated to the default exception handler.
*
* <p>The wire shape is
*
* <pre>{@code
* {"outcome":"Up","dependencies":[{"id":"jdbc","status":"Up"}]}
* }</pre>
*
* <p>The body is rendered by a built-in writer; no JSON library on the classpath is required.
*
* @param probe supplier of the current {@link HealthOutcome}
*/
public static RequestHandler healthHandler(Supplier<HealthOutcome> probe) {
Objects.requireNonNull(probe, "probe");
return req -> {
if (req.method() != GET && req.method() != HEAD) {
return Response.status(HTTP_BAD_METHOD).withHeader("Allow", "GET, HEAD");
}
boolean up;
List<Dependency> dependencies;
try {
HealthOutcome outcome = Objects.requireNonNull(probe.get(), "Health probe returned null");
up = outcome.up();
dependencies = outcome.dependencies();
} catch (RuntimeException e) {
LOG.warn("Health probe failed", e);
up = false;
dependencies = List.of();
}
byte[] body = HealthRenderer.renderJson(up, dependencies).getBytes(UTF_8);
int status = up ? HTTP_OK : HTTP_UNAVAILABLE;
return Response.bytes(status, body, "application/json");
};
}
/**
* Serves a classpath resource. Content-Type is inferred from the file extension. The resource is
* loaded eagerly; a missing resource fails immediately with {@link IllegalArgumentException}.
*
* @param classpathResource absolute classpath path, e.g. {@code /schemas/v1/openapi.yaml}
*/
public static RequestHandler specHandler(String classpathResource) {
ClasspathResourceHandler resource = new ClasspathResourceHandler(classpathResource);
byte[] bytes = resource.bytes();
String contentType = resource.contentType();
return req ->
switch (req.method()) {
case GET -> Response.bytes(HTTP_OK, bytes, contentType);
case HEAD ->
Response.status(HTTP_OK)
.withContentType(contentType)
.withHeader("Content-Length", String.valueOf(bytes.length));
default -> Response.status(HTTP_BAD_METHOD).withHeader("Allow", "GET, HEAD");
};
}
}