c6b121ae386434d1d44b50b002ac341ac39d1a94
[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.Objects;
29 import java.util.Optional;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  *
39  * @author Michael Dürre, Herbert Eiselt
40  *
41  *         subset of configuration identified by its name
42  */
43 public class Section {
44
45     //Interfaces
46     public interface EnvGetter {
47         String getenv(String substring);
48     }
49
50     // constants
51     private static final Logger LOG = LoggerFactory.getLogger(Section.class);
52     private static final String DELIMITER = "=";
53     private static final String DEFAULT_COMMENTCHAR = "#";
54     private static final String COMMENTCHARS[] = {DEFAULT_COMMENTCHAR, ";"};
55     private static final String ENVVARIABLE = "${";
56     private static final String REGEXENVVARIABLE = "(\\$\\{[A-Z0-9_-]+\\})";
57     // end of constants
58     private final Pattern pattern;
59
60     // variables for test purpose
61     private static EnvGetter envGetter = (mkey) -> System.getenv(mkey);
62
63     private final String name;
64     private final List<String> rawLines;
65     private final LinkedHashMap<String, SectionValue> values;
66     // end of variables
67
68     // constructors
69     public Section(String name) {
70         LOG.debug("new section created: '{}'", name);
71         this.name = name;
72         this.rawLines = new ArrayList<>();
73         this.values = new LinkedHashMap<>();
74         this.pattern = Pattern.compile(REGEXENVVARIABLE);
75     }
76     //end of constructors
77
78     // getters and setters
79     public String getName() {
80         return name;
81     }
82     // end of getters and setters
83
84     // private methods
85     private boolean isCommentLine(String line) {
86         for (String c : COMMENTCHARS) {
87             if (line.startsWith(c)) {
88                 return true;
89             }
90         }
91         return false;
92     }
93     // end of private methods
94
95     // public methods
96     public void addLine(String line) {
97         LOG.trace("adding raw line:" + line);
98         this.rawLines.add(line);
99     }
100
101     public String getProperty(String key) {
102         return this.getProperty(key, "");
103     }
104
105     public String getProperty(final String key, final String defValue) {
106         String value = defValue;
107         LOG.debug("try to get property for {} with def {}", key, defValue);
108         if (values.containsKey(key)) {
109             value = values.get(key).getValue();
110         }
111         //try to read env var
112         if (value != null && value.contains(ENVVARIABLE)) {
113
114             LOG.debug("try to find env var(s) for {}", value);
115             final Matcher matcher = pattern.matcher(value);
116             String tmp = new String(value);
117             while (matcher.find() && matcher.groupCount() > 0) {
118                 final String mkey = matcher.group(1);
119                 if (mkey != null) {
120                     try {
121                         LOG.debug("match found for v={} and env key={}", tmp, mkey);
122                         //String env=System.getenv(mkey.substring(2,mkey.length()-1));
123                         String env = envGetter.getenv(mkey.substring(2, mkey.length() - 1));
124                         tmp = tmp.replace(mkey, env == null ? "" : env);
125                     } catch (SecurityException e) {
126                         LOG.warn("unable to read env {}: {}", value, e);
127                     }
128                 }
129             }
130             value = tmp;
131         }
132         return value;
133     }
134
135     public boolean addComment(String key,String comment) {
136         if (this.values.containsKey(key)) {
137             this.values.get(key).addComment(DEFAULT_COMMENTCHAR+comment);
138         }
139         return false;
140     }
141
142     public boolean removeComment(String key,String comment) {
143         if (this.values.containsKey(key)) {
144             this.values.get(key).removeComment(DEFAULT_COMMENTCHAR+comment);
145         }
146         return false;
147     }
148
149     public void setProperty(String key, String value) {
150         boolean isuncommented = this.isCommentLine(key);
151         if (isuncommented) {
152             key = key.substring(1);
153         }
154         if (this.values.containsKey(key)) {
155             this.values.get(key).setValue(value).setIsUncommented(isuncommented);
156         } else {
157             this.values.put(key, new SectionValue(value, isuncommented));
158         }
159     }
160
161     public void parseLines() {
162         this.values.clear();
163         List<String> commentsForValue = new ArrayList<>();
164         boolean uncommented = false;
165         for (String line : rawLines) {
166
167             if (this.isCommentLine(line)) {
168                 if (!line.contains(DELIMITER)) {
169                     commentsForValue.add(line);
170                     continue;
171                 } else {
172                     uncommented = true;
173                     line = line.substring(1);
174                 }
175             }
176             if (!line.contains(DELIMITER)) {
177                 continue;
178             }
179             String hlp[] = line.split(DELIMITER);
180             if (hlp.length > 1) {
181                 String key = hlp[0];
182                 String value =
183                         line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : "";
184                 if (this.values.containsKey(key)) {
185                     this.values.get(key).setValue(value);
186                 } else {
187                     this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
188                     commentsForValue = new ArrayList<>();
189                 }
190             } else {
191                 LOG.warn("ignoring unknown formatted line:" + line);
192             }
193             uncommented = false;
194         }
195     }
196
197     public String[] toLines() {
198         List<String> lines = new ArrayList<>();
199         if (!this.name.isEmpty()) {
200             lines.add("[" + this.name + "]");
201         }
202         for (Entry<String, SectionValue> entry : this.values.entrySet()) {
203             SectionValue sectionValue = entry.getValue();
204             if (sectionValue.getComments().size() > 0) {
205                 for (String comment : sectionValue.getComments()) {
206                     lines.add(comment);
207                 }
208             }
209             lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
210                     + sectionValue.getValue());
211         }
212         String[] alines = new String[lines.size()];
213         return lines.toArray(alines);
214     }
215
216     public String getString(String key, String def) {
217         return this.getProperty(key, def);
218     }
219
220     public boolean getBoolean(String key, boolean def) throws ConversionException {
221         String v = this.getProperty(key);
222         if (v == null || v.isEmpty()) {
223             return def;
224         }
225         if (v.equals("true")) {
226             return true;
227         }
228         if (v.equals("false")) {
229             return false;
230         }
231         throw new ConversionException("invalid value for key " + key);
232     }
233
234     public int getInt(String key, int def) throws ConversionException {
235         String v = this.getProperty(key);
236         if (v == null || v.isEmpty()) {
237             return def;
238         }
239         try {
240             return Integer.parseInt(v);
241         } catch (NumberFormatException e) {
242             throw new ConversionException(e.getMessage());
243         }
244     }
245
246     public Optional<Long> getLong(String key) {
247         String v = this.getProperty(key);
248         try {
249             return Optional.of(Long.parseLong(v));
250         } catch (NumberFormatException e) {
251         }
252         return Optional.empty();
253     }
254
255     public boolean hasValues() {
256         return this.values.size() > 0;
257     }
258
259     public boolean hasKey(String key) {
260         return this.values.containsKey(key);
261     }
262
263     @Override
264     public String toString() {
265         return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
266     }
267
268     // static methods
269     public static void setEnvGetter(@NonNull EnvGetter newEnvGetter) {
270         if (Objects.nonNull(newEnvGetter)) {
271             envGetter = newEnvGetter;
272         } else {
273             throw new IllegalArgumentException("Null not allowed here");
274         }
275     }
276
277     public static EnvGetter getEnvGetter() {
278         return envGetter;
279     }
280     // end of public methods
281
282 }