try {
String tmpdir = System.getProperty("java.io.tmpdir");
File classDir = new File(new File(tmpdir), "classes" + hashCode() + System.currentTimeMillis());
if (!classDir.mkdir()) {
throw new BuildException("Could not create output directory.");
}
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
Set<URL> urlSet = getClasspathURLs(oldCl);
String classpath = createClasspath(urlSet);
URLClassLoader newCL = createNewClassLoader();
String[] args = {srcDir.getAbsolutePath() + "/generated/sxc/Reader.java",
srcDir.getAbsolutePath() + "/generated/sxc/Writer.java",
"-g",
"-d", classDir.getAbsolutePath(),
"-classpath", classpath,
"-sourcepath", srcDir.getAbsolutePath()};
// System.out.println("Args: " + Arrays.toString(args));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(bos);
int i;
try {
Class<?> main = newCL.loadClass("com.sun.tools.javac.Main");
Method method = main.getMethod("compile", new Class[] {String[].class, PrintWriter.class});
i = (Integer)method.invoke(null, new Object[] {args, writer});
} catch (ClassNotFoundException e1) {
throw new BuildException("Could not find javac compiler!", e1);
} catch (Exception e) {
throw new BuildException("Could not invoke javac compiler!", e);
}
if (i != 0) {
writer.close();
System.out.println(bos.toString());
throw new BuildException("Could not compile generated files! Code: " + i);
}
Thread.currentThread().setContextClassLoader(oldCl);
URLClassLoader cl = new URLClassLoader(new URL[] {classDir.toURL()}, oldCl);
try {
cl.loadClass("generated.sxc.Reader");
cl.loadClass("generated.sxc.Writer");
} catch (ClassNotFoundException e) {
throw new BuildException("Could not load generated classes.", e);
}
Util.delete(classDir);
return cl;
} catch (IOException e) {
throw new BuildException(e);
}
}