Listening for changes to a configuration file
When the ConfigurationManager loads a configuration it sets up a FileWatcher to watch the file. If the file has changed the configuration will be reloaded automatically. Now you can add your application as a FileListener to this event and recieve a notification when the configuration is reloaded. There is a new method in the ConfigurationManager:
public void addFileListener(String configName,FileListener fl)
You need to supply the name of the configuration that you want to watch and a FileListener.
Here is a short example to demonstrate this:
import org.jconfig.*;
import org.jconfig.handler.*;
import org.jconfig.event.*;
public class WatchConfiguration implements FileListener {
private static final ConfigurationManager cm = ConfigurationManager.getInstance();
public static void main(String[] args) {
try {
Configuration config = cm.getConfiguration();
cm.addFileListener("default",new WatchConfiguration());
Thread.currentThread().sleep(1000000);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fileChanged(FileListenerEvent e) {
System.out.println("file has changed and was reloaded");
}
}
Please note that we have used the default configuration (the configuration file is called config.xml) and so the name is "default".
When you run this example then open the config.xml and change something and save it. You will see that the file will be reloaded. The FileWatcher checks the file every two minutes.
Using a different configuration name would mean that you have to change the code:
Configuration config = cm.getConfiguration("app");
cm.addFileListener("app",new WatchConfiguration());
and the configuration file must be called app_config.xml.
Another way of handling the FileListener would be:
import org.jconfig.*;
import org.jconfig.handler.*;
import org.jconfig.event.*;
public class WatchConfiguration implements FileListener {
private static final Configuration config = ConfigurationManager.getConfiguration();
public static void main(String[] args) {
try {
ConfigurationManager.getInstance().addFileListener("default",new WatchConfiguration());
Thread.currentThread().sleep(1000000);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fileChanged(FileListenerEvent e) {
System.out.println("file has changed and was reloaded");
}
}