fd1e404a1eff8ca941ee4d6aae1c401e0e329830
[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 public class Section {
37
38     private static final Logger LOG = LoggerFactory.getLogger(Section.class);
39     private static final String DELIMITER = "=";
40     private static final String COMMENTCHARS[] = {"#", ";"};
41
42     private final String name;
43     private final List<String> rawLines;
44     private final LinkedHashMap<String, SectionValue> values;
45
46     public Section(String name) {
47         LOG.debug("new section created: '{}'", name);
48         this.name = name;
49         this.rawLines = new ArrayList<>();
50         this.values = new LinkedHashMap<>();
51     }
52
53     public void addLine(String line) {
54         LOG.trace("adding raw line:" + line);
55         this.rawLines.add(line);
56     }
57
58     public String getProperty(String key) {
59         return this.getProperty(key, "");
60     }
61
62         public String getProperty(final String key, final String defValue) {
63                 String value=defValue;
64                 LOG.debug("try to get property for {} with def {}",key,defValue);
65                 if (values.containsKey(key)) {
66                         value = values.get(key).getValue();
67                 }
68                 //try to read env var
69                 if (value != null && value.contains("${")) {
70                         
71                         LOG.debug("try to find env var(s) for {}",value);
72                         final String regex = "(\\$\\{[A-Z]+\\})";
73                         final Pattern pattern = Pattern.compile(regex);
74                         final Matcher matcher = pattern.matcher(value);
75                         String tmp=new String(value);
76                         while(matcher.find() && matcher.groupCount()>0) {
77                                 final String mkey = matcher.group(1);
78                                 if(mkey!=null) {
79                                         try {
80                                                 LOG.debug("match found for v={} and env key={}",tmp,mkey);
81                                                 String env=System.getenv(mkey.substring(2,mkey.length()-1));
82                                                 tmp = tmp.replace(mkey, env==null?"":env );     
83                                         } catch (SecurityException e) {
84                                                 LOG.warn("unable to read env {}: {}", value, e);
85                                         }
86                                 }
87                         }
88                         value=tmp;
89                 }
90                 return value;
91         }
92
93     public String getName() {
94         return name;
95     }
96
97     public void setProperty(String key, String value) {
98         boolean isuncommented = this.isCommentLine(key);
99         if (isuncommented) {
100             key = key.substring(1);
101         }
102         if (this.values.containsKey(key)) {
103             this.values.get(key).setValue(value).setIsUncommented(isuncommented);
104         } else {
105             this.values.put(key, new SectionValue(value,isuncommented));
106         }
107     }
108
109     public void parseLines() {
110         this.values.clear();
111         List<String> commentsForValue = new ArrayList<>();
112         boolean uncommented = false;
113         for (String line : rawLines) {
114
115             if (this.isCommentLine(line)) {
116                 if (!line.contains(DELIMITER)) {
117                     commentsForValue.add(line);
118                     continue;
119                 } else {
120                     uncommented = true;
121                     line = line.substring(1);
122                 }
123             }
124             if (!line.contains(DELIMITER)) {
125                 continue;
126             }
127             String hlp[] = line.split(DELIMITER);
128             if (hlp.length > 1) {
129                 String key = hlp[0];
130                 String value =
131                         line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length())
132                                 : "";
133                 if (this.values.containsKey(key)) {
134                     this.values.get(key).setValue(value);
135                 } else {
136                     this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
137                     commentsForValue = new ArrayList<>();
138                 }
139             } else {
140                 LOG.warn("ignoring unknown formatted line:" + line);
141             }
142             uncommented = false;
143         }
144     }
145
146     private boolean isCommentLine(String line) {
147         for (String c : COMMENTCHARS) {
148             if (line.startsWith(c)) {
149                 return true;
150             }
151         }
152         return false;
153     }
154
155     public String[] toLines() {
156         List<String> lines = new ArrayList<>();
157         if (!this.name.isEmpty()) {
158             lines.add("[" + this.name + "]");
159         }
160         for (Entry<String, SectionValue> entry : this.values.entrySet()) {
161             SectionValue sectionValue = entry.getValue();
162             if (sectionValue.getComments().size() > 0) {
163                 for (String comment : sectionValue.getComments()) {
164                     lines.add(comment);
165                 }
166             }
167             lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
168                     + sectionValue.getValue());
169         }
170         String[] alines = new String[lines.size()];
171         return lines.toArray(alines);
172     }
173
174     public String getString(String key, String def) {
175         return this.getProperty(key, def);
176     }
177
178     public boolean getBoolean(String key, boolean def) throws ConversionException {
179         String v = this.getProperty(key);
180         if (v == null || v.isEmpty()) {
181             return def;
182         }
183         if (v.equals("true")) {
184             return true;
185         }
186         if (v.equals("false")) {
187             return false;
188         }
189         throw new ConversionException("invalid value for key " + key);
190     }
191
192     public int getInt(String key, int def) throws ConversionException {
193         String v = this.getProperty(key);
194         if (v == null || v.isEmpty()) {
195             return def;
196         }
197         try {
198             return Integer.parseInt(v);
199         } catch (NumberFormatException e) {
200             throw new ConversionException(e.getMessage());
201         }
202     }
203
204     public Optional<Long> getLong(String key) {
205         String v = this.getProperty(key);
206         try {
207             return Optional.of(Long.parseLong(v));
208         } catch (NumberFormatException e) {
209         }
210            return Optional.empty();
211     }
212
213     public boolean hasValues() {
214         return this.values.size() > 0;
215     }
216
217     public boolean hasKey(String key) {
218         return this.values.containsKey(key);
219     }
220
221     @Override
222     public String toString() {
223         return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
224     }
225
226 }