54ebd03aca8dc0d91b2a71aa0befb2e10449507f
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.common.configuration.subtypes;
23
24 import java.util.ArrayList;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * 
38  * @author Michael Dürre, Herbert Eiselt
39  *
40  *         subset of configuration identified by its name
41  */
42 public class Section {
43
44     // constants
45     private static final Logger LOG = LoggerFactory.getLogger(Section.class);
46     private static final String DELIMITER = "=";
47     private static final String COMMENTCHARS[] = {"#", ";"};
48     // end of constants
49
50     // variables
51     private final String name;
52     private final List<String> rawLines;
53     private final LinkedHashMap<String, SectionValue> values;
54     // end of variables
55
56     // constructors
57     public Section(String name) {
58         LOG.debug("new section created: '{}'", name);
59         this.name = name;
60         this.rawLines = new ArrayList<>();
61         this.values = new LinkedHashMap<>();
62     }
63     //end of constructors
64
65     // getters and setters
66     public String getName() {
67         return name;
68     }
69     // end of getters and setters
70
71     // private methods
72     private boolean isCommentLine(String line) {
73         for (String c : COMMENTCHARS) {
74             if (line.startsWith(c)) {
75                 return true;
76             }
77         }
78         return false;
79     }
80     // end of private methods
81
82     // public methods
83     public void addLine(String line) {
84         LOG.trace("adding raw line:" + line);
85         this.rawLines.add(line);
86     }
87
88     public String getProperty(String key) {
89         return this.getProperty(key, "");
90     }
91
92     public String getProperty(final String key, final String defValue) {
93         String value = defValue;
94         LOG.debug("try to get property for {} with def {}", key, defValue);
95         if (values.containsKey(key)) {
96             value = values.get(key).getValue();
97         }
98         //try to read env var
99         if (value != null && value.contains("${")) {
100
101             LOG.debug("try to find env var(s) for {}", value);
102             final String regex = "(\\$\\{[A-Z0-9_-]+\\})";
103             final Pattern pattern = Pattern.compile(regex);
104             final Matcher matcher = pattern.matcher(value);
105             String tmp = new String(value);
106             while (matcher.find() && matcher.groupCount() > 0) {
107                 final String mkey = matcher.group(1);
108                 if (mkey != null) {
109                     try {
110                         LOG.debug("match found for v={} and env key={}", tmp, mkey);
111                         String env = System.getenv(mkey.substring(2, mkey.length() - 1));
112                         tmp = tmp.replace(mkey, env == null ? "" : env);
113                     } catch (SecurityException e) {
114                         LOG.warn("unable to read env {}: {}", value, e);
115                     }
116                 }
117             }
118             value = tmp;
119         }
120         return value;
121     }
122
123
124
125     public void setProperty(String key, String value) {
126         boolean isuncommented = this.isCommentLine(key);
127         if (isuncommented) {
128             key = key.substring(1);
129         }
130         if (this.values.containsKey(key)) {
131             this.values.get(key).setValue(value).setIsUncommented(isuncommented);
132         } else {
133             this.values.put(key, new SectionValue(value, isuncommented));
134         }
135     }
136
137     public void parseLines() {
138         this.values.clear();
139         List<String> commentsForValue = new ArrayList<>();
140         boolean uncommented = false;
141         for (String line : rawLines) {
142
143             if (this.isCommentLine(line)) {
144                 if (!line.contains(DELIMITER)) {
145                     commentsForValue.add(line);
146                     continue;
147                 } else {
148                     uncommented = true;
149                     line = line.substring(1);
150                 }
151             }
152             if (!line.contains(DELIMITER)) {
153                 continue;
154             }
155             String hlp[] = line.split(DELIMITER);
156             if (hlp.length > 1) {
157                 String key = hlp[0];
158                 String value =
159                         line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : "";
160                 if (this.values.containsKey(key)) {
161                     this.values.get(key).setValue(value);
162                 } else {
163                     this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
164                     commentsForValue = new ArrayList<>();
165                 }
166             } else {
167                 LOG.warn("ignoring unknown formatted line:" + line);
168             }
169             uncommented = false;
170         }
171     }
172
173
174
175     public String[] toLines() {
176         List<String> lines = new ArrayList<>();
177         if (!this.name.isEmpty()) {
178             lines.add("[" + this.name + "]");
179         }
180         for (Entry<String, SectionValue> entry : this.values.entrySet()) {
181             SectionValue sectionValue = entry.getValue();
182             if (sectionValue.getComments().size() > 0) {
183                 for (String comment : sectionValue.getComments()) {
184                     lines.add(comment);
185                 }
186             }
187             lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
188                     + sectionValue.getValue());
189         }
190         String[] alines = new String[lines.size()];
191         return lines.toArray(alines);
192     }
193
194     public String getString(String key, String def) {
195         return this.getProperty(key, def);
196     }
197
198     public boolean getBoolean(String key, boolean def) throws ConversionException {
199         String v = this.getProperty(key);
200         if (v == null || v.isEmpty()) {
201             return def;
202         }
203         if (v.equals("true")) {
204             return true;
205         }
206         if (v.equals("false")) {
207             return false;
208         }
209         throw new ConversionException("invalid value for key " + key);
210     }
211
212     public int getInt(String key, int def) throws ConversionException {
213         String v = this.getProperty(key);
214         if (v == null || v.isEmpty()) {
215             return def;
216         }
217         try {
218             return Integer.parseInt(v);
219         } catch (NumberFormatException e) {
220             throw new ConversionException(e.getMessage());
221         }
222     }
223
224     public Optional<Long> getLong(String key) {
225         String v = this.getProperty(key);
226         try {
227             return Optional.of(Long.parseLong(v));
228         } catch (NumberFormatException e) {
229         }
230         return Optional.empty();
231     }
232
233     public boolean hasValues() {
234         return this.values.size() > 0;
235     }
236
237     public boolean hasKey(String key) {
238         return this.values.containsKey(key);
239     }
240
241     @Override
242     public String toString() {
243         return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
244     }
245     // end of public methods
246
247 }