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