import { NextRequest, NextResponse } from 'next/server' import { spawn } from 'child_process' import { writeFile, unlink, mkdir } from 'fs/promises' import { join } from 'path' import { tmpdir } from 'os' export async function POST(request: NextRequest) { let tempDir: string | null = null let className = 'Solution' try { const body = await request.json() const { code, testCase, functionName } = body if (!code || !testCase) { return NextResponse.json( { error: 'Code and test case are required' }, { status: 400 } ) } // Extract class name from code or use default const classMatch = code.match(/public\s+class\s+(\w+)/) if (classMatch) { className = classMatch[1] } // Create a temporary directory for Java files const baseDir = tmpdir() tempDir = join(baseDir, `java_exec_${Date.now()}_${Math.random().toString(36).substring(7)}`) await mkdir(tempDir, { recursive: true }) const javaFile = join(tempDir, `${className}.java`) // Wrap user code with main method for testing const wrappedCode = ` ${code} class Main { // Helper to convert Object to JSON string (handles int[], Integer, and other types) public static String convertToJson(Object obj) { if (obj == null) return "null"; if (obj instanceof int[]) { int[] arr = (int[]) obj; StringBuilder sb = new StringBuilder("["); for (int i = 0; i < arr.length; i++) { if (i > 0) sb.append(","); sb.append(arr[i]); } sb.append("]"); return sb.toString(); } if (obj instanceof Integer) { return String.valueOf((Integer) obj); } // Fallback for other types (including primitive int which gets auto-boxed) return obj.toString(); } public static void main(String[] args) { ${className} solution = new ${className}(); try { // Test input ${generateJavaTestCode(testCase.input, functionName, className)} } catch (Exception e) { System.err.println("ERROR: " + e.getMessage()); e.printStackTrace(); System.exit(1); } } } ` await writeFile(javaFile, wrappedCode, 'utf-8') // Ensure tempDir is not null if (!tempDir) { return NextResponse.json( { error: 'Failed to create temporary directory' }, { status: 500 } ) } const javaTempDir = tempDir // Store in const for TypeScript // Compile and execute Java code const result = await new Promise<{ output: string; error: string; exitCode: number }>(async (resolve) => { // First compile const compileResult = await new Promise<{ success: boolean; error: string }>((resolveCompile) => { const javac = spawn('javac', [javaFile], { cwd: javaTempDir }) let compileError = '' javac.stderr.on('data', (data) => { compileError += data.toString() }) javac.on('close', (code) => { resolveCompile({ success: code === 0, error: compileError }) }) setTimeout(() => { javac.kill() resolveCompile({ success: false, error: 'Compilation timeout' }) }, 5000) }) if (!compileResult.success) { resolve({ output: '', error: compileResult.error, exitCode: 1 }) return } // Then execute const java = spawn('java', ['-cp', javaTempDir, 'Main']) let output = '' let error = '' java.stdout.on('data', (data) => { output += data.toString() }) java.stderr.on('data', (data) => { error += data.toString() }) java.on('close', (code) => { resolve({ output: output.trim(), error: error.trim(), exitCode: code || 0 }) }) // Timeout after 5 seconds setTimeout(() => { java.kill() resolve({ output: '', error: 'Execution timeout (5 seconds)', exitCode: -1 }) }, 5000) }) // Clean up temp directory if (javaTempDir) { try { const { exec } = require('child_process') await new Promise((resolve) => { exec(`rm -rf "${javaTempDir}"`, () => resolve(undefined)) }) } catch (e) { // Ignore cleanup errors } } if (result.exitCode !== 0 || result.error) { if (result.output && result.output.trim() && !result.error.includes('ERROR')) { try { const actualOutput = JSON.parse(result.output) return NextResponse.json({ success: true, output: actualOutput, }) } catch (e) { // If parsing fails, return the error } } return NextResponse.json({ success: false, error: result.error || 'Execution failed', output: result.output, }) } if (!result.output || !result.output.trim()) { return NextResponse.json({ success: false, error: 'No output from code execution', rawOutput: result.output, }) } try { const actualOutput = JSON.parse(result.output) return NextResponse.json({ success: true, output: actualOutput, }) } catch (e) { return NextResponse.json({ success: false, error: `Failed to parse output as JSON: ${result.output}`, rawOutput: result.output, }) } } catch (error: any) { // Clean up temp directory on error if (tempDir) { try { const { exec } = require('child_process') await new Promise((resolve) => { exec(`rm -rf "${tempDir}"`, () => resolve(undefined)) }) } catch (e) { // Ignore cleanup errors } } return NextResponse.json( { error: error.message || 'Internal server error' }, { status: 500 } ) } } function generateJavaTestCode(input: any, functionName: string, className: string): string { // Generate Java code to call the function with test input if (Array.isArray(input) && input.length === 1) { return `Object result = solution.${functionName}(${formatJavaValue(input[0])}); System.out.println(convertToJson(result));` } else if (Array.isArray(input) && input.length === 2) { return `Object result = solution.${functionName}(${formatJavaValue(input[0])}, ${formatJavaValue(input[1])}); System.out.println(convertToJson(result));` } else { return `Object result = solution.${functionName}(${formatJavaValue(input)}); System.out.println(convertToJson(result));` } } function formatJavaValue(value: any): string { if (Array.isArray(value)) { return `new int[]{${value.join(', ')}}` } if (typeof value === 'string') { return `"${value}"` } return String(value) } // Helper to convert Java objects to JSON (simplified) // In production, you'd want a more robust solution function convertToJson(obj: any): string { if (obj == null) return 'null' if (Array.isArray(obj)) { return JSON.stringify(obj) } return JSON.stringify(obj) }