1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.jci.examples.configuration;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Properties;
27
28 import org.apache.commons.jci.listeners.FileChangeListener;
29 import org.apache.commons.jci.monitor.FilesystemAlterationListener;
30 import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
31 import org.apache.commons.jci.monitor.FilesystemAlterationObserver;
32
33
34
35
36
37 public final class ConfigurationReloading {
38
39 private final FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
40
41 private void run(String[] args) {
42
43 final File configFile = new File("some.properties");
44
45 System.out.println("Watching " + configFile.getAbsolutePath());
46
47 final Collection<Configurable> configurables = new ArrayList<Configurable>();
48
49 final FilesystemAlterationListener listener = new FileChangeListener() {
50 public void onStop(FilesystemAlterationObserver pObserver) {
51 super.onStop(pObserver);
52
53 if (hasChanged()) {
54 System.out.println("Configuration change detected " + configFile);
55
56 final Properties props = new Properties();
57 InputStream is = null;
58 try {
59 is = new FileInputStream(configFile);
60 props.load(is);
61
62 System.out.println("Notifying about configuration change " + configFile);
63
64 for (Configurable configurable : configurables) {
65 configurable.configure(props);
66 }
67
68 } catch (Exception e) {
69 System.err.println("Failed to load configuration " + configFile);
70 } finally {
71 try {
72 is.close();
73 } catch (IOException e) {
74 }
75 }
76
77 }
78 }
79 };
80
81 fam.addListener(configFile, listener);
82 fam.start();
83
84 configurables.add(new Something());
85
86 while(true) {
87 try {
88 Thread.sleep(1000);
89 } catch (InterruptedException e) {
90 }
91 }
92 }
93
94 public static void main(String[] args) {
95 new ConfigurationReloading().run(args);
96 }
97 }