dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
caf8059 verified
Raw History Blame Contribute Delete
6.75 kB
package demo;
// Codex-authored reviewed reference implementation, not a model-generation receipt.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
public final class App {
private static final MathContext MC = MathContext.DECIMAL128;
private static final BigDecimal MAX = new BigDecimal("1e24");
private static final class Failure extends RuntimeException {
final int status;
Failure(String code, int status) { super(code); this.status = status; }
}
private static Failure invalid() { return new Failure("INVALID_EXPRESSION", 400); }
private static Failure limit() { return new Failure("LIMIT_EXCEEDED", 422); }
private static BigDecimal bounded(BigDecimal value) {
if (value.abs().compareTo(MAX) > 0) throw limit();
return value;
}
private static final class Parser {
final String text;
int cursor, operators, depth;
Parser(String text) { this.text = text; }
void spaces() { while (cursor < text.length() && text.charAt(cursor) == ' ') cursor++; }
boolean take(char token) {
spaces();
if (cursor < text.length() && text.charAt(cursor) == token) { cursor++; return true; }
return false;
}
void operator() { if (++operators > 64) throw limit(); }
BigDecimal sum() {
BigDecimal value = product();
while (true) {
if (take('+')) { operator(); value = bounded(value.add(product(), MC)); }
else if (take('-')) { operator(); value = bounded(value.subtract(product(), MC)); }
else return value;
}
}
BigDecimal product() {
BigDecimal value = unary();
while (true) {
if (take('*')) { operator(); value = bounded(value.multiply(unary(), MC)); }
else if (take('/')) {
operator(); BigDecimal divisor = unary();
if (divisor.signum() == 0) throw new Failure("DIVISION_BY_ZERO", 400);
value = bounded(value.divide(divisor, MC));
} else return value;
}
}
BigDecimal unary() {
boolean negative = false;
while (true) {
if (take('+')) operator();
else if (take('-')) { operator(); negative = !negative; }
else break;
}
BigDecimal value;
if (take('(')) {
if (++depth > 16) throw limit();
value = sum();
if (!take(')')) throw invalid();
depth--;
} else value = number();
return negative ? value.negate() : value;
}
BigDecimal number() {
spaces(); int start = cursor, digits = 0;
while (cursor < text.length() && Character.isDigit(text.charAt(cursor))) { cursor++; digits++; }
if (cursor < text.length() && text.charAt(cursor) == '.') {
cursor++; int fractionStart = cursor;
while (cursor < text.length() && Character.isDigit(text.charAt(cursor))) { cursor++; digits++; }
if (cursor == fractionStart) throw invalid();
}
if (digits == 0) throw invalid();
if (digits > 24) throw limit();
return bounded(new BigDecimal(text.substring(start, cursor)));
}
String calculate() {
if (text.length() > 128) throw limit();
if (text.isBlank() || !text.matches("[0-9+*/(). -]+")) throw invalid();
BigDecimal value = sum(); spaces();
if (cursor != text.length()) throw invalid();
value = value.setScale(12, RoundingMode.HALF_UP).stripTrailingZeros();
return value.signum() == 0 ? "0" : value.toPlainString();
}
}
private static String expression(HttpExchange exchange) {
String query = exchange.getRequestURI().getRawQuery();
if (query == null || !query.startsWith("expression64=")) throw new Failure("INVALID_INPUT", 400);
String encoded = query.substring(13);
if (encoded.length() > 256 || !encoded.matches("[A-Za-z0-9_-]+")) throw new Failure("INVALID_INPUT", 400);
try {
byte[] bytes = Base64.getUrlDecoder().decode(encoded);
String decoded = new String(bytes, StandardCharsets.UTF_8);
if (!Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).equals(encoded)
|| !Arrays.equals(bytes, decoded.getBytes(StandardCharsets.UTF_8)))
throw new IllegalArgumentException();
return decoded;
} catch (IllegalArgumentException error) { throw new Failure("INVALID_INPUT", 400); }
}
private static void send(HttpExchange exchange, int status, String json) throws IOException {
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.sendResponseHeaders(status, bytes.length);
try (var output = exchange.getResponseBody()) { output.write(bytes); }
}
private static void handle(HttpExchange exchange) throws IOException {
try {
String path = exchange.getRequestURI().getRawPath();
if (!path.equals("/health") && !path.equals("/api/calculate")) throw new Failure("NOT_FOUND", 404);
if (!exchange.getRequestMethod().equals("GET")) throw new Failure("METHOD_NOT_ALLOWED", 405);
if (path.equals("/health")) { send(exchange, 200, "{\"status\":\"ok\"}"); return; }
if (!"Bearer demo-calculator".equals(exchange.getRequestHeaders().getFirst("Authorization")))
throw new Failure("UNAUTHORIZED", 401);
String text = expression(exchange), result = new Parser(text).calculate();
send(exchange, 200, "{\"expression\":\"" + text + "\",\"result\":\"" + result + "\"}");
} catch (Failure failure) { send(exchange, failure.status, "{\"error\":\"" + failure.getMessage() + "\"}"); }
finally { exchange.close(); }
}
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 32);
server.createContext("/", App::handle);
server.setExecutor(null);
server.start();
}
}