package com.hubilon.handler; import com.hubilon.json.Json; import com.hubilon.proxy.ProxyClient; import com.hubilon.util.DebugState; import com.hubilon.util.HttpResponses; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public final class ProxyHandler implements HttpHandler { private final DebugState debugState; private final Path protoDir; private final AtomicInteger requestSeq = new AtomicInteger(); public ProxyHandler(DebugState debugState, Path protoDir) { this.debugState = debugState; this.protoDir = protoDir; } @Override @SuppressWarnings("unchecked") public void handle(HttpExchange exchange) throws IOException { if (!"POST".equalsIgnoreCase(exchange.getRequestMethod())) { HttpResponses.sendText(exchange, 404, "text/plain; charset=utf-8", "Not found: " + exchange.getRequestURI().getPath()); return; } int reqId = requestSeq.incrementAndGet(); byte[] rawBody = exchange.getRequestBody().readAllBytes(); String requestBody = new String(rawBody, StandardCharsets.UTF_8); Map spec; try { spec = Json.parseObject(requestBody); } catch (Exception e) { HttpResponses.sendJson(exchange, 400, Map.of("error", "Invalid proxy payload: " + e.getMessage())); return; } debugState.log("RECV", "#" + reqId + " POST /proxy -> " + spec.get("method") + " " + spec.get("url")); try { Map result = ProxyClient.invoke(spec, protoDir); HttpResponses.sendJson(exchange, 200, result); debugState.log("DONE", "#" + reqId + " /proxy 200"); } catch (Exception e) { HttpResponses.sendJson(exchange, 500, Map.of("error", String.valueOf(e.getMessage()))); debugState.log("ERROR", "#" + reqId + " /proxy failed: " + e.getMessage()); } } }