01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package org.apache.commons.jci.examples.configuration;
19:
20: import java.io.File;
21: import java.io.FileInputStream;
22: import java.util.ArrayList;
23: import java.util.Collection;
24: import java.util.Iterator;
25: import java.util.Properties;
26:
27: import org.apache.commons.jci.listeners.FileChangeListener;
28: import org.apache.commons.jci.monitor.FilesystemAlterationListener;
29: import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
30: import org.apache.commons.jci.monitor.FilesystemAlterationObserver;
31:
32: /**
33: *
34: * @author tcurdt
35: */
36: public final class ConfigurationReloading {
37:
38: private final FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
39:
40: private void run(String[] args) {
41:
42: final File configFile = new File("some.properties");
43:
44: System.out.println("Watching " + configFile.getAbsolutePath());
45:
46: final Collection configurables = new ArrayList();
47:
48: final FilesystemAlterationListener listener = new FileChangeListener() {
49: public void onStop(FilesystemAlterationObserver pObserver) {
50: super .onStop(pObserver);
51:
52: if (hasChanged()) {
53: System.out.println("Configuration change detected "
54: + configFile);
55:
56: final Properties props = new Properties();
57: try {
58:
59: props.load(new FileInputStream(configFile));
60:
61: System.out
62: .println("Notifying about configuration change "
63: + configFile);
64:
65: for (Iterator it = configurables.iterator(); it
66: .hasNext();) {
67: final Configurable configurable = (Configurable) it
68: .next();
69: configurable.configure(props);
70: }
71:
72: } catch (Exception e) {
73: System.err
74: .println("Failed to load configuration "
75: + configFile);
76: }
77:
78: }
79: }
80: };
81:
82: fam.addListener(configFile, listener);
83: fam.start();
84:
85: configurables.add(new Something());
86:
87: while (true) {
88: try {
89: Thread.sleep(1000);
90: } catch (InterruptedException e) {
91: }
92: }
93: }
94:
95: public static void main(String[] args) {
96: new ConfigurationReloading().run(args);
97: }
98: }
|