VES-mapper - Switch CBS client library to 1.8.6 or higher
[dcaegen2/services/mapper.git] / UniversalVesAdapter / src / main / java / org / onap / universalvesadapter / service / VESAdapterInitializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : DCAE
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
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.service;
22
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;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Set;
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.CbsClientConfiguration;
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;
54
55 // AdapterInitializer
56 @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");
60
61     @Value("${defaultConfigFilelocation}")
62     String defaultConfigFilelocation;
63     @Value("${server.port}")
64     String serverPort;
65
66     private static Map<String, String> mappingFiles = new HashMap<String, String>();
67
68     // Generate RequestID and InvocationID which will be used when logging and in
69     // HTTP requests
70     final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
71     final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);
72
73     // Read necessary properties from the environment
74     final CbsClientConfiguration env = CbsClientConfiguration.fromEnvironment();
75
76     // Polling properties :
77     final Duration initialDelay = Duration.ofSeconds(5);
78     final Duration period = Duration.ofMinutes(1);
79
80     @Autowired
81     private ApplicationContext applicationContext;
82
83     @Override
84     public void run(String... args) throws Exception {
85         debugLogger.info("The Default Config file Location:" + defaultConfigFilelocation.trim());
86
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");
91                 return -1;
92             }));
93         }
94
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 -> {
98
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);
103             }
104
105             readJsonToMap(defaultConfigFilelocation);
106
107             debugLogger.info("Triggering controller's start url ");
108             fetchResultFromDestination("http://localhost:" + serverPort + "/start");
109
110         }, throwable -> {
111             debugLogger.warn("Cannot Connect", throwable);
112         });
113
114     }
115
116     /**
117      * gets the configuration details from JSON an puts those in the mapping data structure for further
118      * processing.
119      *
120      * @param configFile: String
121      */
122     private void readJsonToMap(String configFile) {
123         try {
124             JSONArray collectorArray = CollectorConfigPropertyRetrieval.collectorConfigArray(configFile);
125
126             for (int i = 0; i < collectorArray.size(); i++) {
127                 JSONObject obj2 = (JSONObject) collectorArray.get(i);
128
129                 if (obj2.containsKey("mapping-files")) {
130
131                     JSONArray a1 = (JSONArray) obj2.get("mapping-files");
132
133                     for (int j = 0; j < a1.size(); j++) {
134                         JSONObject obj3 = (JSONObject) a1.get(j);
135                         Set<Entry<String, String>> set = obj3.entrySet();
136
137                         for (Entry<String, String> entry : set) {
138
139                             mappingFiles.put(entry.getKey(), entry.getValue());
140                         }
141                     }
142
143                 }
144             }
145
146         } catch (Exception e) {
147             // e.printStackTrace();
148             errorLogger.error(
149                     " Class VESAdapterInitializer: method readJsonToMap: Exception occured while reading Collector config file cause: ",
150                     e.getCause());
151         }
152     }
153
154     public static Map<String, String> getMappingFiles() {
155         return mappingFiles;
156     }
157
158     public static void setMappingFiles(Map<String, String> mappingFiles) {
159         VESAdapterInitializer.mappingFiles = mappingFiles;
160     }
161
162     @Override
163     public int getOrder() {
164         return 0;
165     }
166
167     private static String fetchResultFromDestination(String url) {
168         debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: START");
169         String line = "";
170         StringBuffer sb = new StringBuffer();
171         try {
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()));
176
177             while ((line = rd.readLine()) != null) {
178                 sb.append(line);
179                 sb.append('\n');
180             }
181         } catch (ClientProtocolException e) {
182             debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: ClientProtocolException thrown "
183                     + e.getMessage());
184         } catch (UnsupportedOperationException e) {
185             debugLogger
186             .debug("VESAdapterInitializer:: fetchResultFromDestination :: UnsupportedOperationException thrown "
187                     + e.getMessage());
188         } catch (IOException e) {
189             debugLogger.debug(
190                     "VESAdapterInitializer:: fetchResultFromDestination :: IOException thrown " + e.getMessage());
191         }
192         debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: END");
193         return sb.toString();
194     }
195
196 }