View Javadoc

1   /*
2    * REPOWEB, repository manager.
3    *
4    * Terms of license - http://opensource.org/licenses/apachepl.php
5    */
6   package org.repoweb.model;
7   import java.io.File;
8   import java.io.FileReader;
9   import java.io.FileWriter;
10  import java.io.IOException;
11  import java.net.URL;
12  import javax.servlet.ServletException;
13  import org.apache.commons.logging.Log;
14  import org.apache.commons.logging.LogFactory;
15  import org.apache.struts.action.ActionServlet;
16  import org.apache.struts.action.PlugIn;
17  import org.apache.struts.config.ModuleConfig;
18  /***
19   * Plugin used to load/save the configuration file at startup/shutdown.
20   */
21  public class ManagerPlugIn implements PlugIn {
22      private static final Log LOG = LogFactory.getLog(ManagerPlugIn.class);
23  
24      public void destroy() {
25          LOG.debug("Save configuration file");
26          ManagerConfig currentConfig = Manager.getConfig();
27  
28          if (Manager.NULL_CONFIG.equals(currentConfig)) {
29              getConfigFile().delete();
30              return;
31          }
32  
33          saveConfigFile(currentConfig);
34      }
35  
36  
37      public void init(ActionServlet actionServlet, ModuleConfig moduleConfig)
38          throws ServletException {
39          LOG.debug("Load configuration file");
40  
41          ManagerConfig config = new ManagerConfig();
42  
43          loadConfigFile(config);
44  
45          try {
46              Manager.setConfig(config);
47          }
48          catch (BadConfigException e) {
49              LOG.error("Bad configuration in the file", e);
50          }
51      }
52  
53  
54      protected File getConfigFile() {
55          URL rootFolder = Manager.class.getResource("ManagerPlugIn.class");
56          return new File(rootFolder.getFile(), "../../../../config.properties");
57      }
58  
59  
60      private void loadConfigFile(ManagerConfig config) {
61          File file = getConfigFile();
62  
63          if (file.exists()) {
64              try {
65                  final FileReader reader = new FileReader(file);
66                  try {
67                      config.load(reader);
68                  }
69                  finally {
70                      reader.close();
71                  }
72              }
73              catch (IOException e) {
74                  LOG.error("Unable to load configuration file", e);
75              }
76          }
77      }
78  
79  
80      private void saveConfigFile(ManagerConfig config) {
81          File configFile = getConfigFile();
82  
83          try {
84              FileWriter writer = new FileWriter(configFile);
85              try {
86                  config.save(writer);
87              }
88              finally {
89                  writer.close();
90              }
91          }
92          catch (IOException e) {
93              LOG.error("Unable to save configuration !" + e);
94          }
95      }
96  }