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;
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;
40 * @author Michael Dürre, Herbert Eiselt
42 * subset of configuration identified by its name
44 public class Section {
47 public interface EnvGetter {
48 String getenv(String substring);
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_-]+\\})";
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 void setProperty(String key, String value) {
136 boolean isuncommented = this.isCommentLine(key);
138 key = key.substring(1);
140 if (this.values.containsKey(key)) {
141 this.values.get(key).setValue(value).setIsUncommented(isuncommented);
143 this.values.put(key, new SectionValue(value, isuncommented));
147 public void parseLines() {
149 List<String> commentsForValue = new ArrayList<>();
150 boolean uncommented = false;
151 for (String line : rawLines) {
153 if (this.isCommentLine(line)) {
154 if (!line.contains(DELIMITER)) {
155 commentsForValue.add(line);
159 line = line.substring(1);
162 if (!line.contains(DELIMITER)) {
165 String hlp[] = line.split(DELIMITER);
166 if (hlp.length > 1) {
169 line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : "";
170 if (this.values.containsKey(key)) {
171 this.values.get(key).setValue(value);
173 this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
174 commentsForValue = new ArrayList<>();
177 LOG.warn("ignoring unknown formatted line:" + line);
183 public String[] toLines() {
184 List<String> lines = new ArrayList<>();
185 if (!this.name.isEmpty()) {
186 lines.add("[" + this.name + "]");
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()) {
195 lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
196 + sectionValue.getValue());
198 String[] alines = new String[lines.size()];
199 return lines.toArray(alines);
202 public String getString(String key, String def) {
203 return this.getProperty(key, def);
206 public boolean getBoolean(String key, boolean def) throws ConversionException {
207 String v = this.getProperty(key);
208 if (v == null || v.isEmpty()) {
211 if (v.equals("true")) {
214 if (v.equals("false")) {
217 throw new ConversionException("invalid value for key " + key);
220 public int getInt(String key, int def) throws ConversionException {
221 String v = this.getProperty(key);
222 if (v == null || v.isEmpty()) {
226 return Integer.parseInt(v);
227 } catch (NumberFormatException e) {
228 throw new ConversionException(e.getMessage());
232 public Optional<Long> getLong(String key) {
233 String v = this.getProperty(key);
235 return Optional.of(Long.parseLong(v));
236 } catch (NumberFormatException e) {
238 return Optional.empty();
241 public boolean hasValues() {
242 return this.values.size() > 0;
245 public boolean hasKey(String key) {
246 return this.values.containsKey(key);
250 public String toString() {
251 return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
255 public static void setEnvGetter(@NonNull EnvGetter newEnvGetter) {
256 if (Objects.nonNull(newEnvGetter)) {
257 envGetter = newEnvGetter;
259 throw new IllegalArgumentException("Null not allowed here");
263 public static EnvGetter getEnvGetter() {
266 // end of public methods