Search code examples
javaphpcompilationcompiler-errorssandbox

How to tell if a user's java code compiled successfully?


I have a web app running on a LAMP stack that allows users to write java code into an HTML form, but depending on whether or not that code compiles successfully, I want to do different things.

The way I have it currently is that the PHP program would generate a .java file using user's input, execute it on the server (I have the security part taken care of), and then check to see if any errors were output.

I know that Java prints errors out using the System.err stream, is there a way for me to tell if that output anything to the console? Like a way to listen and distinguish output streams of a program?


Solution

  • You can check the javac exit code. Here is a list of the javac exit code:

    static final int
        EXIT_OK = 0,        // Compilation completed with no errors.
        EXIT_ERROR = 1,     // Completed but reported errors.
        EXIT_CMDERR = 2,    // Bad command-line arguments
        EXIT_SYSERR = 3,    // System error or resource exhaustion.
        EXIT_ABNORMAL = 4;  // Compiler terminated abnormally
    

    References: http://bugs.java.com/view_bug.do?bug_id=7014715

    Since Java 6, you can programmatically call the Java compiler (if provided). See this: ToolProvider#getSystemJavaCompiler