VES-mapper - Switch CBS client library to 1.8.6 or higher
[dcaegen2/services/mapper.git] / UniversalVesAdapter / src / main / java / org / onap / universalvesadapter / utils / FetchDynamicConfig.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : DCAE
4  * ================================================================================
5  * Copyright 2019 TechMahindra
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.universalvesadapter.utils;
22
23 import java.io.BufferedReader;
24 import java.io.File;
25 import java.io.FileNotFoundException;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.io.PrintWriter;
30 import java.nio.file.Files;
31 import org.apache.http.HttpResponse;
32 import org.apache.http.client.ClientProtocolException;
33 import org.apache.http.client.HttpClient;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.impl.client.HttpClientBuilder;
36 import org.json.JSONArray;
37 import org.json.JSONObject;
38 import org.json.JSONTokener;
39 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
40 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
41 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
42 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.stereotype.Component;
46 import org.springframework.util.ResourceUtils;
47 import com.fasterxml.jackson.databind.JsonNode;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 @Component
51 public class FetchDynamicConfig {
52
53     // @Value("${defaultProtocol}")
54     static String defaultProtocol = "http";
55
56     private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
57     private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
58
59     private static String url;
60     public static String retString;
61     public static String retCBSString;
62
63     // Generate RequestID and InvocationID which will be used when logging and in
64     // HTTP requests
65     final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
66     final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);
67
68     // Read necessary properties from the environment
69     static final CbsClientConfiguration env = CbsClientConfiguration.fromEnvironment();
70
71     public FetchDynamicConfig() {
72
73     }
74
75     public static void cbsCall(String configFile) {
76
77         Boolean areEqual;
78         // Call consul api and identify the CBS Service address and port
79         getconsul();
80         // Construct and invoke CBS API to get application Configuration
81         getCBS();
82         // Verify if data has changed
83         areEqual = verifyConfigChange(configFile);
84
85         if (!areEqual) {
86             FetchDynamicConfig fc = new FetchDynamicConfig();
87             if (retCBSString != null) {
88                 fc.writefile(retCBSString, configFile);
89             } else {
90                 debugLogger.debug("No content recieved from server");
91             }
92         } else {
93             debugLogger.info("New config pull results identical -  {} NOT refreshed", configFile);
94         }
95     }
96
97     private static void getconsul() {
98         url = defaultProtocol + "://" + env.consulHost() + ":" + env.consulPort() + "/v1/catalog/service/"
99                 + env.cbsName();
100         retString = fetchResultFromDestination(url);
101         debugLogger.info("CBS details fetched from Consul");
102     }
103
104     public static boolean verifyConfigChange(String configFile) {
105
106         boolean areEqual = false;
107         // Read current data
108         try {
109
110             File f = new File(ClassLoader.getSystemResource(configFile.trim()).getFile());
111
112             if (f.exists() && !f.isDirectory()) {
113                 debugLogger.info("Comparing local configuration with the configuration fethed from CBS ");
114
115                 String jsonData = readFile(configFile);
116                 JSONObject jsonObject = new JSONObject(jsonData);
117
118                 ObjectMapper mapper = new ObjectMapper();
119
120                 JsonNode tree1 = mapper.readTree(jsonObject.toString());
121                 JsonNode tree2 = mapper.readTree(retCBSString);
122                 areEqual = tree1.equals(tree2);
123                 debugLogger.info("Comparison value:{}", areEqual);
124             } else {
125                 debugLogger.info("First time config file read: {}",configFile);
126             }
127
128         } catch (IOException e) {
129             errorLogger.error("Comparison with new fetched data failed", e);
130
131         }
132
133         return areEqual;
134
135     }
136
137     public static void getCBS() {
138
139         // consul return as array
140         JSONTokener temp = new JSONTokener(retString);
141         JSONObject cbsjobj = (JSONObject) new JSONArray(temp).get(0);
142
143         String urlPart1 = null;
144         if (cbsjobj.has("ServiceAddress") && cbsjobj.has("ServicePort")) {
145
146             urlPart1 = cbsjobj.getString("ServiceAddress") + ":" + cbsjobj.getInt("ServicePort");
147
148         }
149         debugLogger.info("CONFIG_BINDING_SERVICE HOST:PORT is {}", urlPart1);
150
151         if (env.appName() != null) {
152             url = defaultProtocol + "://" + urlPart1 + "/service_component/" + env.appName();
153             retCBSString = fetchResultFromDestination(url);
154             debugLogger.info("Configuration fetched from CBS successfully..");
155         } else {
156             errorLogger.error("Service name environment variable - APP_NAME/SERVICE_NAME not found within container ");
157         }
158     }
159
160     public void writefile(String retCBSString, String configFile) {
161
162         String indentedretstring = (new JSONObject(retCBSString)).toString(4);
163         try {
164             debugLogger.info("Overwriting local configuration file {} with configuartions received from CBS",
165                     configFile);
166
167             File file2 = ResourceUtils.getFile("classpath:" + configFile);
168             try (FileWriter fstream = new FileWriter(file2, false);
169                     PrintWriter printWriter = new PrintWriter(fstream)) {
170                 printWriter.print(indentedretstring);
171             }
172
173             debugLogger.info("New Config successfully written to local file to {}", configFile);
174         } catch (IOException e) {
175             errorLogger.error(
176                     "Error in writing configuration into local KV file " + configFile + retString, e);
177         }
178     }
179
180     public static String readFile(String configFileName) {
181         String content = null;
182         File file = null;
183
184         try {
185             file = ResourceUtils.getFile("classpath:" + configFileName);
186             content = new String(Files.readAllBytes(file.toPath()));
187         } catch (FileNotFoundException e) {
188             errorLogger.error("colud not find file :{}", configFileName);
189         } catch (IOException e) {
190             errorLogger.error("unable to read the file , reason:", e);
191         } catch (Exception e) {
192             errorLogger.error("Exception occured , reason:", e);
193         }
194
195         return content;
196     }
197
198     private static String fetchResultFromDestination(String url) {
199         debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : START");
200
201         StringBuffer sb = new StringBuffer();
202         try {
203             HttpClient client = HttpClientBuilder.create().build();
204             HttpGet request = new HttpGet(url);
205             HttpResponse response = client.execute(request);
206             BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
207             String line = "";
208             while ((line = rd.readLine()) != null) {
209                 sb.append(line);
210                 sb.append('\n');
211             }
212         } catch (ClientProtocolException e) {
213             debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : ClientProtocolException thrown.", e);
214         } catch (UnsupportedOperationException e) {
215             debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : UnsupportedOperationException thrown.",
216                     e);
217         } catch (IOException e) {
218             debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : IOException thrown.", e);
219         }
220
221         debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : END");
222         return sb.toString();
223     }
224
225 }