1160c281cab298defb06149ca6289597beb5f52b
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.common.configuration.subtypes;
19
20 import java.util.ArrayList;
21 import java.util.LinkedHashMap;
22 import java.util.List;
23 import java.util.Map.Entry;
24 import java.util.Optional;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class Section {
33
34     private static final Logger LOG = LoggerFactory.getLogger(Section.class);
35     private static final String DELIMITER = "=";
36     private static final String COMMENTCHARS[] = {"#", ";"};
37
38     private final String name;
39     private final List<String> rawLines;
40     private final LinkedHashMap<String, SectionValue> values;
41
42     public Section(String name) {
43         LOG.debug("new section created: '{}'", name);
44         this.name = name;
45         this.rawLines = new ArrayList<>();
46         this.values = new LinkedHashMap<>();
47     }
48
49     public void addLine(String line) {
50         LOG.trace("adding raw line:" + line);
51         this.rawLines.add(line);
52     }
53
54     public String getProperty(String key) {
55         return this.getProperty(key, "");
56     }
57
58         public String getProperty(final String key, final String defValue) {
59                 String value=defValue;
60                 LOG.debug("try to get property for {} with def {}",key,defValue);
61                 if (values.containsKey(key)) {
62                         value = values.get(key).getValue();
63                 }
64                 //try to read env var
65                 if (value != null && value.contains("${")) {
66                         
67                         LOG.debug("try to find env var(s) for {}",value);
68                         final String regex = "(\\$\\{[A-Z]+\\})";
69                         final Pattern pattern = Pattern.compile(regex);
70                         final Matcher matcher = pattern.matcher(value);
71                         String tmp=new String(value);
72                         while(matcher.find() && matcher.groupCount()>0) {
73                                 final String mkey = matcher.group(1);
74                                 if(mkey!=null) {
75                                         try {
76                                                 LOG.debug("match found for v={} and env key={}",tmp,mkey);
77                                                 String env=System.getenv(mkey.substring(2,mkey.length()-1));
78                                                 tmp = tmp.replace(mkey, env==null?"":env );     
79                                         } catch (SecurityException e) {
80                                                 LOG.warn("unable to read env {}: {}", value, e);
81                                         }
82                                 }
83                         }
84                         value=tmp;
85                 }
86                 return value;
87         }
88
89     public String getName() {
90         return name;
91     }
92
93     public void setProperty(String key, String value) {
94         boolean isuncommented = this.isCommentLine(key);
95         if (isuncommented) {
96             key = key.substring(1);
97         }
98         if (this.values.containsKey(key)) {
99             this.values.get(key).setValue(value).setIsUncommented(isuncommented);
100         } else {
101             this.values.put(key, new SectionValue(value,isuncommented));
102         }
103     }
104
105     public void parseLines() {
106         this.values.clear();
107         List<String> commentsForValue = new ArrayList<>();
108         boolean uncommented = false;
109         for (String line : rawLines) {
110
111             if (this.isCommentLine(line)) {
112                 if (!line.contains(DELIMITER)) {
113                     commentsForValue.add(line);
114                     continue;
115                 } else {
116                     uncommented = true;
117                     line = line.substring(1);
118                 }
119             }
120             if (!line.contains(DELIMITER)) {
121                 continue;
122             }
123             String hlp[] = line.split(DELIMITER);
124             if (hlp.length > 1) {
125                 String key = hlp[0];
126                 String value =
127                         line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length())
128                                 : "";
129                 if (this.values.containsKey(key)) {
130                     this.values.get(key).setValue(value);
131                 } else {
132                     this.values.put(key, new SectionValue(value, commentsForValue, uncommented));
133                     commentsForValue = new ArrayList<>();
134                 }
135             } else {
136                 LOG.warn("ignoring unknown formatted line:" + line);
137             }
138             uncommented = false;
139         }
140     }
141
142     private boolean isCommentLine(String line) {
143         for (String c : COMMENTCHARS) {
144             if (line.startsWith(c)) {
145                 return true;
146             }
147         }
148         return false;
149     }
150
151     public String[] toLines() {
152         List<String> lines = new ArrayList<>();
153         if (!this.name.isEmpty()) {
154             lines.add("[" + this.name + "]");
155         }
156         for (Entry<String, SectionValue> entry : this.values.entrySet()) {
157             SectionValue sectionValue = entry.getValue();
158             if (sectionValue.getComments().size() > 0) {
159                 for (String comment : sectionValue.getComments()) {
160                     lines.add(comment);
161                 }
162             }
163             lines.add((sectionValue.isUncommented() ? COMMENTCHARS[0] : "") + entry.getKey() + DELIMITER
164                     + sectionValue.getValue());
165         }
166         String[] alines = new String[lines.size()];
167         return lines.toArray(alines);
168     }
169
170     public String getString(String key, String def) {
171         return this.getProperty(key, def);
172     }
173
174     public boolean getBoolean(String key, boolean def) throws ConversionException {
175         String v = this.getProperty(key);
176         if (v == null || v.isEmpty()) {
177             return def;
178         }
179         if (v.equals("true")) {
180             return true;
181         }
182         if (v.equals("false")) {
183             return false;
184         }
185         throw new ConversionException("invalid value for key " + key);
186     }
187
188     public int getInt(String key, int def) throws ConversionException {
189         String v = this.getProperty(key);
190         if (v == null || v.isEmpty()) {
191             return def;
192         }
193         try {
194             return Integer.parseInt(v);
195         } catch (NumberFormatException e) {
196             throw new ConversionException(e.getMessage());
197         }
198     }
199
200     public Optional<Long> getLong(String key) {
201         String v = this.getProperty(key);
202         try {
203             return Optional.of(Long.parseLong(v));
204         } catch (NumberFormatException e) {
205         }
206            return Optional.empty();
207     }
208
209     public boolean hasValues() {
210         return this.values.size() > 0;
211     }
212
213     public boolean hasKey(String key) {
214         return this.values.containsKey(key);
215     }
216
217     @Override
218     public String toString() {
219         return "Section [name=" + name + ", rawLines=" + rawLines + ", values=" + values + "]";
220     }
221
222 }