File size: 1,329 Bytes
e957698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import subprocess, tempfile, os

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def serve_frontend():
    return FileResponse("index.html")

@app.post("/run-java")
async def run_java(request: Request):
    data = await request.json()
    code = data.get("code", "")
    filename = data.get("filename", "Main.java")

    if not code.strip():
        return {"output": "❌ No code provided."}

    with tempfile.TemporaryDirectory() as tmpdir:
        filepath = os.path.join(tmpdir, filename)
        with open(filepath, "w") as f:
            f.write(code)

        compile_proc = subprocess.run(
            ["javac", filepath],
            capture_output=True,
            text=True
        )
        if compile_proc.returncode != 0:
            return {"output": "Compilation Error:\n" + compile_proc.stderr}

        classname = filename.replace(".java", "")
        run_proc = subprocess.run(
            ["java", "-cp", tmpdir, classname],
            capture_output=True,
            text=True,
            timeout=5
        )
        return {"output": run_proc.stdout or run_proc.stderr}