View Javadoc

1   package org.apache.log4j.chainsaw;
2   
3   import java.io.File;
4   import java.io.FileReader;
5   import java.io.FileWriter;
6   
7   import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
8   import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
9   import org.apache.log4j.chainsaw.prefs.SettingsListener;
10  import org.apache.log4j.chainsaw.prefs.SettingsManager;
11  
12  import com.thoughtworks.xstream.XStream;
13  import com.thoughtworks.xstream.io.xml.DomDriver;
14  
15  /***
16   * Helper class that helps delegate the work of loading and saving the  values
17   * of the ApplicationPreferenceModel, allowing that class to remain a simple
18   * bean.
19   * 
20   * The Model passed to this class' constructor is the instance of the ApplicationPreference
21   * that will be saved, and will have properties modified by loading from the
22   * 'chainsaw.settings.xml' file in the .chainsaw directory of the user's home directory.
23   * 
24   * @author psmith
25   *
26   */
27  public class ApplicationPreferenceModelSaver implements SettingsListener {
28  
29      private final ApplicationPreferenceModel model;
30      
31      /***
32       * @param model
33       */
34      public ApplicationPreferenceModelSaver(final ApplicationPreferenceModel model) {
35          this.model = model;
36      }
37  
38      public void loadSettings(LoadSettingsEvent event) {
39          XStream stream = new XStream(new DomDriver());
40          try {
41              File file = getApplicationPreferenceXMLFile(SettingsManager.getInstance().getSettingsDirectory());
42              if (file.exists()) {
43                  FileReader reader = new FileReader(file);
44                  ApplicationPreferenceModel loadedModel = (ApplicationPreferenceModel) stream
45                          .fromXML(reader);
46                  model.apply(loadedModel);
47                  reader.close();
48              }
49          } catch (Exception e) {
50  //            TODO exception handling
51              e.printStackTrace();
52          }
53  
54      }
55  
56      public void saveSettings(SaveSettingsEvent event) {
57          XStream stream = new XStream(new DomDriver());
58          try {
59              File file = getApplicationPreferenceXMLFile(event.getSettingsLocation());
60              FileWriter writer = new FileWriter(file);
61              stream.toXML(model, writer);
62              writer.close();
63          } catch (Exception e) {
64  //            TODO exception handling
65              e.printStackTrace();
66          }
67  
68      }
69  
70      private File getApplicationPreferenceXMLFile(File settingsLocation) {
71          return new File(settingsLocation, "chainsaw.settings.xml");
72      }
73  
74  }