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