import java.io.*;
public class DynamicDateReload {

	public static void main(String[] args) throws Exception {
		
		/* ------------- Write the Java code ------------- */
		String code = "public class DateTeller implements Teller {\n"
				+ "public String tell(String name) {\n "
				+ "return \"Hello \" + name + \". \" + \"The time is \" + new java.util.Date(); "
				+ "}}";
		
		
		File javaFile = new File("DateTeller.java");
		FileWriter fwriter = new FileWriter(javaFile);
		fwriter.write(code);		
		fwriter.close();
		/* ------------------------------------------------ */
		
		
		/* ------------- Compile the code ------------- */
		Process compileProc = Runtime.getRuntime().exec("javac -classpath .  DateTeller.java");		
		compileProc.waitFor(); //Wait for the process to terminate
		
		if(compileProc.exitValue()!=0) {
			System.out.println("Compile exit status: " + compileProc.exitValue());
			System.out.println("Compile error:");
			printStream(compileProc.getErrorStream());
		}
		
		/* ------------------------------------------------ */
		
		/* ------------- Delete the Java file ------------- */
		javaFile.delete();		
		/* ------------------------------------------------ */
		
		
		
		/* ------------- Load the class ------------- */
		Class tellerClass = DBIClassLoader.loadNewClass("DateTeller");	
		/* ------------------------------------------------ */
		
		
		
		
		 
		/* ------------- Instantiate the class ------------- */
		Teller teller = (Teller)(tellerClass.newInstance());
		/* ------------------------------------------------ */
		
		
		/* ------------- Invoke the interface method ------------- */
		System.out.println(teller.tell("Snoopy"));
		/* ------------------------------------------------ */
		
		
		
		
		
		//Reload the class
		code = "public class DateTeller implements Teller {\n"
			+ "public String tell(String name) {\n "
			+ "return \"Hello \" + name + \". \" + \"No date this time.\";" 
			+ "}}";
		/* ------------- Compile the code ------------- */
		javaFile = new File("DateTeller.java");
		fwriter = new FileWriter(javaFile);
		fwriter.write(code);		
		fwriter.close();
		compileProc = Runtime.getRuntime().exec("javac -classpath .  DateTeller.java");
		compileProc.waitFor(); //Wait for the process to terminate
		
		if(compileProc.exitValue()!=0) {
			System.out.println("Compile exit status: " + compileProc.exitValue());
			System.out.println("Compile error:");
			printStream(compileProc.getErrorStream());
		}
			
		tellerClass = DBIClassLoader.loadNewClass("DateTeller");
		javaFile.delete();
		new File("a/DateTeller.class").delete();
		teller = (Teller)(tellerClass.newInstance());		
		System.out.println(teller.tell("Snoopy"));			
	}
	
	public static void printStream(InputStream stream) throws IOException {
		byte read = 0;
		while((read=(byte)stream.read())>=0) {
			System.err.print((char)read);
		}			
	}
	
	
	
	
}