2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright 2018-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.service;
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStreamReader;
26 import java.time.Duration;
27 import java.util.HashMap;
29 import java.util.Map.Entry;
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.simple.JSONArray;
37 import org.json.simple.JSONObject;
38 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
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.onap.universalvesadapter.utils.CollectorConfigPropertyRetrieval;
44 import org.onap.universalvesadapter.utils.FetchDynamicConfig;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.boot.CommandLineRunner;
50 import org.springframework.boot.SpringApplication;
51 import org.springframework.context.ApplicationContext;
52 import org.springframework.core.Ordered;
53 import org.springframework.stereotype.Component;
57 public class VESAdapterInitializer implements CommandLineRunner, Ordered {
58 private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
59 private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
61 @Value("${defaultConfigFilelocation}")
62 String defaultConfigFilelocation;
63 @Value("${server.port}")
66 private static Map<String, String> mappingFiles = new HashMap<String, String>();
68 // Generate RequestID and InvocationID which will be used when logging and in
70 final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
71 final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);
73 // Read necessary properties from the environment
74 final EnvProperties env = EnvProperties.fromEnvironment();
76 // Polling properties :
77 final Duration initialDelay = Duration.ofSeconds(5);
78 final Duration period = Duration.ofMinutes(1);
81 private ApplicationContext applicationContext;
84 public void run(String... args) throws Exception {
85 debugLogger.info("The Default Config file Location:" + defaultConfigFilelocation.trim());
87 if (ClassLoader.getSystemResource(defaultConfigFilelocation.trim()) == null) {
88 errorLogger.error("Default Config file " + defaultConfigFilelocation.trim() + " is missing");
89 System.exit(SpringApplication.exit(applicationContext, () -> {
90 errorLogger.error("Application stoped due to missing default Config file");
95 // Create the client and use it to get the configuration
96 CbsClientFactory.createCbsClient(env).flatMapMany(cbsClient -> cbsClient.updates(request, initialDelay, period))
97 .subscribe(jsonObject -> {
99 // If env details not fetched static configuration file will be used
100 if (env.consulHost() != null && env.cbsName() != null && env.appName() != null) {
101 debugLogger.info(">>>Dynamic configuration to be used");
102 FetchDynamicConfig.cbsCall(defaultConfigFilelocation);
105 readJsonToMap(defaultConfigFilelocation);
107 debugLogger.info("Triggering controller's start url ");
108 fetchResultFromDestination("http://localhost:" + serverPort + "/start");
111 debugLogger.warn("Cannot Connect", throwable);
117 * gets the configuration details from JSON an puts those in the mapping data structure for further
120 * @param configFile: String
122 private void readJsonToMap(String configFile) {
124 JSONArray collectorArray = CollectorConfigPropertyRetrieval.collectorConfigArray(configFile);
126 for (int i = 0; i < collectorArray.size(); i++) {
127 JSONObject obj2 = (JSONObject) collectorArray.get(i);
129 if (obj2.containsKey("mapping-files")) {
131 JSONArray a1 = (JSONArray) obj2.get("mapping-files");
133 for (int j = 0; j < a1.size(); j++) {
134 JSONObject obj3 = (JSONObject) a1.get(j);
135 Set<Entry<String, String>> set = obj3.entrySet();
137 for (Entry<String, String> entry : set) {
139 mappingFiles.put(entry.getKey(), entry.getValue());
146 } catch (Exception e) {
147 // e.printStackTrace();
149 " Class VESAdapterInitializer: method readJsonToMap: Exception occured while reading Collector config file cause: ",
154 public static Map<String, String> getMappingFiles() {
158 public static void setMappingFiles(Map<String, String> mappingFiles) {
159 VESAdapterInitializer.mappingFiles = mappingFiles;
163 public int getOrder() {
167 private static String fetchResultFromDestination(String url) {
168 debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: START");
170 StringBuffer sb = new StringBuffer();
172 HttpClient client = HttpClientBuilder.create().build();
173 HttpGet request = new HttpGet(url);
174 HttpResponse response = client.execute(request);
175 BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
177 while ((line = rd.readLine()) != null) {
181 } catch (ClientProtocolException e) {
182 debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: ClientProtocolException thrown "
184 } catch (UnsupportedOperationException e) {
186 .debug("VESAdapterInitializer:: fetchResultFromDestination :: UnsupportedOperationException thrown "
188 } catch (IOException e) {
190 "VESAdapterInitializer:: fetchResultFromDestination :: IOException thrown " + e.getMessage());
192 debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: END");
193 return sb.toString();