Extract http endpoint handler function

This commit is contained in:
AsamK 2022-11-02 21:13:52 +01:00
parent 9563496efb
commit 1b029b765f

View file

@ -40,14 +40,32 @@ public class HttpServerHandler {
} }
public void init() throws IOException { public void init() throws IOException {
logger.info("Starting server on " + address.toString()); logger.info("Starting server on " + address.toString());
final var server = HttpServer.create(address, 0); final var server = HttpServer.create(address, 0);
server.setExecutor(Executors.newFixedThreadPool(10)); server.setExecutor(Executors.newFixedThreadPool(10));
server.createContext("/api/v1/rpc", httpExchange -> { server.createContext("/api/v1/rpc", this::handleRpcEndpoint);
server.start();
}
private void sendResponse(int status, Object response, HttpExchange httpExchange) throws IOException {
if (response != null) {
final var byteResponse = objectMapper.writeValueAsBytes(response);
httpExchange.getResponseHeaders().add("Content-Type", "application/json");
httpExchange.sendResponseHeaders(status, byteResponse.length);
httpExchange.getResponseBody().write(byteResponse);
} else {
httpExchange.sendResponseHeaders(status, 0);
}
httpExchange.getResponseBody().close();
}
private void handleRpcEndpoint(HttpExchange httpExchange) throws IOException {
if (!"POST".equals(httpExchange.getRequestMethod())) { if (!"POST".equals(httpExchange.getRequestMethod())) {
sendResponse(405, null, httpExchange); sendResponse(405, null, httpExchange);
return; return;
@ -70,9 +88,8 @@ public class HttpServerHandler {
}); });
final var jsonRpcReader = new JsonRpcReader(jsonRpcSender, httpExchange.getRequestBody()); final var jsonRpcReader = new JsonRpcReader(jsonRpcSender, httpExchange.getRequestBody());
jsonRpcReader.readMessages((method, params) -> commandHandler.handleRequest(objectMapper, jsonRpcReader.readMessages((method, params) -> commandHandler.handleRequest(objectMapper, method, params),
method, response -> logger.debug("Received unexpected response for id {}", response.getId()));
params), response -> logger.debug("Received unexpected response for id {}", response.getId()));
if (result[0] != null) { if (result[0] != null) {
sendResponse(200, result[0], httpExchange); sendResponse(200, result[0], httpExchange);
@ -88,25 +105,5 @@ public class HttpServerHandler {
null), null), null), null),
httpExchange); httpExchange);
} }
});
server.start();
} }
private void sendResponse(int status, Object response, HttpExchange httpExchange) throws IOException {
if (response != null) {
final var byteResponse = objectMapper.writeValueAsBytes(response);
httpExchange.getResponseHeaders().add("Content-Type", "application/json");
httpExchange.sendResponseHeaders(status, byteResponse.length);
httpExchange.getResponseBody().write(byteResponse);
} else {
httpExchange.sendResponseHeaders(status, 0);
}
httpExchange.getResponseBody().close();
}
} }