hi,
I am writing web app for java learning. Using which users may compile their code on my serwer + run that code. Compiling is easy with JavaCompiler:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
task.call();
List<String> returnErrors = new ArrayList<String>();
String tmp = new String();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
tmp = String.valueOf(diagnostic.getLineNumber());
tmp += " msg: " + diagnostic.getMessage(null);
returnErrors.add(tmp.replaceAll("\n", " "));
}
I manage to load class with code:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
try {
URL[] urls = {new URL("file:///root/"), new URL("file://C:\\serv\\Apache Tomcat 6.0.20\\bin\\")};
ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
ClassLoader cl_new = new URLClassLoader(urls, cl_old);
Class compiledClass = cl_new.loadClass(CLASS_NAME);
Method myMethod = compiledClass.getMethod(METHOD_NAME);
Object tmp = myMethod.invoke(null);
} catch (Exception ex) {
Logger.getLogger(ITaskCompile.class.getName()).log(Level.SEVERE, null, ex);
}
How can i protect my app from endless loop, and evil students ;)
- is there any way to run that code with a lifetime ?
- is there any risk with memory leaks, and what can i do to fix this.
- is this good solution, or can you suggest something better ?
thx. Tzim