Skip to content

Commit 7d8f479

Browse files
matmat
authored andcommitted
externalize dynamic compilation
1 parent fccd114 commit 7d8f479

11 files changed

Lines changed: 484 additions & 0 deletions

File tree

‎file-compiler/.classpath‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" path="src"/>
4+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
5+
<classpathentry combineaccessrules="false" kind="src" path="/file-monitor"/>
6+
<classpathentry combineaccessrules="false" kind="src" path="/util"/>
7+
<classpathentry kind="output" path="bin"/>
8+
</classpath>

‎file-compiler/.project‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<projectDescription>
3+
<name>file-compiler</name>
4+
<comment></comment>
5+
<projects>
6+
</projects>
7+
<buildSpec>
8+
<buildCommand>
9+
<name>org.eclipse.jdt.core.javabuilder</name>
10+
<arguments>
11+
</arguments>
12+
</buildCommand>
13+
</buildSpec>
14+
<natures>
15+
<nature>org.eclipse.jdt.core.javanature</nature>
16+
</natures>
17+
</projectDescription>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
eclipse.preferences.version=1
2+
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3+
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
4+
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5+
org.eclipse.jdt.core.compiler.compliance=1.6
6+
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7+
org.eclipse.jdt.core.compiler.debug.localVariable=generate
8+
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9+
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10+
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11+
org.eclipse.jdt.core.compiler.source=1.6
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
5+
import com.sandwich.util.io.ui.DefaultErrorPresenter;
6+
import com.sandwich.util.io.ui.ErrorPresenter;
7+
8+
public class CompilationFailureLogger implements CompilationListener {
9+
10+
private ErrorPresenter presenter;
11+
12+
public CompilationFailureLogger(){
13+
this(new DefaultErrorPresenter());
14+
}
15+
16+
public CompilationFailureLogger(ErrorPresenter presenter){
17+
this.presenter = presenter;
18+
}
19+
20+
public void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x) {
21+
String lineSeparator = System.getProperty("line.separator");
22+
presenter.displayError(
23+
lineSeparator +
24+
"*****************************************************************" + lineSeparator +
25+
"Compile Output:" + lineSeparator +
26+
errorMessage.replace(lineSeparator, lineSeparator + " ") + lineSeparator +
27+
"Compiling \"" + src.getAbsolutePath() + "\" failed." + lineSeparator +
28+
"The exit status was: " + exitCode + lineSeparator +
29+
"*****************************************************************" + lineSeparator +
30+
lineSeparator);
31+
}
32+
public void compilationSucceeded(File src, String[] command, String stdIo, Throwable x) { }
33+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
5+
public interface CompilationListener {
6+
void compilationFailed(File src, String[] command, int exitCode, String errorMessage, Throwable x);
7+
void compilationSucceeded(File src, String[] command, String stdIo, Throwable x);
8+
}
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.ByteArrayOutputStream;
4+
import java.io.File;
5+
import java.io.IOException;
6+
import java.io.InputStream;
7+
import java.net.URL;
8+
import java.net.URLConnection;
9+
import java.util.HashMap;
10+
import java.util.Map;
11+
import java.util.Map.Entry;
12+
13+
public class DynamicClassLoader extends ClassLoader {
14+
15+
private static Map<URL, Class<?>> classesByLocation = new HashMap<URL, Class<?>>();
16+
private static Map<Class<?>, URL> locationByClass = new HashMap<Class<?>, URL>();
17+
18+
private final FileMonitor fileMonitor;
19+
private final String binDir, sourceDir;
20+
private final String[] classPath;
21+
22+
public DynamicClassLoader(String binDir, String sourceDir, String[] classPath, FileMonitor fileMonitor){
23+
this(binDir, sourceDir, classPath, fileMonitor, ClassLoader.getSystemClassLoader());
24+
}
25+
26+
public DynamicClassLoader(String binDir, String sourceDir, String[] classPath,
27+
FileMonitor fileMonitor, ClassLoader parent) {
28+
super(parent);
29+
this.fileMonitor = fileMonitor;
30+
this.binDir = binDir;
31+
this.sourceDir = sourceDir;
32+
this.classPath = classPath;
33+
}
34+
35+
public static void remove(URL url){
36+
String urlToString = url.toString().replace(FileCompiler.CLASS_SUFFIX, "").replace(FileCompiler.JAVA_SUFFIX, "");
37+
for(Entry<URL, Class<?>> entry : classesByLocation.entrySet()){
38+
if(entry.getKey().toString().contains(urlToString)){
39+
locationByClass.remove(entry.getValue());
40+
entry.setValue(null);
41+
}
42+
}
43+
}
44+
45+
public static void remove(Class<?> clas){
46+
for(Entry<Class<?>, URL> entry : locationByClass.entrySet()){
47+
if(entry.getKey().getName().contains(clas.getName())){
48+
classesByLocation.remove(entry.getValue());
49+
entry.setValue(null);
50+
}
51+
}
52+
}
53+
54+
public Class<?> loadClass(String className){
55+
return loadClass(className, FileCompilerAction.LOGGING_HANDLER);
56+
}
57+
58+
public Class<?> loadClass(String className, CompilationListener listener){
59+
String fileSeparator = System.getProperty("file.separator");
60+
String fileName = binDir + fileSeparator
61+
+ className.replace(".", fileSeparator)
62+
+ FileCompiler.CLASS_SUFFIX;
63+
File classFile = new File(fileName);
64+
try {
65+
// file may have never been compiled, go ahead and compile it now
66+
File sourceFile = FileCompiler.classToSource(binDir, sourceDir,classFile);
67+
if(classFile.exists()){
68+
String absolutePath = classFile.getAbsolutePath();
69+
boolean isAnonymous = absolutePath.contains("$");
70+
if(fileMonitor.isFileModifiedSinceLastPoll(sourceFile.getAbsolutePath(), sourceFile.lastModified())){
71+
if(!isAnonymous){
72+
compile(className, fileName, sourceFile, listener);
73+
}
74+
}
75+
return loadClass(classFile.toURI().toURL(), className);
76+
}
77+
try{
78+
return super.loadClass(className);
79+
}catch(ClassNotFoundException x){
80+
compile(className, fileName, sourceFile, listener);
81+
classFile = new File(fileName);
82+
return loadClass(classFile.toURI().toURL(), className);
83+
}
84+
} catch (Exception e) {
85+
throw new RuntimeException(e);
86+
}
87+
}
88+
89+
private void compile(String className, String fileName, File sourceFile, CompilationListener listener)
90+
throws IOException {
91+
FileCompiler.compile(sourceFile, new File(binDir), listener, classPath);
92+
fileMonitor.updateFileSaveTime(sourceFile);
93+
}
94+
95+
public Class<?> loadClass(URL url, String className){
96+
Class<?> clazz = classesByLocation.get(url);
97+
if(clazz != null){
98+
return clazz;
99+
}
100+
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
101+
try {
102+
URLConnection connection = url.openConnection();
103+
InputStream input = connection.getInputStream();
104+
int data = input.read();
105+
while(data != -1){
106+
buffer.write(data);
107+
data = input.read();
108+
}
109+
input.close();
110+
} catch (IOException e) {
111+
e.printStackTrace();
112+
}
113+
114+
byte[] classData = buffer.toByteArray();
115+
clazz = defineClass(className, classData, 0, classData.length);
116+
classesByLocation.put(url, clazz);
117+
locationByClass.put(clazz, url);
118+
return clazz;
119+
}
120+
121+
@Override
122+
public DynamicClassLoader clone(){
123+
return new DynamicClassLoader(binDir, sourceDir, classPath, fileMonitor);
124+
}
125+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.io.FileNotFoundException;
5+
import java.io.IOException;
6+
7+
import com.sandwich.util.io.ui.DefaultErrorPresenter;
8+
import com.sandwich.util.io.ui.ErrorPresenter;
9+
10+
public class FileCompiler {
11+
12+
private static final String DOLLAR_SIGN = "$";
13+
public static final String JAVA_SUFFIX = ".java";
14+
public static final String CLASS_SUFFIX = ".class";
15+
16+
public static void compile(String src, String bin) throws IOException {
17+
compile(new DefaultErrorPresenter(), new File(src), new File(bin));
18+
}
19+
20+
public static void compile(ErrorPresenter errorPresenter, String src, String bin) throws IOException {
21+
compile(errorPresenter, new File(src), new File(bin));
22+
}
23+
24+
public static void compile(ErrorPresenter errorPresenter, File src, File bin,
25+
final String...classpath) throws IOException {
26+
compile(src, bin, new CompilationFailureLogger(errorPresenter), classpath);
27+
}
28+
29+
public static void compile(File src, final File bin, CompilationListener listener, String[] classpath) throws IOException {
30+
if(!bin.exists()){
31+
if(!bin.mkdir()){
32+
System.err.println("Was unable to create: "+bin);
33+
System.exit(-231);
34+
}
35+
}
36+
FileUtils.forEachFile(src, bin, new FileCompilerAction(bin, listener, classpath));
37+
}
38+
39+
public static String getContentsOfJavaFile(String sourceDir, String className) {
40+
return FileUtils.readFileAsString(getSourceFileFromClass(sourceDir, className));
41+
}
42+
43+
public static File getSourceFileFromClass(String sourceDir, String className) {
44+
File sourceFile = new File(
45+
sourceDir + System.getProperty("file.separator") +
46+
classNameToJavaFileName(className));
47+
if (!sourceFile.exists()) {
48+
throw new IllegalArgumentException(new FileNotFoundException(
49+
sourceFile.getAbsolutePath() + " does not exist"));
50+
}
51+
return sourceFile;
52+
}
53+
54+
public static String classNameToJavaFileName(String className) {
55+
className = className.replace(".", System.getProperty("file.separator"));
56+
if(className.contains(DOLLAR_SIGN)){
57+
className = className.substring(0, className.indexOf(DOLLAR_SIGN));
58+
}
59+
return className + JAVA_SUFFIX;
60+
}
61+
62+
public static File sourceToClass(String sourceDir, String binDir, File file) {
63+
return new File(file.getAbsolutePath()
64+
.replace(sourceDir, binDir).replace(JAVA_SUFFIX, CLASS_SUFFIX));
65+
}
66+
67+
public static File classToSource(String binDir, String sourceDir, File file) {
68+
return classToSource(binDir, sourceDir, file.getAbsolutePath());
69+
}
70+
71+
public static File classToClassFile(Class<?> clazz) {
72+
String className = clazz.getName();
73+
String path = className.replace(".", System.getProperty("file.separator")) + CLASS_SUFFIX;
74+
return new File(ClassLoader.getSystemResource(path).toString().substring(5));
75+
}
76+
77+
public static File classToSource(String binDir, String sourceDir, String absolutePath) {
78+
return new File(absolutePath
79+
.replace(binDir, sourceDir).replace(CLASS_SUFFIX, JAVA_SUFFIX));
80+
}
81+
82+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
class FileCompilerAction implements FileAction {
7+
8+
private final String destinationPath;
9+
private final String[] classPaths;
10+
private CompilationListener compilationListner;
11+
static final CompilationListener LOGGING_HANDLER = new CompilationFailureLogger();
12+
13+
public FileCompilerAction(File destinationPath, CompilationListener errorHandler, String...classPaths){
14+
if(destinationPath == null){
15+
throw new IllegalArgumentException("the destination path is required");
16+
}
17+
this.destinationPath = destinationPath.getAbsolutePath();
18+
this.classPaths = classPaths;
19+
this.compilationListner = errorHandler == null ? LOGGING_HANDLER : errorHandler;
20+
}
21+
22+
public void sourceToDestination(File src, File bin) throws IOException {
23+
String fileName = src.getName();
24+
if (fileName.length() > 4 && fileName.toLowerCase().endsWith(FileCompiler.JAVA_SUFFIX)) {
25+
String[] command = constructJavaCompilationCommand(src);
26+
Process p = Runtime.getRuntime().exec(command);
27+
try {
28+
if (p.waitFor() != 0) {
29+
compilationListner.compilationFailed(src, command, p.exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), null);
30+
}else{
31+
compilationListner.compilationSucceeded(src, command, StreamUtils.convertStreamToString(p.getInputStream()), null);
32+
}
33+
} catch (Exception x) {
34+
x.printStackTrace();
35+
compilationListner.compilationFailed(src, command,
36+
p.exitValue(), StreamUtils.convertStreamToString(p.getErrorStream()), x);
37+
}
38+
}
39+
}
40+
41+
private String[] constructJavaCompilationCommand(File src) {
42+
return copy(new String[]{"javac", "-d", destinationPath}, getClasspath(), new String[]{src.getAbsolutePath()});
43+
}
44+
45+
private String[] copy(String[]...strings) {
46+
String[] copies = new String[getTotalSize(strings)];
47+
int i = 0;
48+
for(String[] strings2 : strings){
49+
for(String string : strings2){
50+
copies[i++] = string;
51+
}
52+
}
53+
return copies;
54+
}
55+
56+
private int getTotalSize(String[][] strings) {
57+
int i = 0;
58+
for(String[] strings2 : strings){
59+
i += strings2.length;
60+
}
61+
return i;
62+
}
63+
64+
private String[] getClasspath() {
65+
String[] classpaths = new String[classPaths.length + 1];
66+
if (classPaths.length > 0) {
67+
classpaths[0] = "-classpath";
68+
}else{
69+
return new String[]{};
70+
}
71+
for(int i = 1; i <= classPaths.length; i++){
72+
classpaths[i] = classPaths[i - 1];
73+
}
74+
return classpaths;
75+
}
76+
77+
public File makeDestination(File dest, String fileInDirectory) {
78+
String fileName = dest.getName();
79+
fileName = fileName.length() > 4
80+
&& fileName.toLowerCase().contains(FileCompiler.JAVA_SUFFIX) ? fileName
81+
.replace(FileCompiler.JAVA_SUFFIX, FileCompiler.CLASS_SUFFIX) : fileName;
82+
dest = new File(dest, fileInDirectory);
83+
System.out.println("file: " + dest.getAbsolutePath());
84+
return dest;
85+
}
86+
87+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.sandwich.util.io;
2+
3+
import java.io.InputStream;
4+
5+
public class StreamUtils {
6+
7+
public static String convertStreamToString(InputStream stream) {
8+
try {
9+
return new java.util.Scanner(stream).useDelimiter("\\A").next();
10+
} catch (java.util.NoSuchElementException e) {
11+
return "";
12+
}
13+
}
14+
15+
}

0 commit comments

Comments
 (0)