CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/external/source/msfJavaToolkit/javaCompile/CompileSourceInMemory.java
Views: 11779
1
// Based on the example from http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm
2
3
package javaCompile;
4
5
import java.net.URI;
6
import java.util.Arrays;
7
import java.util.List;
8
import java.util.ArrayList;
9
import java.lang.String;
10
11
import javax.tools.JavaCompiler;
12
import javax.tools.JavaFileObject;
13
import javax.tools.SimpleJavaFileObject;
14
import javax.tools.StandardJavaFileManager;
15
import javax.tools.ToolProvider;
16
import javax.tools.JavaFileObject.Kind;
17
18
public class CompileSourceInMemory {
19
20
public static boolean CompileFromMemory(String strClass, String strCodeContent) {
21
String[] classNames = { strClass };
22
String[] codeContent = { strCodeContent };
23
return CompileFromMemory(classNames, codeContent, null);
24
}
25
26
public static boolean CompileFromMemory(String[] classNames, String[] codeContent) {
27
return CompileFromMemory(classNames, codeContent, null);
28
}
29
30
public static boolean CompileFromMemory(String[] classNames, String[] codeContent, String[] compOptions) {
31
32
List<String> compOptList = null;
33
if (compOptions != null) { compOptList = Arrays.asList(compOptions); }
34
35
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
36
37
// Need to add a check that classNames.length == codeContent.length, else we're fubared.
38
List<JavaFileObject> files = new ArrayList<JavaFileObject> () ;
39
int i = 0;
40
for (String codePage : codeContent) {
41
files.add(new JavaSourceFromString(classNames[i], codePage));
42
i++;
43
}
44
45
Iterable<? extends JavaFileObject> compilationUnits = files;
46
47
JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, compOptList, null, compilationUnits);
48
49
boolean success = task.call();
50
51
return success;
52
53
}
54
}
55
56
class JavaSourceFromString extends SimpleJavaFileObject {
57
final String code;
58
59
JavaSourceFromString(String name, String code) {
60
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
61
this.code = code;
62
}
63
64
@Override
65
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
66
return code;
67
}
68
}
69
70
71