Fix sonar issues in UniversalVesAdapter
[dcaegen2/services/mapper.git] / UniversalVesAdapter / src / main / java / org / onap / universalvesadapter / service / VESAdapterInitializer.java
index e7e4705..85c5f42 100644 (file)
-/*-\r
- * ============LICENSE_START=======================================================\r
- * ONAP : DCAE\r
- * ================================================================================\r
- * Copyright 2018-2019 TechMahindra\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *      http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.universalvesadapter.service;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.IOException;\r
-import java.io.InputStreamReader;\r
-import java.time.Duration;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-import java.util.Map.Entry;\r
-import java.util.Set;\r
-\r
-import org.apache.http.HttpResponse;\r
-import org.apache.http.client.ClientProtocolException;\r
-import org.apache.http.client.HttpClient;\r
-import org.apache.http.client.methods.HttpGet;\r
-import org.apache.http.impl.client.HttpClientBuilder;\r
-import org.json.simple.JSONArray;\r
-import org.json.simple.JSONObject;\r
-import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;\r
-import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;\r
-import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;\r
-import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;\r
-import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;\r
-import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrival;\r
-import org.onap.universalvesadapter.utils.FetchDynamicConfig;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.beans.factory.annotation.Value;\r
-import org.springframework.boot.CommandLineRunner;\r
-import org.springframework.boot.SpringApplication;\r
-import org.springframework.context.ApplicationContext;\r
-import org.springframework.core.Ordered;\r
-import org.springframework.stereotype.Component;\r
-\r
-// AdapterInitializer\r
-@Component\r
-public class VESAdapterInitializer implements CommandLineRunner, Ordered {\r
-       private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");\r
-       private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
-\r
-       @Value("${defaultConfigFilelocation}")\r
-       String defaultConfigFilelocation;\r
-       @Value("${server.port}")\r
-       String serverPort;\r
-\r
-       private static Map<String, String> mappingFiles = new HashMap<String, String>();\r
-\r
-       // Generate RequestID and InvocationID which will be used when logging and in\r
-       // HTTP requests\r
-       final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();\r
-       final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);\r
-\r
-       // Read necessary properties from the environment\r
-       final EnvProperties env = EnvProperties.fromEnvironment();\r
-\r
-       // Polling properties :\r
-       final Duration initialDelay = Duration.ofSeconds(5);\r
-       final Duration period = Duration.ofMinutes(1);\r
-\r
-       @Autowired\r
-       private ApplicationContext applicationContext;\r
-\r
-       @Override\r
-       public void run(String... args) throws Exception {\r
-               debugLogger.info("The Default Config file Location:" + defaultConfigFilelocation.trim());\r
-\r
-               if (ClassLoader.getSystemResource(defaultConfigFilelocation.trim()) == null) {\r
-                       errorLogger.error("Default Config file " + defaultConfigFilelocation.trim() + " is missing");\r
-                       System.exit(SpringApplication.exit(applicationContext, () -> {\r
-                               errorLogger.error("Application stoped due to missing default Config file");\r
-                               return -1;\r
-                       }));\r
-               }\r
-\r
-               // Create the client and use it to get the configuration\r
-               CbsClientFactory.createCbsClient(env).flatMapMany(cbsClient -> cbsClient.updates(request, initialDelay, period))\r
-                               .subscribe(jsonObject -> {\r
-\r
-                                       // If env details not fetched static configuration file will be used\r
-                                       if (env.consulHost() != null && env.cbsName() != null && env.appName() != null) {\r
-                                               debugLogger.info(">>>Dynamic configuration to be used");\r
-                                               FetchDynamicConfig.cbsCall(defaultConfigFilelocation);\r
-                                       }\r
-\r
-                                       readJsonToMap(defaultConfigFilelocation);\r
-\r
-                                       debugLogger.info("Triggering controller's start url ");\r
-                                       fetchResultFromDestination("http://localhost:" + serverPort + "/start");\r
-\r
-                               }, throwable -> {\r
-                                       debugLogger.warn("Cannot Connect", throwable);\r
-                               });\r
-\r
-       }\r
-\r
-       /**\r
-        * gets the configuration details from JSON an puts those in the mapping data\r
-        * structure for further processing.\r
-        * \r
-        * @param configFile: String\r
-        */\r
-       private void readJsonToMap(String configFile) {\r
-               try {\r
-                       JSONArray collectorArray = CollectorConfigPropertyRetrival.collectorConfigArray(configFile);\r
-\r
-                       for (int i = 0; i < collectorArray.size(); i++) {\r
-                               JSONObject obj2 = (JSONObject) collectorArray.get(i);\r
-\r
-                               if (obj2.containsKey("mapping-files")) {\r
-\r
-                                       JSONArray a1 = (JSONArray) obj2.get("mapping-files");\r
-\r
-                                       for (int j = 0; j < a1.size(); j++) {\r
-                                               JSONObject obj3 = (JSONObject) a1.get(j);\r
-                                               Set<Entry<String, String>> set = obj3.entrySet();\r
-\r
-                                               for (Entry<String, String> entry : set) {\r
-\r
-                                                       mappingFiles.put(entry.getKey(), entry.getValue());\r
-                                               }\r
-                                       }\r
-\r
-                               }\r
-                       }\r
-\r
-               } catch (Exception e) {\r
-                       // e.printStackTrace();\r
-                       errorLogger.error(\r
-                                       " Class VESAdapterInitializer: method readJsonToMap: Exception occured while reading Collector config file cause: ",\r
-                                       e.getCause());\r
-               }\r
-       }\r
-\r
-       public static Map<String, String> getMappingFiles() {\r
-               return mappingFiles;\r
-       }\r
-\r
-       public static void setMappingFiles(Map<String, String> mappingFiles) {\r
-               VESAdapterInitializer.mappingFiles = mappingFiles;\r
-       }\r
-\r
-       @Override\r
-       public int getOrder() {\r
-               return 0;\r
-       }\r
-\r
-       private static String fetchResultFromDestination(String url) {\r
-               debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: START");\r
-               String line = "";\r
-               StringBuffer sb = new StringBuffer();\r
-               try {\r
-                       HttpClient client = HttpClientBuilder.create().build();\r
-                       HttpGet request = new HttpGet(url);\r
-                       HttpResponse response = client.execute(request);\r
-                       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));\r
-\r
-                       while ((line = rd.readLine()) != null) {\r
-                               sb.append(line);\r
-                               sb.append('\n');\r
-                       }\r
-               } catch (ClientProtocolException e) {\r
-                       debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: ClientProtocolException thrown "\r
-                                       + e.getMessage());\r
-               } catch (UnsupportedOperationException e) {\r
-                       debugLogger\r
-                                       .debug("VESAdapterInitializer:: fetchResultFromDestination :: UnsupportedOperationException thrown "\r
-                                                       + e.getMessage());\r
-               } catch (IOException e) {\r
-                       debugLogger.debug(\r
-                                       "VESAdapterInitializer:: fetchResultFromDestination :: IOException thrown " + e.getMessage());\r
-               }\r
-               debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: END");\r
-               return sb.toString();\r
-       }\r
-\r
-}\r
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : DCAE
+ * ================================================================================
+ * Copyright 2018-2019 TechMahindra
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.universalvesadapter.service;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
+import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
+import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrieval;
+import org.onap.universalvesadapter.utils.FetchDynamicConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ApplicationContext;
+import org.springframework.core.Ordered;
+import org.springframework.stereotype.Component;
+
+// AdapterInitializer
+@Component
+public class VESAdapterInitializer implements CommandLineRunner, Ordered {
+    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
+    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
+
+    @Value("${defaultConfigFilelocation}")
+    String defaultConfigFilelocation;
+    @Value("${server.port}")
+    String serverPort;
+
+    private static Map<String, String> mappingFiles = new HashMap<String, String>();
+
+    // Generate RequestID and InvocationID which will be used when logging and in
+    // HTTP requests
+    final RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create();
+    final CbsRequest request = CbsRequests.getConfiguration(diagnosticContext);
+
+    // Read necessary properties from the environment
+    final EnvProperties env = EnvProperties.fromEnvironment();
+
+    // Polling properties :
+    final Duration initialDelay = Duration.ofSeconds(5);
+    final Duration period = Duration.ofMinutes(1);
+
+    @Autowired
+    private ApplicationContext applicationContext;
+
+    @Override
+    public void run(String... args) throws Exception {
+        debugLogger.info("The Default Config file Location:" + defaultConfigFilelocation.trim());
+
+        if (ClassLoader.getSystemResource(defaultConfigFilelocation.trim()) == null) {
+            errorLogger.error("Default Config file " + defaultConfigFilelocation.trim() + " is missing");
+            System.exit(SpringApplication.exit(applicationContext, () -> {
+                errorLogger.error("Application stoped due to missing default Config file");
+                return -1;
+            }));
+        }
+
+        // Create the client and use it to get the configuration
+        CbsClientFactory.createCbsClient(env).flatMapMany(cbsClient -> cbsClient.updates(request, initialDelay, period))
+        .subscribe(jsonObject -> {
+
+            // If env details not fetched static configuration file will be used
+            if (env.consulHost() != null && env.cbsName() != null && env.appName() != null) {
+                debugLogger.info(">>>Dynamic configuration to be used");
+                FetchDynamicConfig.cbsCall(defaultConfigFilelocation);
+            }
+
+            readJsonToMap(defaultConfigFilelocation);
+
+            debugLogger.info("Triggering controller's start url ");
+            fetchResultFromDestination("http://localhost:" + serverPort + "/start");
+
+        }, throwable -> {
+            debugLogger.warn("Cannot Connect", throwable);
+        });
+
+    }
+
+    /**
+     * gets the configuration details from JSON an puts those in the mapping data structure for further
+     * processing.
+     *
+     * @param configFile: String
+     */
+    private void readJsonToMap(String configFile) {
+        try {
+            JSONArray collectorArray = CollectorConfigPropertyRetrieval.collectorConfigArray(configFile);
+
+            for (int i = 0; i < collectorArray.size(); i++) {
+                JSONObject obj2 = (JSONObject) collectorArray.get(i);
+
+                if (obj2.containsKey("mapping-files")) {
+
+                    JSONArray a1 = (JSONArray) obj2.get("mapping-files");
+
+                    for (int j = 0; j < a1.size(); j++) {
+                        JSONObject obj3 = (JSONObject) a1.get(j);
+                        Set<Entry<String, String>> set = obj3.entrySet();
+
+                        for (Entry<String, String> entry : set) {
+
+                            mappingFiles.put(entry.getKey(), entry.getValue());
+                        }
+                    }
+
+                }
+            }
+
+        } catch (Exception e) {
+            // e.printStackTrace();
+            errorLogger.error(
+                    " Class VESAdapterInitializer: method readJsonToMap: Exception occured while reading Collector config file cause: ",
+                    e.getCause());
+        }
+    }
+
+    public static Map<String, String> getMappingFiles() {
+        return mappingFiles;
+    }
+
+    public static void setMappingFiles(Map<String, String> mappingFiles) {
+        VESAdapterInitializer.mappingFiles = mappingFiles;
+    }
+
+    @Override
+    public int getOrder() {
+        return 0;
+    }
+
+    private static String fetchResultFromDestination(String url) {
+        debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: START");
+        String line = "";
+        StringBuffer sb = new StringBuffer();
+        try {
+            HttpClient client = HttpClientBuilder.create().build();
+            HttpGet request = new HttpGet(url);
+            HttpResponse response = client.execute(request);
+            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
+
+            while ((line = rd.readLine()) != null) {
+                sb.append(line);
+                sb.append('\n');
+            }
+        } catch (ClientProtocolException e) {
+            debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: ClientProtocolException thrown "
+                    + e.getMessage());
+        } catch (UnsupportedOperationException e) {
+            debugLogger
+            .debug("VESAdapterInitializer:: fetchResultFromDestination :: UnsupportedOperationException thrown "
+                    + e.getMessage());
+        } catch (IOException e) {
+            debugLogger.debug(
+                    "VESAdapterInitializer:: fetchResultFromDestination :: IOException thrown " + e.getMessage());
+        }
+        debugLogger.debug("VESAdapterInitializer:: fetchResultFromDestination :: END");
+        return sb.toString();
+    }
+
+}