View Javadoc
1   package com.atlassian.refapp.sal;
2   
3   import com.atlassian.fugue.Pair;
4   import com.atlassian.sal.api.ApplicationProperties;
5   import org.apache.commons.io.IOUtils;
6   import org.slf4j.Logger;
7   import org.slf4j.LoggerFactory;
8   
9   import java.io.File;
10  import java.io.FileInputStream;
11  import java.io.IOException;
12  import java.io.InputStream;
13  import java.util.Properties;
14  
15  public class FileBackedSettingsFileFactory {
16      private static Logger log = LoggerFactory.getLogger(FileBackedSettingsFileFactory.class);
17  
18      public static Pair<File, Properties> getFileAndProperties(String fileStorageProperty, String defaultFileName, boolean useMemoryStore, ApplicationProperties applicationProperties) {
19          File file = new File(System.getProperty(fileStorageProperty, defaultFileName));
20          Properties properties = new Properties();
21          if (useMemoryStore) {
22              log.info("Using memory store for settings");
23              file = null;
24          } else if (!file.exists() || !file.canRead()) {
25              // Use refapp home directory
26              File dataDir = new File(applicationProperties.getHomeDirectory(), "data");
27              try {
28                  if (!dataDir.exists()) {
29                      dataDir.mkdirs();
30                  }
31                  file = new File(dataDir, defaultFileName);
32                  file.createNewFile();
33              } catch (IOException ioe) {
34                  log.warn("Error creating settings properties, using memory store", ioe);
35                  file = null;
36              }
37          }
38          if (file != null && file.length() > 0) {
39              file = load(file, properties);
40          }
41          if (file != null) {
42              // File is a new file
43              log.info("Using " + file.getAbsolutePath() + " as settings store");
44          }
45          return Pair.pair(file, properties);
46      }
47  
48      private static File load(File file, Properties properties) {
49          InputStream is = null;
50          try {
51              is = new FileInputStream(file);
52              properties.loadFromXML(is);
53          } catch (Exception e) {
54              log.error("Error loading settings properties, using memory store", e);
55              IOUtils.closeQuietly(is);
56              return null;
57          }
58          return file;
59      }
60  }