package com.hubilon.handler; import com.hubilon.util.HttpResponses; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; import java.io.InputStream; import java.util.Map; /** * Serves the embedded UI assets: index.html was split into markup, style.css * and app.js (plus messages.js for editable wording) so each can be read and * changed independently in the jar's resources. Registered on "/", so it also * catches anything not claimed by the more specific API contexts. */ public final class StaticHandler implements HttpHandler { private static final Map ASSETS = Map.of( "/", new String[]{"/static/index.html", "text/html; charset=utf-8"}, "/index.html", new String[]{"/static/index.html", "text/html; charset=utf-8"}, "/style.css", new String[]{"/static/style.css", "text/css; charset=utf-8"}, "/messages.js", new String[]{"/static/messages.js", "application/javascript; charset=utf-8"}, "/app.js", new String[]{"/static/app.js", "application/javascript; charset=utf-8"} ); @Override public void handle(HttpExchange exchange) throws IOException { String path = exchange.getRequestURI().getPath(); String[] asset = ASSETS.get(path); if (asset == null) { HttpResponses.sendText(exchange, 404, "text/plain; charset=utf-8", "Not found: " + path); return; } try (InputStream in = StaticHandler.class.getResourceAsStream(asset[0])) { if (in == null) { HttpResponses.sendText(exchange, 404, "text/plain; charset=utf-8", asset[0] + " not found in jar"); return; } byte[] bytes = in.readAllBytes(); HttpResponses.sendBytes(exchange, 200, asset[1], bytes); } } }