d30ee9d676f490b5314ccdd055af75224cc79402
[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.util.Base64;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.Properties;
29 import org.json.JSONArray;
30 import org.onap.ccsdk.features.sdnr.wt.common.HtAssert;
31 import org.onap.ccsdk.features.sdnr.wt.common.configuration.Configuration;
32 import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 public class AaiConfig implements Configuration {
37
38     private static Logger LOG = LoggerFactory.getLogger(AaiConfig.class);
39
40     private static final String SECTION_MARKER_AAI = "aai";
41
42     private enum Config {
43         AAIPROP_FILE("aaiPropertiesFile", "null"),
44         BASEURL("aaiUrl", "off", "org.onap.ccsdk.sli.adaptors.aai.uri"),
45         USERCREDENTIALS("aaiUserCredentials",""),
46         HEADERS("aaiHeaders","[\"X-TransactionId: 9999\"]"),
47         DELETEONMOUNTPOINTREMOVED("aaiDeleteOnMountpointRemove",false),
48         TRUSTALLCERTS("aaiTrustAllCerts",false, "org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore"),
49         APIVERSION("aaiApiVersion", "aai/v13"),
50         PCKS12CERTFILENAME("aaiPcks12ClientCertFile","", "org.onap.ccsdk.sli.adaptors.aai.ssl.key"),
51         PCKS12PASSPHRASE("aaiPcks12ClientCertPassphrase","", "org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd"),
52         CONNECTIONTIMEOUT("aaiClientConnectionTimeout",String.valueOf(DEFAULT_VALUE_CONNECTION_TIMEOUT), "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.PCKS12PASSPHRASE.propertyKey).orElse(DEFAULT_VALUE_CONNECTION_TIMEOUT);
106         return (int)res;
107     }
108
109     public boolean isOff() {
110         return configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey).equalsIgnoreCase("off");
111     }
112
113     public String getBaseUri() {
114         String res = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey);
115         if (!res.startsWith("/")) {
116             res = "/" + res;
117         }
118         return res;
119     }
120
121     public String getBaseUrl() {
122         if (isOff()) {
123             return "";
124         } else {
125             String url = configuration.getProperty(SECTION_MARKER_AAI, Config.BASEURL.propertyKey);
126             if (!url.endsWith("/")) {
127                 url += "/";
128             }
129             String apiVersion = configuration.getProperty(SECTION_MARKER_AAI, Config.APIVERSION.propertyKey);
130             if (apiVersion.startsWith("/")) {
131                 apiVersion = apiVersion.substring(1);
132             }
133             return url + apiVersion;
134         }
135     }
136
137     public Map<String, String> getHeaders() {
138
139         Map<String,String> headers = _parseHeadersMap(configuration.getProperty(SECTION_MARKER_AAI, Config.HEADERS.propertyKey));
140         headers.put(HEADER_KEY_APPLICATION, configuration.getProperty(SECTION_MARKER_AAI, Config.APPLICATIONID.propertyKey));
141
142         String credentials = configuration.getProperty(SECTION_MARKER_AAI, Config.USERCREDENTIALS.propertyKey);
143         if (!nullorempty(credentials)) {
144             String credentialParts[] = credentials.split(":");
145             if (credentialParts.length == 2) {
146                 // 0:username 1:password
147                 String s = headers.getOrDefault("Authorization", null);
148                 if (nullorempty(s) && !nullorempty(credentialParts[0]) && !nullorempty(credentialParts[1])) {
149                     headers.put("Authorization",
150                             "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes())));
151                 }
152             }
153         }
154         return headers;
155     }
156
157     @Override
158     public String getSectionName() {
159         return SECTION_MARKER_AAI;
160     }
161
162     @Override
163     public void defaults() {
164         for (Config conf : Config.values()) {
165             configuration.setPropertyIfNotAvailable(SECTION_MARKER_AAI, conf.propertyKey, conf.propertyValue);
166            }
167         // If file is available, the content is assigned to related parameters.
168         getAaiPropertiesFile();
169     }
170
171     @Override
172     public String toString() {
173         return "AaiConfig [doDeleteOnMountPointRemoved()=" + doDeleteOnMountPointRemoved() + ", getTrustAll()="
174                 + getTrustAll() + ", getPcks12CertificateFilename()=" + getPcks12CertificateFilename()
175                 + ", getPcks12CertificatePassphrase()=" + getPcks12CertificatePassphrase() + ", getConnectionTimeout()="
176                 + getConnectionTimeout() + ", isOff()=" + isOff() + ", getBaseUri()=" + getBaseUri() + ", getBaseUrl()="
177                 + getBaseUrl() + ", getHeaders()=" + getHeaders() + ", getSectionName()=" + getSectionName() + "]";
178     }
179
180     /*
181      * Private
182      */
183
184     private boolean nullorempty(String s) {
185         return s == null || s.isEmpty();
186     }
187
188     /**
189      * Convert headers to configuration string.
190      * @param headers
191      * @return
192      */
193     @SuppressWarnings("unused")
194     private static String _printHeadersMap(Map<String, String> headers) {
195         String r = "[";
196         if (headers != null) {
197             int i = 0;
198             for (Entry<String, String> entry : headers.entrySet()) {
199                 if (i > 0) {
200                     r += ",";
201                 }
202                 r += "\"" + entry.getKey() + ":" + entry.getValue() + "\"";
203                 i++;
204             }
205         }
206         r += "]";
207         return r;
208     }
209
210     private static Map<String, String> _parseHeadersMap(String s) {
211
212         LOG.info("Parse: '{}'",s);
213         Map<String, String> r = new HashMap<>();
214         if (s != null) {
215             s = s.trim();
216             if (!s.isEmpty()) {
217                 JSONArray a;
218                 try {
219                     a = new JSONArray(s);
220                     if (a.length() > 0) {
221                         for (int i = 0; i < a.length(); i++) {
222                             String item = a.getString(i);
223                             String[] hlp = item.split(":");
224                             if (hlp.length > 1) {
225                                 r.put(hlp[0], hlp[1]);
226                             }
227                         }
228                     }
229                 } catch (Exception e) {
230                     LOG.debug("Unparsable '{}'", s);
231                 }
232             }
233         }
234         return r;
235     }
236
237     /**
238      * Read file if available and assign to configuration
239      */
240     private void getAaiPropertiesFile() {
241         String aaiPropertiesFileName = configuration.getProperty(SECTION_MARKER_AAI, Config.AAIPROP_FILE.propertyKey);
242         File f = new File(aaiPropertiesFileName);
243         if (f.exists()) {
244             try {
245                 FileInputStream in = new FileInputStream(f);
246                 Properties defaultProps = new Properties();
247                 defaultProps.load(in);
248
249                 for (Config conf : Config.values()) {
250                     if (conf.propertyKeySecondFile.isPresent()) {
251                         String config = defaultProps.getProperty("org.onap.ccsdk.sli.adaptors.aai.ssl.key", conf.propertyValue);
252                         LOG.debug("Property file assign  {} = {} ",conf.propertyKey, config );
253                         configuration.setPropertyIfNotAvailable(
254                                 SECTION_MARKER_AAI,
255                                 conf.propertyKey,
256                                 config);
257                     }
258                 }
259
260                 in.close();
261             } catch (IOException e) {
262                 LOG.warn("Problem during file read {} {}", f.getAbsoluteFile(), e);
263             }
264         }
265     }
266
267 }