|
@@ -0,0 +1,53 @@
|
|
1
|
+package com.uqac.rthoni.java_rmi.server.executors;
|
|
2
|
+
|
|
3
|
+import com.uqac.rthoni.java_rmi.common.Command;
|
|
4
|
+import com.uqac.rthoni.java_rmi.server.ServerApplication;
|
|
5
|
+
|
|
6
|
+import javax.tools.JavaCompiler;
|
|
7
|
+import javax.tools.ToolProvider;
|
|
8
|
+import java.io.ByteArrayOutputStream;
|
|
9
|
+import java.io.File;
|
|
10
|
+import java.net.URL;
|
|
11
|
+import java.net.URLClassLoader;
|
|
12
|
+import java.nio.charset.StandardCharsets;
|
|
13
|
+import java.nio.file.Files;
|
|
14
|
+import java.util.List;
|
|
15
|
+import java.util.Vector;
|
|
16
|
+import java.util.stream.Collectors;
|
|
17
|
+
|
|
18
|
+/**
|
|
19
|
+ * Created by robin on 9/16/16.
|
|
20
|
+ */
|
|
21
|
+public class ClassBuilderExecutor extends AbstractCommandExecutor {
|
|
22
|
+ @Override
|
|
23
|
+ public String getCommandName() {
|
|
24
|
+ return "compilation";
|
|
25
|
+ }
|
|
26
|
+
|
|
27
|
+ @Override
|
|
28
|
+ public String run(Command command, ServerApplication server) throws Exception
|
|
29
|
+ {
|
|
30
|
+ Vector<String> files = command.getArgumentAsList(0, false);
|
|
31
|
+ String classDir = command.getArgument(1, false);
|
|
32
|
+ File classFile = new File(server.getClassDir(), classDir);
|
|
33
|
+ classFile.mkdirs();
|
|
34
|
+
|
|
35
|
+ List<String> sources = files.stream().map(f -> new File(server.getSourceDir(), f).getPath() ).collect(Collectors.toList());
|
|
36
|
+ Vector<String> arguments = new Vector<>();
|
|
37
|
+ arguments.add("-d");
|
|
38
|
+ arguments.add(classFile.getPath());
|
|
39
|
+ arguments.addAll(sources);
|
|
40
|
+
|
|
41
|
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
|
42
|
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
|
43
|
+ compiler.run(null, outputStream, outputStream, arguments.toArray(new String[arguments.size()]));
|
|
44
|
+
|
|
45
|
+// Load and instantiate compiled class.
|
|
46
|
+// URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
|
|
47
|
+// Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
|
|
48
|
+// Object instance = cls.newInstance(); // Should print "world".
|
|
49
|
+// System.out.println(instance); // Should print "test.Test@hashcode".
|
|
50
|
+
|
|
51
|
+ return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
|
|
52
|
+ }
|
|
53
|
+}
|