2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.common.configuration.subtypes;
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;
39 * @author Michael Dürre, Herbert Eiselt
41 * subset of configuration identified by its name
43 public class Section {
46 public interface EnvGetter {
47 String getenv(String substring);
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_-]+\\})";
58 private final Pattern pattern;
60 // variables for test purpose
61 private static EnvGetter envGetter = (mkey) -> System.getenv(mkey);
63 private final String name;
64 private final List<String> rawLines;
65 private final LinkedHashMap<String, SectionValue> values;
69 public Section(String name) {
70 LOG.debug("new section created: '{}'", name);
72 this.rawLines = new ArrayList<>();
73 this.values = new LinkedHashMap<>();
74 this.pattern = Pattern.compile(REGEXENVVARIABLE);
78 // getters and setters
79 public String getName() {
82 // end of getters and setters
85 private boolean isCommentLine(String line) {
86 for (String c : COMMENTCHARS) {
87 if (line.startsWith(c)) {
93 // end of private methods
96 public void addLine(String line) {
97 LOG.trace("adding raw line:" + line);
98 this.rawLines.add(line);
101 public String getProperty(String key) {
102 return this.getProperty(key, "");
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();
111 //try to read env var
112 if (value != null && value.contains(ENVVARIABLE)) {
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);
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);
135 public boolean addComment(String key,String comment) {
136 if (this.values.containsKey(key)) {
137 this.values.get(key).addComment(DEFAULT_COMMENTCHAR+comment);
142 public boolean removeComment(String key,String comment) {
143 if (this.values.containsKey(key)) {
144 this.values.get(key).removeComment(DEFAULT_COMMENTCHAR+comment);
149 public void setProperty(String key, String value) {
150 boolean isuncommented = this.isCommentLine(key);
152 key = key.substring(1);
154 if (this.values.containsKey(key)) {
155 this.values.get(key).setValue(value).setIsUncommented(isuncommented);
157 this.values.put(key, new SectionValue(value, isuncommented));
161 public void parseLines() {
163 List<String> commentsForValue = new ArrayList<>();
164 boolean uncommented = false;
165 for (String line : rawLines) {
167 if (this.isCommentLine(line)) {
168 if (!line.contains(DELIMITER)) {
169 commentsForValue.add(line);
173 line = line.substring(1);
176 if (!line.contains(DELIMITER)) {
179 String hlp[] = line.split(DELIMITER);
180 if (hlp.length > 1) {
183 line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : "";
184 if (this.values.containsKey(key)) {
185 this.values.get(key).setValue(value);
187 this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
188 commentsForValue = new ArrayList<>();
191 LOG.warn("ignoring unknown formatted line:" + line);
197 public String[] toLines() {
198 List<String> lines = new ArrayList<>();
199 if (!this.name.isEmpty()) {
200 lines.add("[" + this.name + "]");
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()) {
209 lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
210 + sectionValue.getValue());
212 String[] alines = new String[lines.size()];
213 return lines.toArray(alines);
216 public String getString(String key, String def) {
217 return this.getProperty(key, def);
220 public boolean getBoolean(String key, boolean def) throws ConversionException {
221 String v = this.getProperty(key);
222 if (v == null || v.isEmpty()) {
225 if (v.equals("true")) {
228 if (v.equals("false")) {
231 throw new ConversionException("invalid value for key " + key);
234 public int getInt(String key, int def) throws ConversionException {
235 String v = this.getProperty(key);
236 if (v == null || v.isEmpty()) {
240 return Integer.parseInt(v);
241 } catch (NumberFormatException e) {
242 throw new ConversionException(e.getMessage());
246 public Optional<Long> getLong(String key) {
247 String v = this.getProperty(key);
249 return Optional.of(Long.parseLong(v));
250 } catch (NumberFormatException e) {
252 return Optional.empty();
255 public boolean hasValues() {
256 return this.values.size() > 0;
259 public boolean hasKey(String key) {
260 return this.values.containsKey(key);
264 public String toString() {
265 return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
269 public static void setEnvGetter(@NonNull EnvGetter newEnvGetter) {
270 if (Objects.nonNull(newEnvGetter)) {
271 envGetter = newEnvGetter;
273 throw new IllegalArgumentException("Null not allowed here");
277 public static EnvGetter getEnvGetter() {
280 // end of public methods