From 9af614d22ace652c4d0602b9f9913e2ebea75cdf Mon Sep 17 00:00:00 2001
From: Mathias Wagner <germannewsmaker@gmail.com>
Date: Tue, 13 Feb 2024 18:41:31 +0100
Subject: [PATCH] Created the StaticHandler.java

---
 .../gnmyt/mcdash/handler/StaticHandler.java   | 62 +++++++++++++++++++
 1 file changed, 62 insertions(+)
 create mode 100644 src/main/java/de/gnmyt/mcdash/handler/StaticHandler.java

diff --git a/src/main/java/de/gnmyt/mcdash/handler/StaticHandler.java b/src/main/java/de/gnmyt/mcdash/handler/StaticHandler.java
new file mode 100644
index 0000000..1caa3ba
--- /dev/null
+++ b/src/main/java/de/gnmyt/mcdash/handler/StaticHandler.java
@@ -0,0 +1,62 @@
+package de.gnmyt.mcdash.handler;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import de.gnmyt.mcdash.MCDashWrapper;
+import de.gnmyt.mcdash.http.ContentType;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Objects;
+
+public class StaticHandler implements HttpHandler {
+
+    /**
+     * Handles the request of the client
+     *
+     * @param exchange the exchange containing the request from the
+     *                 client and used to send the response
+     * @throws IOException An exception that can occur while reading the request or writing the response
+     */
+    @Override
+    public void handle(HttpExchange exchange) throws IOException {
+        if (Objects.equals(MCDashWrapper.getConfig().getVersion(), "DEVELOPMENT")) {
+            exchange.sendResponseHeaders(404, 0);
+            exchange.close();
+            return;
+        }
+
+        String path = exchange.getRequestURI().getPath();
+        if (path.equals("/")) path = "/index.html";
+
+        if (getResourceStream("webui" + path) == null) path = "/index.html";
+
+        exchange.getResponseHeaders().add("Content-Type", ContentType.getContentType(path).getType());
+
+        try (InputStream inputStream = getResourceStream("webui" + path)) {
+            if (inputStream != null) {
+                exchange.sendResponseHeaders(200, 0);
+
+                try (OutputStream outputStream = exchange.getResponseBody()) {
+                    byte[] buffer = new byte[8192];
+                    int length;
+                    while ((length = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, length);
+                }
+            }
+        }
+
+        exchange.close();
+    }
+
+    /**
+     * Gets the input stream of a resource
+     *
+     * @param path The path of the resource
+     * @return the input stream of the resource
+     */
+    private InputStream getResourceStream(String path) {
+        return getClass().getClassLoader().getResourceAsStream(path);
+    }
+
+}
\ No newline at end of file