2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.universalvesadapter.utils;
23 import java.io.BufferedReader;
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.EnvProperties;
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;
51 public class FetchDynamicConfig {
53 // @Value("${defaultProtocol}")
54 static String defaultProtocol = "http";
56 private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
57 private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
59 private static String url;
60 public static String retString;
61 public static String retCBSString;
63 // Generate RequestID and InvocationID which will be used when logging and in
65 final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
66 final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);
68 // Read necessary properties from the environment
69 static final EnvProperties env = EnvProperties.fromEnvironment();
71 public FetchDynamicConfig() {
75 public static void cbsCall(String configFile) {
78 // Call consul api and identify the CBS Service address and port
80 // Construct and invoke CBS API to get application Configuration
82 // Verify if data has changed
83 areEqual = verifyConfigChange(configFile);
86 FetchDynamicConfig fc = new FetchDynamicConfig();
87 if (retCBSString != null) {
88 fc.writefile(retCBSString, configFile);
90 debugLogger.debug("No content recieved from server");
93 debugLogger.info("New config pull results identical - {} NOT refreshed", configFile);
97 private static void getconsul() {
98 url = defaultProtocol + "://" + env.consulHost() + ":" + env.consulPort() + "/v1/catalog/service/"
100 retString = fetchResultFromDestination(url);
101 debugLogger.info("CBS details fetched from Consul");
104 public static boolean verifyConfigChange(String configFile) {
106 boolean areEqual = false;
110 File f = new File(ClassLoader.getSystemResource(configFile.trim()).getFile());
112 if (f.exists() && !f.isDirectory()) {
113 debugLogger.info("Comparing local configuration with the configuration fethed from CBS ");
115 String jsonData = readFile(configFile);
116 JSONObject jsonObject = new JSONObject(jsonData);
118 ObjectMapper mapper = new ObjectMapper();
120 JsonNode tree1 = mapper.readTree(jsonObject.toString());
121 JsonNode tree2 = mapper.readTree(retCBSString);
122 areEqual = tree1.equals(tree2);
123 debugLogger.info("Comparison value:{}", areEqual);
125 debugLogger.info("First time config file read: {}",configFile);
128 } catch (IOException e) {
129 errorLogger.error("Comparison with new fetched data failed", e);
137 public static void getCBS() {
139 // consul return as array
140 JSONTokener temp = new JSONTokener(retString);
141 JSONObject cbsjobj = (JSONObject) new JSONArray(temp).get(0);
143 String urlPart1 = null;
144 if (cbsjobj.has("ServiceAddress") && cbsjobj.has("ServicePort")) {
146 urlPart1 = cbsjobj.getString("ServiceAddress") + ":" + cbsjobj.getInt("ServicePort");
149 debugLogger.info("CONFIG_BINDING_SERVICE HOST:PORT is {}", urlPart1);
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..");
156 errorLogger.error("Service name environment variable - APP_NAME/SERVICE_NAME not found within container ");
160 public void writefile(String retCBSString, String configFile) {
162 String indentedretstring = (new JSONObject(retCBSString)).toString(4);
164 debugLogger.info("Overwriting local configuration file {} with configuartions received from CBS",
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);
173 debugLogger.info("New Config successfully written to local file to {}", configFile);
174 } catch (IOException e) {
176 "Error in writing configuration into local KV file " + configFile + retString, e);
180 public static String readFile(String configFileName) {
181 String content = null;
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);
198 private static String fetchResultFromDestination(String url) {
199 debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : START");
201 StringBuffer sb = new StringBuffer();
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()));
208 while ((line = rd.readLine()) != null) {
212 } catch (ClientProtocolException e) {
213 debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : ClientProtocolException thrown.", e);
214 } catch (UnsupportedOperationException e) {
215 debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : UnsupportedOperationException thrown.",
217 } catch (IOException e) {
218 debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : IOException thrown.", e);
221 debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : END");
222 return sb.toString();