package demo; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.text.PDFTextStripper; /** Auditable reference implementation; compiled and executed only inside the disposable VM. */ public final class App { private static final int MAX_PDF = 131072, MAX_BODY = 180000, MAX_TEXT = 24000; private static final Pattern INPUT = Pattern.compile("\\s*\\{\\s*\"base64\"\\s*:\\s*\"([A-Za-z0-9+/=]*)\"\\s*\\}\\s*"); public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 8080), 0); server.createContext("/", App::handle); server.setExecutor(null); server.start(); } private static void handle(HttpExchange exchange) throws IOException { try { String path = exchange.getRequestURI().getPath(); boolean health = path.equals("/health"), analyze = path.equals("/api/pdf/analyze"); if (!health && !analyze) { error(exchange, 404, "NOT_FOUND"); return; } if (!exchange.getRequestMethod().equals(health ? "GET" : "POST")) { error(exchange, 405, "METHOD_NOT_ALLOWED"); return; } if (health) { send(exchange, 200, "{\"status\":\"ok\"}"); return; } if (!"Bearer demo-pdf".equals(exchange.getRequestHeaders().getFirst("Authorization"))) { error(exchange, 401, "UNAUTHORIZED"); return; } String type = exchange.getRequestHeaders().getFirst("Content-Type"); if (exchange.getRequestURI().getRawQuery() != null || type == null || !type.toLowerCase(java.util.Locale.ROOT).startsWith("application/json")) { error(exchange, 400, "INVALID_INPUT"); return; } byte[] body = exchange.getRequestBody().readNBytes(MAX_BODY + 1); if (body.length > MAX_BODY) { error(exchange, 413, "PDF_TOO_LARGE"); return; } Matcher input = INPUT.matcher(new String(body, StandardCharsets.UTF_8)); if (!input.matches() || input.group(1).isEmpty()) { error(exchange, 400, "INVALID_INPUT"); return; } byte[] pdf; try { pdf = Base64.getDecoder().decode(input.group(1)); if (!Base64.getEncoder().encodeToString(pdf).equals(input.group(1))) throw new IllegalArgumentException(); } catch (IllegalArgumentException invalid) { error(exchange, 400, "INVALID_INPUT"); return; } if (pdf.length > MAX_PDF) { error(exchange, 413, "PDF_TOO_LARGE"); return; } if (pdf.length < 5 || !new String(pdf, 0, 5, StandardCharsets.US_ASCII).equals("%PDF-")) { error(exchange, 400, "INVALID_PDF"); return; } try (PDDocument document = Loader.loadPDF(pdf)) { if (document.isEncrypted()) { error(exchange, 422, "ENCRYPTED_PDF"); return; } int count = document.getNumberOfPages(); if (count == 0) { error(exchange, 400, "INVALID_PDF"); return; } if (count > 20) { error(exchange, 422, "PAGE_LIMIT"); return; } PDFTextStripper stripper = new PDFTextStripper(); stripper.setSortByPosition(true); StringBuilder pages = new StringBuilder("["); int characters = 0, textBytes = 0; for (int page = 1; page <= count; page++) { stripper.setStartPage(page); stripper.setEndPage(page); String text = stripper.getText(document).replace("\r\n", "\n").replace('\r', '\n').strip(); textBytes += text.getBytes(StandardCharsets.UTF_8).length; if (textBytes > MAX_TEXT) { error(exchange, 413, "TEXT_LIMIT"); return; } characters += text.codePointCount(0, text.length()); if (page > 1) pages.append(','); pages.append("{\"page\":").append(page).append(",\"text\":").append(quote(text)).append('}'); } String result = "{\"pageCount\":" + count + ",\"pages\":" + pages.append(']') + ",\"totalCharacters\":" + characters + ",\"status\":\"" + (characters == 0 ? "NO_TEXT" : "TEXT_EXTRACTED") + "\"}"; if (result.getBytes(StandardCharsets.UTF_8).length > 60000) { error(exchange, 413, "TEXT_LIMIT"); return; } send(exchange, 200, result); } catch (InvalidPasswordException encrypted) { error(exchange, 422, "ENCRYPTED_PDF"); } catch (IOException | RuntimeException malformed) { error(exchange, 400, "INVALID_PDF"); } } finally { exchange.close(); } } private static String quote(String text) { StringBuilder out = new StringBuilder("\""); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '"' || ch == '\\') out.append('\\').append(ch); else if (ch < 32) out.append(String.format("\\u%04x", (int) ch)); else out.append(ch); } return out.append('"').toString(); } private static void error(HttpExchange exchange, int status, String code) throws IOException { send(exchange, status, "{\"error\":\"" + code + "\"}"); } private static void send(HttpExchange exchange, int status, String result) throws IOException { byte[] bytes = result.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); exchange.sendResponseHeaders(status, bytes.length); exchange.getResponseBody().write(bytes); } }