File size: 2,178 Bytes
3e445a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import subprocess
import re  # NEW: Import the 're' module for regular expressions
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/')
def home():
    return jsonify({
        "status": "ok",
        "message": "Java compiler backend is running. Send POST requests to /api/run-java"
    })

@app.route('/api/run-java', methods=['POST'])
def run_java():
    code = request.json.get('code', '')
    user_input = request.json.get('input', '')

    if not code:
        return jsonify({'error': 'No code provided.'}), 400

    # --- MODIFIED LOGIC: Find the public class name ---
    class_name = "Main" # Default class name
    # Regex to find "public class TheClassName"
    match = re.search(r'public\s+class\s+([a-zA-Z0-9_]+)', code)
    if match:
        class_name = match.group(1)
    
    file_path = f"{class_name}.java"
    # --- END OF MODIFIED LOGIC ---

    with open(file_path, "w") as f:
        f.write(code)

    try:
        compile_process = subprocess.run(
            ['javac', file_path],
            capture_output=True, text=True, timeout=10
        )
        if compile_process.returncode != 0:
            return jsonify({'compileErrors': compile_process.stderr})
    except Exception as e:
        return jsonify({'error': f"An unexpected error occurred during compilation: {str(e)}"})
    finally:
        # We need to clean up the .java file even if compilation fails
        if os.path.exists(file_path):
            os.remove(file_path)

    try:
        run_process = subprocess.run(
            ['java', class_name],
            input=user_input,
            capture_output=True, text=True, timeout=15
        )
        
        if run_process.returncode != 0:
            return jsonify({'runErrors': run_process.stderr})
        else:
            return jsonify({'output': run_process.stdout})
    finally:
        # The .java file is already removed above. Now remove the .class file.
        class_file = f"{class_name}.class"
        if os.path.exists(class_file):
            os.remove(class_file)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=7860)