Tuesday, July 3, 2012

Hot Deploy Example

Can be used to build a generic task-execution engine that can be used to load the code supplied by any remote client.


The most important point is to correctly set the parent class loader which is null here .
note: with windows custom urlClassLoader is necessary which is overrides the close method of the base class  (due to a jvm bug{may be fixed in jdk7})


import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;


import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class JarReloader {


public static void main(String[] args) {

Runnable r = new Runnable() {

@Override
public void run() {
while (true) {
reloadJarFile();
watchDirectory();
}
}


private void reloadJarFile() {
try {
System.out.println("Reloading the jar file !");
URLClassLoader cl = null;
   File file = new File("/home/ssunel/jars/reload.jar");
   String classToLoad = "com.freetime.enjoy.ReloadMe";
   URL jarUrl = new URL("file:" + file.getAbsolutePath());
   cl = new URLClassLoader(new URL[] {jarUrl}, null);
   Class loadedClass = cl.loadClass(classToLoad);
   Method method = loadedClass.getMethod("giveAMessage", new Class[] {});
   Object reloadMe = loadedClass.getConstructor().newInstance();
   method.invoke(reloadMe, null);
} catch (Exception e) {
e.printStackTrace();
}
}


private void watchDirectory() {
try {
Path dir = Paths.get("/home/ssunel/jars");
WatchService watchService = FileSystems.getDefault().newWatchService();
dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY);
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
Path child = dir.resolve(name);
System.out.format("%s: %s\n", event.kind().name(), child);
}
Thread.sleep(1000L);
       } catch (Exception x) {
           return;
       }
}


};

startReloader(r);

}


private static void startReloader(Runnable r) {
try {
Thread reloader = new Thread(r);
reloader.start();
reloader.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}


package com.freetime.enjoy;

public class ReloadMe {
private final static String someMessage = "HELLO WORLD AGAIN";
public static void giveAMessage (){
System.out.println(someMessage);
}
}

No comments:

Post a Comment