File size: 10,296 Bytes
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package demo;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpExchange;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.ByteBuffer;
import java.util.Base64;

public class App {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/health", App::handleHealth);
        server.createContext("/api/pdf/analyze", App::handleAnalyze);
        server.createContext("/", App::handleDefault);
        server.start();
    }

    static void handleDefault(HttpExchange ex) throws IOException {
        sendJson(ex, 404, "{\"error\":\"NOT_FOUND\"}");
    }

    static void handleHealth(HttpExchange ex) throws IOException {
        if (!"GET".equals(ex.getRequestMethod())) {
            sendJson(ex, 405, "{\"error\":\"METHOD_NOT_ALLOWED\"}");
            return;
        }
        sendJson(ex, 200, "{\"status\":\"ok\"}");
    }

    static void handleAnalyze(HttpExchange ex) throws IOException {
        if (!"POST".equals(ex.getRequestMethod())) {
            sendJson(ex, 405, "{\"error\":\"METHOD_NOT_ALLOWED\"}");
            return;
        }
        String auth = ex.getRequestHeaders().getFirst("Authorization");
        if (auth == null || !auth.equals("Bearer demo-pdf")) {
            sendJson(ex, 401, "{\"error\":\"UNAUTHORIZED\"}");
            return;
        }
        String ct = ex.getRequestHeaders().getFirst("Content-Type");
        if (ct == null || !ct.startsWith("application/json")) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        if (ex.getRequestURI().getQuery() != null) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        byte[] body;
        try (InputStream is = ex.getRequestBody(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buf = new byte[8192];
            int n, total = 0;
            while ((n = is.read(buf)) != -1) {
                total += n;
                if (total > 180001) break;
                baos.write(buf, 0, n);
            }
            body = baos.toByteArray();
        }
        if (body.length > 180000) {
            sendJson(ex, 413, "{\"error\":\"PDF_TOO_LARGE\"}");
            return;
        }
        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
        String json;
        try {
            json = decoder.decode(ByteBuffer.wrap(body)).toString();
        } catch (Exception e) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        String b64 = parseBase64Field(json);
        if (b64 == null) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        if (b64.isEmpty()) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        byte[] pdfBytes;
        try {
            pdfBytes = Base64.getDecoder().decode(b64);
        } catch (Exception e) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        if (!isCanonicalBase64(b64, pdfBytes)) {
            sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}");
            return;
        }
        if (pdfBytes.length > 131072) {
            sendJson(ex, 413, "{\"error\":\"PDF_TOO_LARGE\"}");
            return;
        }
        if (pdfBytes.length < 5 || pdfBytes[0] != '%' || pdfBytes[1] != 'P' || pdfBytes[2] != 'D' || pdfBytes[3] != 'F' || pdfBytes[4] != '-') {
            sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}");
            return;
        }
        PDDocument doc;
        try {
            doc = Loader.loadPDF(pdfBytes);
        } catch (org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException e) {
            sendJson(ex, 422, "{\"error\":\"ENCRYPTED_PDF\"}");
            return;
        } catch (Exception e) {
            sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}");
            return;
        }
        try (doc) {
            if (doc.isEncrypted()) {
                sendJson(ex, 422, "{\"error\":\"ENCRYPTED_PDF\"}");
                return;
            }
            int pages = doc.getNumberOfPages();
            if (pages == 0) {
                sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}");
                return;
            }
            if (pages > 20) {
                sendJson(ex, 422, "{\"error\":\"PAGE_LIMIT\"}");
                return;
            }
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);
            StringBuilder sb = new StringBuilder();
            sb.append("{\"pageCount\":").append(pages).append(",\"pages\":[");
            int totalChars = 0;
            int utf8Total = 0;
            boolean hasText = false;
            for (int i = 1; i <= pages; i++) {
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                String text = stripper.getText(doc);
                text = text.replace("\r\n", "\n").replace("\r", "\n");
                text = text.strip();
                if (!text.isEmpty()) hasText = true;
                totalChars += text.codePointCount(0, text.length());
                utf8Total += text.getBytes(StandardCharsets.UTF_8).length;
                if (utf8Total > 24000) {
                    sendJson(ex, 413, "{\"error\":\"TEXT_LIMIT\"}");
                    return;
                }
                if (i > 1) sb.append(",");
                sb.append("{\"page\":").append(i).append(",\"text\":\"").append(escapeJson(text)).append("\"}");
            }
            sb.append("],\"totalCharacters\":").append(totalChars);
            sb.append(",\"status\":\"").append(hasText ? "TEXT_EXTRACTED" : "NO_TEXT").append("\"}");
            String resp = sb.toString();
            if (resp.getBytes(StandardCharsets.UTF_8).length > 60000) {
                sendJson(ex, 413, "{\"error\":\"TEXT_LIMIT\"}");
                return;
            }
            sendJson(ex, 200, resp);
        }
    }

    static boolean isCanonicalBase64(String b64, byte[] decoded) {
        if (b64.isEmpty() && decoded.length == 0) return true;
        String reencoded = Base64.getEncoder().encodeToString(decoded);
        return reencoded.equals(b64);
    }

    static String escapeJson(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        return sb.toString();
    }

    static String parseBase64Field(String json) {
        int idx = 0;
        idx = skipWs(json, idx);
        if (idx >= json.length() || json.charAt(idx) != '{') return null;
        idx++;
        idx = skipWs(json, idx);
        if (idx >= json.length() || json.charAt(idx) == '}') return null;
        int keyCount = 0;
        String value = null;
        while (idx < json.length()) {
            idx = skipWs(json, idx);
            if (idx >= json.length() || json.charAt(idx) != '"') return null;
            int keyStart = idx + 1;
            int keyEnd = findClosingQuote(json, keyStart);
            if (keyEnd < 0) return null;
            String key = json.substring(keyStart, keyEnd);
            idx = keyEnd + 1;
            idx = skipWs(json, idx);
            if (idx >= json.length() || json.charAt(idx) != ':') return null;
            idx++;
            idx = skipWs(json, idx);
            if (idx >= json.length() || json.charAt(idx) != '"') return null;
            int valStart = idx + 1;
            int valEnd = findClosingQuote(json, valStart);
            if (valEnd < 0) return null;
            String val = json.substring(valStart, valEnd);
            idx = valEnd + 1;
            keyCount++;
            if (keyCount > 1) return null;
            if (!"base64".equals(key)) return null;
            value = val;
            idx = skipWs(json, idx);
            if (idx < json.length() && json.charAt(idx) == ',') {
                idx++;
                idx = skipWs(json, idx);
                if (idx < json.length() && json.charAt(idx) == '}') return null;
                continue;
            }
            break;
        }
        idx = skipWs(json, idx);
        if (idx >= json.length() || json.charAt(idx) != '}') return null;
        idx++;
        idx = skipWs(json, idx);
        if (idx != json.length()) return null;
        return value;
    }

    static int findClosingQuote(String s, int from) {
        for (int i = from; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\\') { i++; continue; }
            if (c == '"') return i;
        }
        return -1;
    }

    static int skipWs(String s, int i) {
        while (i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t' || s.charAt(i) == '\n' || s.charAt(i) == '\r')) i++;
        return i;
    }

    static void sendJson(HttpExchange ex, int code, String body) throws IOException {
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        ex.getResponseHeaders().set("Content-Type", "application/json");
        ex.sendResponseHeaders(code, bytes.length);
        try (OutputStream os = ex.getResponseBody()) {
            os.write(bytes);
        }
    }
}