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