8fe64b5ca82b91ef95575a4b3d8cb2a9b9bb7fd3
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.internalTypes;
19
20 import java.io.BufferedReader;
21 import java.io.BufferedWriter;
22 import java.io.File;
23 import java.io.FileReader;
24 import java.io.FileWriter;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map.Entry;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class IniConfigurationFile {
34
35     private static final Logger LOG = LoggerFactory.getLogger(IniConfigurationFile.class);
36
37     private static final String SECTIONNAME_ROOT = "";
38     private static final String DELIMITER = "=";
39     private static final String COMMENTCHARS[] = {"#", ";"};
40     private static final String LR = "\n";
41
42     private final File mFile;
43     private final List<Section> sections;
44
45     public IniConfigurationFile(File f) {
46         this.mFile = f;
47         this.sections = new ArrayList<>();
48         this.sections.add(new Section(SECTIONNAME_ROOT));
49     }
50
51     public void load() throws ConfigurationException {
52         String curSectionName = SECTIONNAME_ROOT;
53         LOG.debug("loading file");
54         BufferedReader br = null;
55         try {
56             br = new BufferedReader(new FileReader(this.mFile));
57             for (String line; (line = br.readLine()) != null;) {
58                 line = line.trim();
59                 if (line.isEmpty()) {
60                     continue;
61                 }
62                 if (line.startsWith("[") && line.endsWith("]")) {
63                     curSectionName = line.substring(1, line.length() - 1);
64                     this.addSection(curSectionName);
65                 } else {
66                     this.getSection(curSectionName).addLine(line);
67                 }
68             }
69
70         } catch (Exception e) {
71             throw new ConfigurationException(e.getMessage());
72         } finally {
73             try {
74                 if (br != null) {
75                     br.close();
76                 }
77             } catch (IOException e) {
78             }
79         }
80         LOG.debug("finished loading file");
81         LOG.debug("start parsing sections");
82         for (Section section : this.sections) {
83             section.parseLines();
84         }
85         LOG.debug("finished parsing " + this.sections.size() + " sections");
86     }
87
88     private Section getSection(String name) {
89         for (Section s : this.sections) {
90             if (s.Name.equals(name)) {
91                 return s;
92             }
93         }
94         return this.addSection(name);
95
96     }
97
98     private Section addSection(String name) {
99
100         Section s = new Section(name);
101         this.sections.add(s);
102         return s;
103     }
104
105     public void reLoad() throws ConfigurationException {
106         this.sections.clear();
107         this.sections.add(new Section(SECTIONNAME_ROOT));
108         this.load();
109     }
110
111     public String getProperty(String key, String defValue) {
112         Section s;
113         if (key.contains(".")) {
114             s = this.getSection(key.substring(0, key.indexOf(".")));
115             key = key.substring(key.indexOf(".") + 1);
116         } else {
117             s = this.getSection(SECTIONNAME_ROOT);
118         }
119
120         String v = s.getProperty(key);
121         if (v == null || v.isEmpty()) {
122             return defValue;
123         }
124         return v;
125     }
126
127     public void setProperty(String key, String value) {
128         Section s;
129         if (key.contains(".")) {
130             s = this.getSection(key.substring(0, key.indexOf(".")));
131             key = key.substring(key.indexOf(".") + 1);
132         } else {
133             s = this.getSection(SECTIONNAME_ROOT);
134         }
135         s.setProperty(key, value);
136     }
137
138     public int getProperty(String key, int defValue) throws ConversionException {
139         Section s;
140         if (key.contains(".")) {
141             s = this.getSection(key.substring(0, key.indexOf(".")));
142             key = key.substring(key.indexOf(".") + 1);
143         } else {
144             s = this.getSection(SECTIONNAME_ROOT);
145         }
146
147         return s.getInt(key, defValue);
148     }
149
150     public void setProperty(String key, int value) {
151         Section s;
152         if (key.contains(".")) {
153             s = this.getSection(key.substring(0, key.indexOf(".")));
154             key = key.substring(key.indexOf(".") + 1);
155         } else {
156             s = this.getSection(SECTIONNAME_ROOT);
157         }
158         s.setProperty(key, String.format("%d", value));
159     }
160
161     public boolean getProperty(String key, boolean defValue) throws ConversionException {
162         Section s;
163         if (key.contains(".")) {
164             s = this.getSection(key.substring(0, key.indexOf(".")));
165             key = key.substring(key.indexOf(".") + 1);
166         } else {
167             s = this.getSection(SECTIONNAME_ROOT);
168         }
169
170         return s.getBoolean(key, defValue);
171     }
172
173     public void setProperty(String key, boolean value) {
174         Section s;
175         if (key.contains(".")) {
176             s = this.getSection(key.substring(0, key.indexOf(".")));
177             key = key.substring(key.indexOf(".") + 1);
178         } else {
179             s = this.getSection(SECTIONNAME_ROOT);
180         }
181         s.setProperty(key, value ? "true" : "false");
182     }
183
184     public void setProperty(String key, Object value) {
185         this.setProperty(key, value == null ? "null" : value.toString());
186     }
187
188     public void save() {
189         try (BufferedWriter bw = new BufferedWriter(new FileWriter(this.mFile, false))) {
190             for (Section section : this.sections) {
191                 if (section.hasValues()) {
192                     bw.write(String.join(LR, section.toLines()) + LR + LR);
193                 }
194             }
195             bw.close();
196         } catch (Exception e) {
197             LOG.warn("problem saving value: " + e.getMessage());
198         }
199     }
200
201     public Section subset(String section) {
202         return this.getSection(section);
203     }
204
205     public static class ConfigurationException extends Exception {
206
207         private static final long serialVersionUID = 733061908616404383L;
208
209         public ConfigurationException(String m) {
210             super(m);
211         }
212     }
213
214     public static class ConversionException extends Exception {
215         private static final long serialVersionUID = 5179891576029923079L;
216
217         public ConversionException(String m) {
218             super(m);
219         }
220     }
221
222     private static class SectionValue {
223         private String Value;
224         private final List<String> Comments;
225         private boolean IsUncommented;
226
227         public SectionValue(String value) {
228             this(value, new ArrayList<String>(), false);
229         }
230
231         public SectionValue(String value, List<String> commentsForValue, boolean isuncommented) {
232             this.Comments = commentsForValue;
233             this.Value = value;
234             this.IsUncommented = isuncommented;
235         }
236     }
237
238     public static class Section {
239         private final String Name;
240         private final List<String> rawLines;
241         private final LinkedHashMap<String, SectionValue> values;
242
243         public Section(String name) {
244             LOG.debug("new section created:" + name);
245             this.Name = name;
246             this.rawLines = new ArrayList<>();
247             this.values = new LinkedHashMap<>();
248         }
249
250         public void addLine(String line) {
251             LOG.trace("adding raw line:" + line);
252             this.rawLines.add(line);
253         }
254
255         public String getProperty(String key) {
256             return this.getProperty(key, null);
257         }
258
259         public String getProperty(String key, String defValue) {
260             if (values.containsKey(key)) {
261                 return values.get(key).Value;
262             }
263             return defValue;
264         }
265
266         public void setProperty(String key, String value) {
267             boolean isuncommented = this.isCommentLine(key);
268             if (isuncommented) {
269                 key = key.substring(1);
270             }
271             if (this.values.containsKey(key)) {
272                 this.values.get(key).Value = value;
273                 this.values.get(key).IsUncommented = isuncommented;
274             } else {
275                 SectionValue sv = new SectionValue(value);
276                 sv.IsUncommented = isuncommented;
277                 this.values.put(key, sv);
278             }
279         }
280
281         public void parseLines() {
282             this.values.clear();
283             List<String> commentsForValue = new ArrayList<>();
284             boolean uncommented = false;
285             for (String line : rawLines) {
286
287                 if (this.isCommentLine(line)) {
288                     if (!line.contains(DELIMITER)) {
289                         commentsForValue.add(line);
290                         continue;
291                     } else {
292                         uncommented = true;
293                         line = line.substring(1);
294                     }
295                 }
296                 if (!line.contains(DELIMITER)) {
297                     continue;
298                 }
299                 String hlp[] = line.split(DELIMITER);
300                 if (hlp.length > 1) {
301                     String key = hlp[0];
302                     String value =
303                             line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length())
304                                     : "";
305                     if (this.values.containsKey(key)) {
306                         this.values.get(key).Value = value;
307                     } else {
308                         this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
309                         commentsForValue = new ArrayList<>();
310                     }
311                 } else {
312                     LOG.warn("ignoring unknown formatted line:" + line);
313                 }
314                 uncommented = false;
315             }
316         }
317
318         private boolean isCommentLine(String line) {
319             for (String c : COMMENTCHARS) {
320                 if (line.startsWith(c)) {
321                     return true;
322                 }
323             }
324             return false;
325         }
326
327         public String[] toLines() {
328             List<String> lines = new ArrayList<>();
329             if (!this.Name.isEmpty()) {
330                 lines.add("[" + this.Name + "]");
331             }
332             for (Entry<String, SectionValue> entry : this.values.entrySet()) {
333                 if (entry.getValue().Comments.size() > 0) {
334                     for (String comment : entry.getValue().Comments) {
335                         lines.add(comment);
336                     }
337                 }
338                 lines.add((entry.getValue().IsUncommented ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
339                         + entry.getValue().Value);
340             }
341             String[] alines = new String[lines.size()];
342             return lines.toArray(alines);
343         }
344
345         public String getString(String key, String def) {
346             return this.getProperty(key, def);
347         }
348
349         public boolean getBoolean(String key, boolean def) throws ConversionException {
350             String v = this.getProperty(key);
351             if (v == null || v.isEmpty()) {
352                 return def;
353             }
354             if (v.equals("true")) {
355                 return true;
356             }
357             if (v.equals("false")) {
358                 return false;
359             }
360             throw new ConversionException("invalid value for key " + key);
361         }
362
363         public int getInt(String key, int def) throws ConversionException {
364             String v = this.getProperty(key);
365             if (v == null || v.isEmpty()) {
366                 return def;
367             }
368             try {
369                 return Integer.parseInt(v);
370             } catch (NumberFormatException e) {
371                 throw new ConversionException(e.getMessage());
372             }
373         }
374
375         public long getLong(String key, long def) throws ConversionException {
376             String v = this.getProperty(key);
377             if (v == null || v.isEmpty()) {
378                 return def;
379             }
380             try {
381                 return Long.parseLong(v);
382             } catch (NumberFormatException e) {
383                 throw new ConversionException(e.getMessage());
384             }
385         }
386
387         public boolean hasValues() {
388             return this.values.size() > 0;
389         }
390
391         public boolean hasKey(String key) {
392             return this.values.containsKey(key);
393         }
394
395     }
396
397 }