e590d7faf6e257d7a0dacad0a7a43475f9f64ac0
[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.devicemanager.aaiconnector.impl.config;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.Base64;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.Properties;
30 import org.json.JSONArray;
31 import org.onap.ccsdk.features.sdnr.wt.common.HtAssert;
32 import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration;
33 import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class AaiConfig implements Configuration {
38
39     private static Logger LOG = LoggerFactory.getLogger(AaiConfig.class);
40
41     private static final String SECTION_MARKER_AAI = "aai";
42
43     private enum Config {
44         // @formatter:off
45         AAIPROP_FILE("aaiPropertiesFile", "null"),
46         BASEURL("aaiUrl", "off", "org.onap.ccsdk.sli.adaptors.aai.uri"),
47         USERCREDENTIALS("aaiUserCredentials", ""),
48         HEADERS("aaiHeaders", "[\"X-TransactionId: 9999\"]"),
49         DELETEONMOUNTPOINTREMOVED("aaiDeleteOnMountpointRemove", false),
50         TRUSTALLCERTS("aaiTrustAllCerts", false, "org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore"),
51         APIVERSION("aaiApiVersion", "aai/v13"),
52         PCKS12CERTFILENAME("aaiPcks12ClientCertFile", "", "org.onap.ccsdk.sli.adaptors.aai.ssl.key"),
53         PCKS12PASSPHRASE("aaiPcks12ClientCertPassphrase", "", "org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd"),
54         CONNECTIONTIMEOUT("aaiClientConnectionTimeout",
55                 String.valueOf(DEFAULT_VALUE_CONNECTION_TIMEOUT), "connection.timeout"), //in ms;
56         APPLICATIONID("aaiApplicationId", "SDNR", "org.onap.ccsdk.sli.adaptors.aai.application"),
57         HTTPREADTIMEOUT("aaiReadTimeout", "60000", "read.timeout");
58         // @formatter:on
59
60         private String propertyKey;
61         private String propertyValue;
62         private Optional<String> propertyKeySecondFile;
63
64         Config(String propertyKey, Object propertyValue) {
65             this.propertyKey = propertyKey;
66             this.propertyValue = propertyValue.toString();
67             this.propertyKeySecondFile = Optional.empty();
68         }
69
70         Config(String propertyKey, Object propertyValue, String propertyKeySecondFile) {
71             this(propertyKey, propertyValue);
72             this.propertyKeySecondFile = Optional.of(propertyKeySecondFile);
73         }
74     }
75
76     private static final long DEFAULT_VALUE_CONNECTION_TIMEOUT = 30000; //in ms
77     private static final String HEADER_KEY_APPLICATION = "X-FromAppId";
78
79     private final ConfigurationFileRepresentation configuration;
80
81     public AaiConfig(ConfigurationFileRepresentation configuration) {
82         HtAssert.nonnull(configuration);
83         this.configuration = configuration;
84         this.configuration.addSection(SECTION_MARKER_AAI);
85         defaults();
86     }
87
88     /*
89      * Getter
90      */
91
92     public boolean doDeleteOnMountPointRemoved() {
93         return configuration.getPropertyBoolean(SECTION_MARKER_AAI, Config.DELETEONMOUNTPOINTREMOVED.propertyKey);
94     }
95
96     public boolean getTrustAll() {
97         return configuration.getPropertyBoolean(SECTION_MARKER_AAI, Config.TRUSTALLCERTS.propertyKey);
98     }
99
100     public String getPcks12CertificateFilename() {
101         return configuration.getProperty(SECTION_MARKER_AAI, Config.PCKS12CERTFILENAME.propertyKey);
102     }
103
104     public String getPcks12CertificatePassphrase() {
105         return configuration.getProperty(SECTION_MARKER_AAI, Config.PCKS12PASSPHRASE.propertyKey);
106     }
107
108     public int getConnectionTimeout() {
109         long res = configuration.getPropertyLong(SECTION_MARKER_AAI, Config.CONNECTIONTIMEOUT.propertyKey)
110                 .orElse(DEFAULT_VALUE_CONNECTION_TIMEOUT);
111         return (int) res;
112     }
113
114     public boolean isOff() {
115         return configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey).equalsIgnoreCase("off");
116     }
117
118     public String getBaseUri() {
119         String res = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey);
120         if (!res.startsWith("/")) {
121             res = "/" + res;
122         }
123         return res;
124     }
125
126     public String getBaseUrl() {
127         if (isOff()) {
128             return "";
129         }
130
131         String url = configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey);
132         if (!url.endsWith("/")) {
133             url += "/";
134         }
135         String apiVersion = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey);
136         if (apiVersion.startsWith("/")) {
137             apiVersion = apiVersion.substring(1);
138         }
139         return url + apiVersion;
140
141     }
142
143     public Map<String, String> getHeaders() {
144
145         Map<String, String> headers =
146                 _parseHeadersMap(configuration.getProperty(SECTION_MARKER_AAI, Config.HEADERS.propertyKey));
147         headers.put(HEADER_KEY_APPLICATION,
148                 configuration.getProperty(SECTION_MARKER_AAI, Config.APPLICATIONID.propertyKey));
149
150         String credentials = configuration.getProperty(SECTION_MARKER_AAI, Config.USERCREDENTIALS.propertyKey);
151         if (!nullorempty(credentials)) {
152             String credentialParts[] = credentials.split(":");
153             if (credentialParts.length == 2) {
154                 // 0:username 1:password
155                 String s = headers.getOrDefault("Authorization", null);
156                 if (nullorempty(s) && !nullorempty(credentialParts[0]) && !nullorempty(credentialParts[1])) {
157                     headers.put("Authorization",
158                             "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes())));
159                 }
160             }
161         }
162         return headers;
163     }
164
165     @Override
166     public String getSectionName() {
167         return SECTION_MARKER_AAI;
168     }
169
170     @Override
171     public void defaults() {
172         for (Config conf : Config.values()) {
173             configuration.setPropertyIfNotAvailable(SECTION_MARKER_AAI, conf.propertyKey, conf.propertyValue);
174         }
175         // If file is available, the content is assigned to related parameters.
176         getAaiPropertiesFile();
177     }
178
179     @Override
180     public String toString() {
181         return "AaiConfig [doDeleteOnMountPointRemoved()=" + doDeleteOnMountPointRemoved() + ", getTrustAll()="
182                 + getTrustAll() + ", getPcks12CertificateFilename()=" + getPcks12CertificateFilename()
183                 + ", getPcks12CertificatePassphrase()=" + getPcks12CertificatePassphrase() + ", getConnectionTimeout()="
184                 + getConnectionTimeout() + ", isOff()=" + isOff() + ", getBaseUri()=" + getBaseUri() + ", getBaseUrl()="
185                 + getBaseUrl() + ", getHeaders()=" + getHeaders() + ", getSectionName()=" + getSectionName() + "]";
186     }
187
188     /*
189      * Private
190      */
191
192     private boolean nullorempty(String s) {
193         return s == null || s.isEmpty();
194     }
195
196     /**
197      * Convert headers to configuration string.
198      *
199      * @param headers
200      * @return
201      */
202     @SuppressWarnings("unused")
203     private static String _printHeadersMap(Map<String, String> headers) {
204         String r = "[";
205         if (headers != null) {
206             int i = 0;
207             for (Entry<String, String> entry : headers.entrySet()) {
208                 if (i > 0) {
209                     r += ",";
210                 }
211                 r += "\"" + entry.getKey() + ":" + entry.getValue() + "\"";
212                 i++;
213             }
214         }
215         r += "]";
216         return r;
217     }
218
219     private static Map<String, String> _parseHeadersMap(String s) {
220
221         LOG.info("Parse: '{}'", s);
222         Map<String, String> r = new HashMap<>();
223         if (s != null) {
224             s = s.trim();
225             if (!s.isEmpty()) {
226                 JSONArray a;
227                 try {
228                     a = new JSONArray(s);
229                     if (a.length() > 0) {
230                         for (int i = 0; i < a.length(); i++) {
231                             String item = a.getString(i);
232                             String[] hlp = item.split(":");
233                             if (hlp.length > 1) {
234                                 r.put(hlp[0], hlp[1]);
235                             }
236                         }
237                     }
238                 } catch (Exception e) {
239                     LOG.debug("Unparsable '{}'", s);
240                 }
241             }
242         }
243         return r;
244     }
245
246     /**
247      * Read file if available and assign to configuration
248      */
249     private void getAaiPropertiesFile() {
250         String aaiPropertiesFileName = configuration.getProperty(SECTION_MARKER_AAI, Config.AAIPROP_FILE.propertyKey);
251         File f = new File(aaiPropertiesFileName);
252         if (f.exists()) {
253             InputStream in = null;
254             try {
255                 in = new FileInputStream(f);
256                 Properties defaultProps = new Properties();
257                 defaultProps.load(in);
258
259                 for (Config conf : Config.values()) {
260                     if (conf.propertyKeySecondFile.isPresent()) {
261                         String config = defaultProps.getProperty(conf.propertyKeySecondFile.get(), conf.propertyValue);
262                         LOG.debug("Property file assign  {} = {} ", conf.propertyKey, config);
263                         configuration.setProperty(SECTION_MARKER_AAI, conf.propertyKey, config);
264                     }
265                 }
266
267             } catch (IOException e) {
268                 LOG.warn("Problem during file read {} {}", f.getAbsoluteFile(), e);
269             } finally {
270                 if (in != null) {
271                     try {
272                         in.close();
273                     } catch (IOException e) {
274                         LOG.warn("problem closing file string for {}: {}", f.getAbsoluteFile(), e);
275                     }
276                 }
277             }
278         }
279     }
280
281 }