ebb46547ea144719b2193457210bd1744ff6942d
[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
112     public void setProperty(String key, String value) {
113         Section s;
114         if (key.contains(".")) {
115             s = this.getSection(key.substring(0, key.indexOf(".")));
116             key = key.substring(key.indexOf(".") + 1);
117         } else {
118             s = this.getSection(SECTIONNAME_ROOT);
119         }
120         s.setProperty(key, value);
121     }
122
123
124     public void setProperty(String key, int value) {
125         Section s;
126         if (key.contains(".")) {
127             s = this.getSection(key.substring(0, key.indexOf(".")));
128             key = key.substring(key.indexOf(".") + 1);
129         } else {
130             s = this.getSection(SECTIONNAME_ROOT);
131         }
132         s.setProperty(key, String.format("%d", value));
133     }
134
135
136     public void setProperty(String key, boolean value) {
137         Section s;
138         if (key.contains(".")) {
139             s = this.getSection(key.substring(0, key.indexOf(".")));
140             key = key.substring(key.indexOf(".") + 1);
141         } else {
142             s = this.getSection(SECTIONNAME_ROOT);
143         }
144         s.setProperty(key, value ? "true" : "false");
145     }
146
147     public void setProperty(String key, Object value) {
148         this.setProperty(key, value == null ? "null" : value.toString());
149     }
150
151     public void save() {
152         try (BufferedWriter bw = new BufferedWriter(new FileWriter(this.mFile, false))) {
153             for (Section section : this.sections) {
154                 if (section.hasValues()) {
155                     bw.write(String.join(LR, section.toLines()) + LR + LR);
156                 }
157             }
158             bw.close();
159         } catch (Exception e) {
160             LOG.warn("problem saving value: " + e.getMessage());
161         }
162     }
163
164     public Section subset(String section) {
165         return this.getSection(section);
166     }
167
168     public static class ConfigurationException extends Exception {
169
170         private static final long serialVersionUID = 733061908616404383L;
171
172         public ConfigurationException(String m) {
173             super(m);
174         }
175     }
176
177     public static class ConversionException extends Exception {
178         private static final long serialVersionUID = 5179891576029923079L;
179
180         public ConversionException(String m) {
181             super(m);
182         }
183     }
184
185     private static class SectionValue {
186         private String Value;
187         private final List<String> Comments;
188         private boolean IsUncommented;
189
190         public SectionValue(String value) {
191             this(value, new ArrayList<String>(), false);
192         }
193
194         public SectionValue(String value, List<String> commentsForValue, boolean isuncommented) {
195             this.Comments = commentsForValue;
196             this.Value = value;
197             this.IsUncommented = isuncommented;
198         }
199     }
200
201     public static class Section {
202         private final String Name;
203         private final List<String> rawLines;
204         private final LinkedHashMap<String, SectionValue> values;
205
206         public Section(String name) {
207             LOG.debug("new section created:" + name);
208             this.Name = name;
209             this.rawLines = new ArrayList<>();
210             this.values = new LinkedHashMap<>();
211         }
212
213         public void addLine(String line) {
214             LOG.trace("adding raw line:" + line);
215             this.rawLines.add(line);
216         }
217
218         public String getProperty(String key) {
219             return this.getProperty(key, null);
220         }
221
222         public String getProperty(String key, String defValue) {
223             if (values.containsKey(key)) {
224                 return values.get(key).Value;
225             }
226             return defValue;
227         }
228
229         public void setProperty(String key, String value) {
230             boolean isuncommented = this.isCommentLine(key);
231             if (isuncommented) {
232                 key = key.substring(1);
233             }
234             if (this.values.containsKey(key)) {
235                 this.values.get(key).Value = value;
236                 this.values.get(key).IsUncommented = isuncommented;
237             } else {
238                 SectionValue sv = new SectionValue(value);
239                 sv.IsUncommented = isuncommented;
240                 this.values.put(key, sv);
241             }
242         }
243
244         public void parseLines() {
245             this.values.clear();
246             List<String> commentsForValue = new ArrayList<>();
247             boolean uncommented = false;
248             for (String line : rawLines) {
249
250                 if (this.isCommentLine(line)) {
251                     if (!line.contains(DELIMITER)) {
252                         commentsForValue.add(line);
253                         continue;
254                     } else {
255                         uncommented = true;
256                         line = line.substring(1);
257                     }
258                 }
259                 if (!line.contains(DELIMITER)) {
260                     continue;
261                 }
262                 String hlp[] = line.split(DELIMITER);
263                 if (hlp.length > 1) {
264                     String key = hlp[0];
265                     String value =
266                             line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length())
267                                     : "";
268                     if (this.values.containsKey(key)) {
269                         this.values.get(key).Value = value;
270                     } else {
271                         this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
272                         commentsForValue = new ArrayList<>();
273                     }
274                 } else {
275                     LOG.warn("ignoring unknown formatted line:" + line);
276                 }
277                 uncommented = false;
278             }
279         }
280
281         private boolean isCommentLine(String line) {
282             for (String c : COMMENTCHARS) {
283                 if (line.startsWith(c)) {
284                     return true;
285                 }
286             }
287             return false;
288         }
289
290         public String[] toLines() {
291             List<String> lines = new ArrayList<>();
292             if (!this.Name.isEmpty()) {
293                 lines.add("[" + this.Name + "]");
294             }
295             for (Entry<String, SectionValue> entry : this.values.entrySet()) {
296                 if (entry.getValue().Comments.size() > 0) {
297                     for (String comment : entry.getValue().Comments) {
298                         lines.add(comment);
299                     }
300                 }
301                 lines.add((entry.getValue().IsUncommented ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
302                         + entry.getValue().Value);
303             }
304             String[] alines = new String[lines.size()];
305             return lines.toArray(alines);
306         }
307
308         public String getString(String key, String def) {
309             return this.getProperty(key, def);
310         }
311
312         public boolean getBoolean(String key, boolean def) throws ConversionException {
313             String v = this.getProperty(key);
314             if (v == null || v.isEmpty()) {
315                 return def;
316             }
317             if (v.equals("true")) {
318                 return true;
319             }
320             if (v.equals("false")) {
321                 return false;
322             }
323             throw new ConversionException("invalid value for key " + key);
324         }
325
326         public int getInt(String key, int def) throws ConversionException {
327             String v = this.getProperty(key);
328             if (v == null || v.isEmpty()) {
329                 return def;
330             }
331             try {
332                 return Integer.parseInt(v);
333             } catch (NumberFormatException e) {
334                 throw new ConversionException(e.getMessage());
335             }
336         }
337
338         public long getLong(String key, long def) throws ConversionException {
339             String v = this.getProperty(key);
340             if (v == null || v.isEmpty()) {
341                 return def;
342             }
343             try {
344                 return Long.parseLong(v);
345             } catch (NumberFormatException e) {
346                 throw new ConversionException(e.getMessage());
347             }
348         }
349
350         public boolean hasValues() {
351             return this.values.size() > 0;
352         }
353
354         public boolean hasKey(String key) {
355             return this.values.containsKey(key);
356         }
357
358     }
359
360 }