1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package mk.fsgrep.util;
26
27
28 import java.io.*;
29 import java.util.*;
30
31
32 /***
33 * Read default application configuration from a file.
34 * First read the config file in the user's home directory (global config).
35 * Then read the file in the current directory (local config).
36 * This the local config file overrides settings in the global config file.
37 *
38 * @author Murali Krishnan
39 *
40 */
41 public class AppProperties extends Properties {
42
43
44
45
46 static public final String USER_HOME = System.getProperty("user.home");
47 static public final String APP_DIR = USER_HOME + File.separator + ".fsgrep";
48 static public final String FILENAME_PROPS = "fsgrep.properties";
49
50
51
52
53
54 protected static void ensureAppDir() {
55 File dir = new File(APP_DIR);
56 if (!dir.exists()) {
57 if (!dir.mkdir()) {
58 System.err.println("Could not create directory [" + dir + "]");
59 }
60 }
61 }
62
63
64 public static AppProperties readDefaults() {
65 ensureAppDir();
66
67 AppProperties result = new AppProperties();
68
69 result.initialize(APP_DIR + File.separator + FILENAME_PROPS);
70
71 result.remove(Args.KEY_DEFAULT_DIR);
72
73 result.initialize(FILENAME_PROPS);
74
75 return result;
76 }
77
78
79
80
81
82 private File _source = null;
83
84
85
86
87 private AppProperties() {
88 super();
89 }
90
91
92 protected AppProperties(String filename) {
93 super();
94
95 _source = new File(filename);
96
97 if (_source.exists()) {
98 initialize(filename);
99 } else {
100 _source = null;
101 }
102 }
103
104
105
106
107
108
109 protected File getSource() {return _source;}
110
111
112
113
114
115
116
117
118
119
120
121 protected void initialize(String filename) {
122 File file = new File(filename);
123
124 if (file.exists()) {
125 try {
126 FileInputStream fis = new FileInputStream(file);
127 load(fis);
128 fis.close();
129 } catch (IOException ioe) {
130 System.err.println("Could not load properties file [" +
131 file.getAbsolutePath() + "].");
132 ioe.printStackTrace();
133 }
134 }
135 }
136
137
138 public void save() {
139 if (getSource() != null) {
140 try {
141 FileOutputStream fos = new FileOutputStream(getSource());
142 store(fos, "fsgrep persistent data");
143 fos.close();
144 } catch (IOException ioe) {
145 System.err.println("Could not save properties file [" +
146 getSource().getAbsolutePath() + "].");
147 ioe.printStackTrace();
148 }
149 }
150 }
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173 }