we have a web application, which helps learners to learn by practice. So there is a module for java as well. For this we require executing the java program written by user and reading its output and displaying it to user.
Currently we use a C# service to do this. We save the java program in a .java file on server and compile it by executing javac.exe command and then run it by executing java.exe and read the output from console and transferring it back to user.
public String ExecuteProgramFetchOutput(String classpath, String filename){
String output = "";
String command = "java -classpath " + classpath + " " + filename;
System.Diagnostics.Process _objProcess = new System.Diagnostics.Process();
try
{
System.Diagnostics.ProcessStartInfo _objProcessInfo = new System.Diagnostics.ProcessStartInfo();
_objProcessInfo.FileName = "cmd.exe";
_objProcessInfo.RedirectStandardInput = true;
_objProcessInfo.RedirectStandardOutput = true;
_objProcessInfo.RedirectStandardError = true;
_objProcessInfo.CreateNoWindow = true;
_objProcessInfo.UseShellExecute = false;
_objProcess.StartInfo = _objProcessInfo;
_objProcess = System.Diagnostics.Process.Start(_objProcessInfo);
_objProcess.StandardInput.AutoFlush = true;
_objProcess.StandardInput.WriteLine(command);
_objProcess.WaitForExit(3000);
if (!_objProcess.HasExited)
{
_objProcess.Kill();
}
output = _objProcess.StandardOutput.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
output = ex.ToString();
}
finally
{
if (_objProcess != null)
{
if (!_objProcess.HasExited)
{
_objProcess.Kill();
}
_objProcess.Dispose();
}
}
return ouput;
}
I have only given the code for execution similar kind of code is there for compilation. The only problem with the above approach is that when someone runs the java program with an infinite loop there is a java.exe running on the server and taking CPU percentage of 50% and more, After that any request which comes fails!!
We employed a solution to that as well by running a separate thread which checks in the system what and all "java.exe"s running for more than 3 secs and terminating them.
Still this approach will start failing as the number of users will start increasing. As if 10 users simultaneously execute a program the server will not be able to handle it.
I am looking for a solution which can compile and run the java program without running the java.exe. The solution can be either in java or c# (preferably c#). I found some code for compiling using java by using JavaCompiler
class, I also found code for executing the program using reflection API, but I could not find how to read the output after executing.
Please help!! Thanks in advance...