read file associations from configuration
[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     public Configuration getConfiguration() {
17         return configuration;
18     }
19
20     private Configuration configuration;
21
22     public ConfigurationManager() throws IOException {
23         initialize();
24     }
25
26     private File getPropertiesFile() {
27         return new File(System.getProperty("user.home") + "/" + CONFIG_FILE_NAME);
28     }
29
30     public File getNavigationRootDirectory() {
31         if (configuration.navigationRootPath == null){
32             configuration.navigationRootPath = System.getProperty("user.home") + "/";
33             propertiesChanged = true;
34             registerDefaultAssociations();
35         }
36
37         return new File(configuration.navigationRootPath);
38     }
39
40     private void initialize() throws IOException {
41
42         loadIfFileExists();
43
44         validatePropertiesFile();
45
46         if (propertiesChanged) {
47             saveFile();
48         }
49     }
50
51     private void loadIfFileExists() throws IOException {
52         final File propertiesFile = getPropertiesFile();
53         if (!propertiesFile.exists())
54             return;
55
56         YamlReader reader = new YamlReader(new FileReader(propertiesFile));
57         configuration = reader.read(Configuration.class);
58         if (configuration == null) {
59             configuration = new Configuration();
60             configuration.fileAssociations = new HashSet<>();
61         };
62     }
63
64     private void saveFile() throws IOException {
65         YamlWriter writer = new YamlWriter(new FileWriter(getPropertiesFile()));
66         writer.write(configuration);
67         writer.close();
68     }
69
70     private void validatePropertiesFile() {
71         getNavigationRootDirectory();
72     }
73
74     private void registerFileAssociation(String fileRegex, String command){
75         FileAssociation association = new FileAssociation(fileRegex, command);
76         configuration.fileAssociations.add(association);
77         propertiesChanged = true;
78     }
79
80
81     private void registerDefaultAssociations(){
82         registerFileAssociation(".jpeg$", "eog {file}");
83     }
84 }