Cloudify blueprint for VES mapper
[dcaegen2/services/mapper.git] / UniversalVesAdapter / src / main / java / org / onap / universalvesadapter / utils / FetchDynamicConfig.java
index af219ce..4bc66bb 100644 (file)
-/*
-* ============LICENSE_START=======================================================
-* ONAP : DCAE
-* ================================================================================
-* Copyright 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.utils;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.Map;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Component
-public class FetchDynamicConfig {
-
-       private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
-       private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
-
-       private static String url;
-       public static String retString;
-       public static String retCBSString;
-       private static Map<String, String> env;
-
-       public FetchDynamicConfig() {
-       }
-
-       public static void cbsCall(String configFile) {
-
-               env = System.getenv();
-               Boolean areEqual;
-               // Call consul api and identify the CBS Service address and port
-               getconsul();
-               // Construct and invoke CBS API to get application Configuration
-               getCBS();
-               // Verify if data has changed
-               areEqual = verifyConfigChange(configFile);
-
-               if (!areEqual) {
-                       FetchDynamicConfig fc = new FetchDynamicConfig();
-                       fc.writefile(retCBSString,configFile);
-               } else {
-                       debugLogger.info("New config pull results identical -  " + configFile + " NOT refreshed");
-               }
-       }
-
-       
-       private static void getconsul() {
-               url = env.get("CONSUL_HOST") + ":8500/v1/catalog/service/" + env.get("CONFIG_BINDING_SERVICE");
-               retString = executecurl(url);
-               debugLogger.info("CBS details fetched from Consul");
-       }
-
-       public static boolean verifyConfigChange(String configFile) {
-
-               boolean areEqual = false;
-               // Read current data
-               try {
-                       File f = new File(configFile);
-                       if (f.exists() && !f.isDirectory()) {
-
-                               String jsonData = readFile(configFile);
-                               JSONObject jsonObject = new JSONObject(jsonData);
-
-                               ObjectMapper mapper = new ObjectMapper();
-
-                               JsonNode tree1 = mapper.readTree(jsonObject.toString());
-                               JsonNode tree2 = mapper.readTree(retCBSString);
-                               areEqual = tree1.equals(tree2);
-                               debugLogger.info("Comparison value:" + areEqual);
-                       } else {
-                               debugLogger.info("First time config file read: " + configFile);
-                       }
-
-               } catch (IOException e) {
-                       errorLogger.error("Comparison with new fetched data failed" + e.getMessage());
-
-               }
-
-               return areEqual;
-
-       }
-
-       public static void getCBS() {
-
-               // consul return as array
-               JSONTokener temp = new JSONTokener(retString);
-               JSONObject cbsjobj = (JSONObject) new JSONArray(temp).get(0);
-
-               String urlPart1 = null;
-               if (cbsjobj.has("ServiceAddress") && cbsjobj.has("ServicePort")) {
-
-                       urlPart1 = cbsjobj.getString("ServiceAddress") + ":" + cbsjobj.getInt("ServicePort");
-                       
-               }
-               debugLogger.info("CONFIG_BINDING_SERVICE DNS RESOLVED:" + urlPart1);
-               
-               if (env.containsKey("HOSTNAME")) {
-                       url = urlPart1 + "/service_component/" + env.get("HOSTNAME");
-                       retCBSString = executecurl(url);
-               } else if (env.containsKey("SERVICE_NAME")) {
-                       url = urlPart1 + "/service_component/" + env.get("SERVICE_NAME");
-                       retCBSString = executecurl(url);
-               } else {
-                       errorLogger.error("Service name environment variable - HOSTNAME/SERVICE_NAME not found within container ");
-               }
-
-       }
-
-       public void writefile(String retCBSString, String configFile) {
-               debugLogger.info("URL to fetch configuration:" + url);
-
-               String indentedretstring = (new JSONObject(retCBSString)).toString(4);
-
-               try (FileWriter file = new FileWriter(configFile)) {
-                       file.write(indentedretstring);
-
-                       debugLogger.info("Successfully Copied JSON Object to file " + configFile);
-               } catch (IOException e) {
-                       errorLogger.error("Error in writing configuration into file " + configFile + retString + e.getMessage());
-                       e.printStackTrace();
-               }
-
-       }
-
-       public static String readFile(String filename) {
-               String result = "";
-               try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
-                       StringBuilder sb = new StringBuilder();
-                       String line = br.readLine();
-                       while (line != null) {
-                               sb.append(line);
-                               line = br.readLine();
-                       }
-                       result = sb.toString();
-               } catch (FileNotFoundException e) {
-                       errorLogger.error("colud not find file :",filename);
-                       
-               } catch (Exception e) {
-                       errorLogger.error("unable to read the file , reason:",e.getCause());
-               } 
-               return result;
-       }
-       private static String executecurl(String url) {
-
-               String[] command = { "curl", "-v", url };
-               ProcessBuilder process = new ProcessBuilder(command);
-               Process p;
-               String result = null;
-               try {
-                       p = process.start();
-                       InputStreamReader ipr = new InputStreamReader(p.getInputStream());
-                       BufferedReader reader = new BufferedReader(ipr);
-                       StringBuilder builder = new StringBuilder();
-                       String line;
-
-                       while ((line = reader.readLine()) != null) {
-                               builder.append(line);
-                       }
-                       result = builder.toString();
-                       reader.close();
-                       ipr.close();
-               } catch (IOException e) {
-                       errorLogger.error("error", e);
-                       e.printStackTrace();
-               }
-               return result;
-
-       }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * ONAP : DCAE\r
+ * ================================================================================\r
+ * Copyright 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.utils;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileWriter;\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+import java.io.PrintWriter;\r
+import java.nio.file.Files;\r
+import java.util.Map;\r
+\r
+import org.json.JSONArray;\r
+import org.json.JSONObject;\r
+import org.json.JSONTokener;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+import org.springframework.stereotype.Component;\r
+import org.springframework.util.ResourceUtils;\r
+\r
+import com.fasterxml.jackson.databind.JsonNode;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
+\r
+@Component\r
+public class FetchDynamicConfig {\r
+        \r
+        private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");\r
+        private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
+        \r
+        private static String url;\r
+        public static String retString;\r
+        public static String retCBSString;\r
+        private static Map<String, String> env;\r
+        \r
+        public FetchDynamicConfig() {}\r
+        \r
+        public static void cbsCall(String configFile) {\r
+                \r
+                env = System.getenv();\r
+                Boolean areEqual;\r
+                // Call consul api and identify the CBS Service address and port\r
+                getconsul();\r
+                // Construct and invoke CBS API to get application Configuration\r
+                getCBS();\r
+                // Verify if data has changed\r
+                areEqual = verifyConfigChange(configFile);\r
+                \r
+                if (!areEqual) {\r
+                        FetchDynamicConfig fc = new FetchDynamicConfig();\r
+                        fc.writefile(retCBSString, configFile);\r
+                } else {\r
+                        debugLogger.info("New config pull results identical -  " + configFile\r
+                                        + " NOT refreshed");\r
+                }\r
+        }\r
+        \r
+        \r
+        private static void getconsul() {\r
+                url = env.get("CONSUL_HOST") + ":8500/v1/catalog/service/"\r
+                                + env.get("CONFIG_BINDING_SERVICE");\r
+                retString = executecurl(url);\r
+                debugLogger.info("CBS details fetched from Consul");\r
+        }\r
+        \r
+        public static boolean verifyConfigChange(String configFile) {\r
+                \r
+                boolean areEqual = false;\r
+                // Read current data\r
+                try {\r
+                        \r
+                        File f = new File(\r
+                                        ClassLoader.getSystemResource(configFile.trim()).getFile());\r
+                        \r
+                        if (f.exists() && !f.isDirectory()) {\r
+                                debugLogger.info(\r
+                                                "Comparing local configuration with the configuration fethed from CBS ");\r
+                                \r
+                                String jsonData = readFile(configFile);\r
+                                JSONObject jsonObject = new JSONObject(jsonData);\r
+                                \r
+                                ObjectMapper mapper = new ObjectMapper();\r
+                                \r
+                                JsonNode tree1 = mapper.readTree(jsonObject.toString());\r
+                                JsonNode tree2 = mapper.readTree(retCBSString);\r
+                                areEqual = tree1.equals(tree2);\r
+                                debugLogger.info("Comparison value:" + areEqual);\r
+                        } else {\r
+                                debugLogger.info("First time config file read: " + configFile);\r
+                        }\r
+                        \r
+                } catch (IOException e) {\r
+                        errorLogger.error(\r
+                                        "Comparison with new fetched data failed" + e.getMessage());\r
+                        \r
+                }\r
+                \r
+                return areEqual;\r
+                \r
+        }\r
+        \r
+        public static void getCBS() {\r
+                \r
+                // consul return as array\r
+                JSONTokener temp = new JSONTokener(retString);\r
+                JSONObject cbsjobj = (JSONObject) new JSONArray(temp).get(0);\r
+                \r
+                String urlPart1 = null;\r
+                if (cbsjobj.has("ServiceAddress") && cbsjobj.has("ServicePort")) {\r
+                        \r
+                        urlPart1 = cbsjobj.getString("ServiceAddress") + ":"\r
+                                        + cbsjobj.getInt("ServicePort");\r
+                        \r
+                }\r
+                debugLogger.info("CONFIG_BINDING_SERVICE HOST:PORT is " + urlPart1);\r
+                \r
+                if (env.containsKey("HOSTNAME")) {\r
+                        url = urlPart1 + "/service_component/" + env.get("HOSTNAME");\r
+                        retCBSString = executecurl(url);\r
+                        debugLogger.info("Configuration fetched from CBS successfully..");\r
+                } else if (env.containsKey("SERVICE_NAME")) {\r
+                        url = urlPart1 + "/service_component/" + env.get("SERVICE_NAME");\r
+                        retCBSString = executecurl(url);\r
+                        debugLogger.info("Configuration fetched from CBS successfully..");\r
+                } else {\r
+                        errorLogger.error(\r
+                                        "Service name environment variable - HOSTNAME/SERVICE_NAME not found within container ");\r
+                }\r
+                \r
+        }\r
+        \r
+        public void writefile(String retCBSString, String configFile) {\r
+                \r
+                String indentedretstring = (new JSONObject(retCBSString)).toString(4);\r
+                File f = new File(ClassLoader.getSystemResource(configFile.trim()).getFile());\r
+                try {\r
+                        debugLogger.info("Overwriting local configuration file " + configFile\r
+                                        + " with configuartions received from CBS");\r
+                        \r
+                        \r
+                        File file2 = ResourceUtils.getFile("classpath:" + configFile);\r
+                        FileWriter fstream = new FileWriter(file2, false);\r
+                        PrintWriter printWriter = new PrintWriter(fstream);\r
+                        printWriter.print(indentedretstring);\r
+                        printWriter.close();\r
+                        \r
+                        debugLogger.info("New Config successfully written to local file to "\r
+                                        + configFile);\r
+                } catch (IOException e) {\r
+                        errorLogger.error("Error in writing configuration into local KV file "\r
+                                        + configFile + retString + e.getMessage());\r
+                        e.printStackTrace();\r
+                }\r
+                \r
+        }\r
+        \r
+        public static String readFile(String configFileName) {\r
+                String content = null;\r
+                File file = null;\r
+                \r
+                try {\r
+                        file = ResourceUtils.getFile("classpath:" + configFileName);\r
+                        content = new String(Files.readAllBytes(file.toPath()));\r
+                } catch (FileNotFoundException e) {\r
+                        errorLogger.error("colud not find file :", file.getName());\r
+                        \r
+                } catch (IOException e) {\r
+                        errorLogger.error("unable to read the file , reason:", e.getCause());\r
+                } catch (Exception e) {\r
+                        errorLogger.error("Exception occured , reason:", e.getMessage());\r
+                }\r
+                \r
+                return content;\r
+                \r
+        }\r
+        \r
+        private static String executecurl(String url) {\r
+                \r
+                String[] command = {"curl", "-v", url};\r
+                ProcessBuilder process = new ProcessBuilder(command);\r
+                Process p;\r
+                String result = null;\r
+                try {\r
+                        p = process.start();\r
+                        InputStreamReader ipr = new InputStreamReader(p.getInputStream());\r
+                        BufferedReader reader = new BufferedReader(ipr);\r
+                        StringBuilder builder = new StringBuilder();\r
+                        String line;\r
+                        \r
+                        while ((line = reader.readLine()) != null) {\r
+                                builder.append(line);\r
+                        }\r
+                        result = builder.toString();\r
+                        reader.close();\r
+                        ipr.close();\r
+                } catch (IOException e) {\r
+                        errorLogger.error("error", e);\r
+                        e.printStackTrace();\r
+                }\r
+                return result;\r
+                \r
+        }\r
+        \r
+}\r