7fb58a165eef189597d98f47f01e0195497b71a3
[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
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  *
40  * @author Michael Dürre, Herbert Eiselt
41  *
42  *         subset of configuration identified by its name
43  */
44 public class Section {
45
46     //Interfaces
47     public interface EnvGetter {
48         String getenv(String substring);
49     }
50
51     // constants
52     private static final Logger LOG = LoggerFactory.getLogger(Section.class);
53     private static final String DELIMITER = "=";
54     private static final String COMMENTCHARS[] = {"#", ";"};
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 void setProperty(String key, String value) {
136         boolean isuncommented = this.isCommentLine(key);
137         if (isuncommented) {
138             key = key.substring(1);
139         }
140         if (this.values.containsKey(key)) {
141             this.values.get(key).setValue(value).setIsUncommented(isuncommented);
142         } else {
143             this.values.put(key, new SectionValue(value, isuncommented));
144         }
145     }
146
147     public void parseLines() {
148         this.values.clear();
149         List<String> commentsForValue = new ArrayList<>();
150         boolean uncommented = false;
151         for (String line : rawLines) {
152
153             if (this.isCommentLine(line)) {
154                 if (!line.contains(DELIMITER)) {
155                     commentsForValue.add(line);
156                     continue;
157                 } else {
158                     uncommented = true;
159                     line = line.substring(1);
160                 }
161             }
162             if (!line.contains(DELIMITER)) {
163                 continue;
164             }
165             String hlp[] = line.split(DELIMITER);
166             if (hlp.length > 1) {
167                 String key = hlp[0];
168                 String value =
169                         line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : "";
170                 if (this.values.containsKey(key)) {
171                     this.values.get(key).setValue(value);
172                 } else {
173                     this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
174                     commentsForValue = new ArrayList<>();
175                 }
176             } else {
177                 LOG.warn("ignoring unknown formatted line:" + line);
178             }
179             uncommented = false;
180         }
181     }
182
183     public String[] toLines() {
184         List<String> lines = new ArrayList<>();
185         if (!this.name.isEmpty()) {
186             lines.add("[" + this.name + "]");
187         }
188         for (Entry<String, SectionValue> entry : this.values.entrySet()) {
189             SectionValue sectionValue = entry.getValue();
190             if (sectionValue.getComments().size() > 0) {
191                 for (String comment : sectionValue.getComments()) {
192                     lines.add(comment);
193                 }
194             }
195             lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
196                     + sectionValue.getValue());
197         }
198         String[] alines = new String[lines.size()];
199         return lines.toArray(alines);
200     }
201
202     public String getString(String key, String def) {
203         return this.getProperty(key, def);
204     }
205
206     public boolean getBoolean(String key, boolean def) throws ConversionException {
207         String v = this.getProperty(key);
208         if (v == null || v.isEmpty()) {
209             return def;
210         }
211         if (v.equals("true")) {
212             return true;
213         }
214         if (v.equals("false")) {
215             return false;
216         }
217         throw new ConversionException("invalid value for key " + key);
218     }
219
220     public int getInt(String key, int def) throws ConversionException {
221         String v = this.getProperty(key);
222         if (v == null || v.isEmpty()) {
223             return def;
224         }
225         try {
226             return Integer.parseInt(v);
227         } catch (NumberFormatException e) {
228             throw new ConversionException(e.getMessage());
229         }
230     }
231
232     public Optional<Long> getLong(String key) {
233         String v = this.getProperty(key);
234         try {
235             return Optional.of(Long.parseLong(v));
236         } catch (NumberFormatException e) {
237         }
238         return Optional.empty();
239     }
240
241     public boolean hasValues() {
242         return this.values.size() > 0;
243     }
244
245     public boolean hasKey(String key) {
246         return this.values.containsKey(key);
247     }
248
249     @Override
250     public String toString() {
251         return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
252     }
253
254     // static methods
255     public static void setEnvGetter(@NonNull EnvGetter newEnvGetter) {
256         if (Objects.nonNull(newEnvGetter)) {
257             envGetter = newEnvGetter;
258         } else {
259             throw new IllegalArgumentException("Null not allowed here");
260         }
261     }
262
263     public static EnvGetter getEnvGetter() {
264         return envGetter;
265     }
266     // end of public methods
267
268 }