View Javadoc

1   /*
2    * Copyright 2004-2005 Germinus XXI
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License")
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.germinus.easyconf;
17  
18  import java.net.URL;
19  
20  import org.apache.commons.configuration.reloading.InvariantReloadingStrategy;
21  import org.apache.commons.configuration.reloading.ReloadingStrategy;
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  
25  /***
26   * Holds a configuration object and reloads it when necessary
27   *
28   * @author  Jorge Ferrer
29   * @version $Revision: 1.1 $
30   *
31   */
32  public class ConfigurationObjectCache {
33  
34      Object configurationObject;
35      ReloadingStrategy reloadingStrategy = new InvariantReloadingStrategy();
36      Object reloadLock = new Object();
37      ConfigurationLoader loader = new ConfigurationLoader();
38      private static final Log log = LogFactory.getLog(ConfigurationObjectCache.class);
39      private URL confFileUrl;
40      private ComponentProperties properties;
41      
42      public ConfigurationObjectCache(Object confObj, URL confFileUrl, ComponentProperties properties) {
43          this.configurationObject = confObj;
44          this.confFileUrl = confFileUrl;
45          this.properties = properties;
46      }
47      
48      public Object getConfigurationObject() {
49          reload();
50          return configurationObject;
51      }
52  
53      private void reload() {
54          synchronized (reloadLock) {
55              if (reloadingStrategy.reloadingRequired()) {
56                  try {
57                      configurationObject =  loader.loadXMLFile(confFileUrl, properties);
58                      reloadingStrategy.reloadingPerformed();
59                  }
60                  catch (Exception e) {
61                      log.error("Error loading " + confFileUrl, e);
62                  }
63              }
64          }
65      }
66  
67      private ReloadingStrategy getReloadingStrategy() {
68          return reloadingStrategy;
69      }
70  
71      public void setReloadingStrategy(ReloadingStrategy strategy) {
72          this.reloadingStrategy = strategy;        
73      }
74  
75  }