From d564f4b240c52aef5b9a9bacfb1cf66c9526d746 Mon Sep 17 00:00:00 2001 From: Tina_Azure <-> Date: Thu, 9 Mar 2023 19:04:15 +0100 Subject: [PATCH] Create Handler Collection to provide Handlers in a centralized location to avoid localized Lambda --- src/main/java/cavecomm/HandlerCollection.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/cavecomm/HandlerCollection.java diff --git a/src/main/java/cavecomm/HandlerCollection.java b/src/main/java/cavecomm/HandlerCollection.java new file mode 100644 index 0000000..3caaddf --- /dev/null +++ b/src/main/java/cavecomm/HandlerCollection.java @@ -0,0 +1,47 @@ +package cavecomm; + +import io.vertx.core.AsyncResult; +import io.vertx.core.json.JsonArray; +import io.vertx.ext.web.RoutingContext; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; + +//Class collecting Handlers to be used instead of Complex Lmabdas +public final class HandlerCollection { + private HandlerCollection() { + } + + //returns a response containing the query result as a JSON + public static void outputJSON(AsyncResult> ar, RoutingContext rc) { + if (ar.succeeded()) { + RowSet result = ar.result(); + //dump RowSet into jsonArray + JsonArray jsonArray = new JsonArray(); + for (Row r : result) { + jsonArray.add(r.toJson()); + } + //sets the header to json + rc.response().putHeader("Content-Type", "application/json; charset=UTF8") + .end(jsonArray.encode()); + } else { + System.out.println("Failure: " + ar.cause().getMessage()); + } + } + + //Potentially unnecessary to exist as its own handler + public static void outputHTML(AsyncResult> ar, RoutingContext rc) { + if (ar.succeeded()) { + RowSet result = ar.result(); + //dump RowSet into jsonArray + JsonArray jsonArray = new JsonArray(); + for (Row r : result) { + jsonArray.add(r.toJson()); + } + //sets the header to html + rc.response().putHeader("Content-Type", "text/html; charset=UTF8") + .end(jsonArray.encodePrettily()); + } else { + System.out.println("Failure: " + ar.cause().getMessage()); + } + } +}