Switched to YAML config format.
[instantlauncher.git] / src / main / java / eu / svjatoslav / instantlauncher / configuration / ConfigurationManager.java
1 package eu.svjatoslav.instantlauncher.configuration;
2
3 import com.esotericsoftware.yamlbeans.YamlReader;
4 import com.esotericsoftware.yamlbeans.YamlWriter;
5
6 import java.io.*;
7 import java.util.HashSet;
8 import java.util.Map;
9
10 public class ConfigurationManager {
11
12     private static final String CONFIG_FILE_NAME = ".instantlauncher";
13
14     private boolean propertiesChanged = false;
15
16     Configuration configuration;
17
18     public ConfigurationManager() throws IOException {
19         initialize();
20     }
21
22     private File getPropertiesFile() {
23         return new File(System.getProperty("user.home") + "/" + CONFIG_FILE_NAME);
24     }
25
26     public File getNavigationRootDirectory() {
27         if (configuration.navigationRootPath == null){
28             configuration.navigationRootPath = System.getProperty("user.home") + "/";
29             propertiesChanged = true;
30             registerDefaultAssociations();
31         }
32
33         return new File(configuration.navigationRootPath);
34     }
35
36     private void initialize() throws IOException {
37
38         loadIfFileExists();
39
40         validatePropertiesFile();
41
42         if (propertiesChanged) {
43             saveFile();
44         }
45     }
46
47     private void loadIfFileExists() throws IOException {
48         final File propertiesFile = getPropertiesFile();
49         if (!propertiesFile.exists())
50             return;
51
52         YamlReader reader = new YamlReader(new FileReader(propertiesFile));
53         configuration = reader.read(Configuration.class);
54         if (configuration == null) {
55             configuration = new Configuration();
56             configuration.fileAssociations = new HashSet<>();
57         };
58     }
59
60     private void saveFile() throws IOException {
61         YamlWriter writer = new YamlWriter(new FileWriter(getPropertiesFile()));
62         writer.write(configuration);
63         writer.close();
64     }
65
66     private void validatePropertiesFile() {
67         getNavigationRootDirectory();
68     }
69
70     private void registerFileAssociation(String fileRegex, String command){
71         FileAssociation association = new FileAssociation(fileRegex, command);
72         configuration.fileAssociations.add(association);
73         propertiesChanged = true;
74     }
75
76     private void registerDefaultAssociations(){
77         registerFileAssociation(".jpeg$", "eog {file}");
78     }
79 }