Fix sonar issues in UniversalVesAdapter 88/91588/4
authorParshad Patel <pars.patel@samsung.com>
Wed, 17 Jul 2019 10:57:57 +0000 (19:57 +0900)
committerParshad Patel <pars.patel@samsung.com>
Fri, 6 Sep 2019 02:18:12 +0000 (11:18 +0900)
Fix Either log or rethrow this exception
Use try-with-resources or close this "FileWriter" in a "finally" clause
Use a logger to log this exception
Rename CollectorConfigPropertyRetrival.java to CollectorConfigPropertyRetrieval

Issue-ID: DCAEGEN2-1384
Change-Id: If38042bd192da2ca30b5d6eaf3288e4e83ef4682
Signed-off-by: Parshad Patel <pars.patel@samsung.com>
UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/adapter/UniversalEventAdapter.java
UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/service/VESAdapterInitializer.java
UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/service/VesService.java
UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/utils/CollectorConfigPropertyRetrieval.java [moved from UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/utils/CollectorConfigPropertyRetrival.java with 83% similarity]
UniversalVesAdapter/src/main/java/org/onap/universalvesadapter/utils/FetchDynamicConfig.java
UniversalVesAdapter/src/test/java/org/onap/universalvesadapter/adapter/UniversalEventAdapterTest.java

index 483b19b..7e41f38 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.adapter;\r
-\r
-import java.io.ByteArrayInputStream;\r
-import java.io.IOException;\r
-import java.nio.charset.StandardCharsets;\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-import java.util.concurrent.ConcurrentHashMap;\r
-\r
-import javax.annotation.PreDestroy;\r
-\r
-import org.milyn.Smooks;\r
-import org.onap.universalvesadapter.exception.ConfigFileSmooksConversionException;\r
-import org.onap.universalvesadapter.exception.VesException;\r
-import org.onap.universalvesadapter.service.VESAdapterInitializer;\r
-import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrival;\r
-import org.onap.universalvesadapter.utils.SmooksUtils;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Value;\r
-import org.springframework.stereotype.Component;\r
-import org.xml.sax.SAXException;\r
-\r
-import com.fasterxml.jackson.core.JsonProcessingException;\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-import com.google.gson.Gson;\r
-import com.google.gson.JsonElement;\r
-import com.google.gson.JsonObject;\r
-import com.google.gson.JsonParseException;\r
-import com.google.gson.JsonSyntaxException;\r
-\r
-/**\r
- * Default implementation of the Generic Adapter\r
- * \r
- * @author kmalbari\r
- *\r
- */\r
-\r
-@Component\r
-public class UniversalEventAdapter implements GenericAdapter {\r
-        private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");\r
-        private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
-        \r
-        @Value("${defaultConfigFilelocation}")\r
-        private String defaultConfigFilelocation;\r
-        private String collectorIdentifierValue;\r
-        private String collectorIdentifierKey;\r
-        private Map<String, Smooks> eventToSmooksMapping = new ConcurrentHashMap<>();\r
-        \r
-        public UniversalEventAdapter() {\r
-                \r
-        }\r
-        \r
-        /**\r
-         * transforms JSON to VES format and and returns the ves Event\r
-         * \r
-         * @param IncomingJason,eventType\r
-         * @return ves Event\r
-         */\r
-        @Override\r
-        public String transform(String incomingJsonString)\r
-                        throws ConfigFileSmooksConversionException, VesException {\r
-                String result = "";\r
-                String configFileData;\r
-                \r
-                String identifier[] = CollectorConfigPropertyRetrival.getProperyArray("identifier",\r
-                                defaultConfigFilelocation);\r
-                String defaultMappingFile =\r
-                                "defaultMappingFile-" + Thread.currentThread().getName();\r
-                try {\r
-                        \r
-                        Gson gson = new Gson();\r
-                        JsonObject body = gson.fromJson(incomingJsonString, JsonObject.class);\r
-                        \r
-                        JsonElement results;\r
-                        for (int i = 0; i < identifier.length; i++) {\r
-                                JsonObject obj;\r
-                                if ((obj = keyObject(body, identifier[i])).has(identifier[i])) {\r
-                                        collectorIdentifierKey = identifier[i];\r
-                                        results = obj.get(identifier[i]);\r
-                                        collectorIdentifierValue = results.getAsString();\r
-                                        \r
-                                }\r
-                                \r
-                        }\r
-                        // collectorIdentifierValue = collectorIdentifierValue.substring(0,\r
-                        // collectorIdentifierValue.length() - 4);\r
-                        if (collectorIdentifierKey.equals("notify OID")) {\r
-                                collectorIdentifierValue = collectorIdentifierValue.substring(0,\r
-                                                collectorIdentifierValue.length() - 4);\r
-                        }\r
-                        \r
-                        \r
-                        if (VESAdapterInitializer.getMappingFiles()\r
-                                        .containsKey(collectorIdentifierValue)) {\r
-                                configFileData = VESAdapterInitializer.getMappingFiles()\r
-                                                .get(collectorIdentifierValue);\r
-                                debugLogger.debug(\r
-                                                "Using Mapping file as Mapping file is available for collector identifier:{}",\r
-                                                collectorIdentifierValue);\r
-                                \r
-                        } else {\r
-                                \r
-                                configFileData = VESAdapterInitializer.getMappingFiles()\r
-                                                .get(defaultMappingFile);\r
-                                \r
-                                debugLogger.debug(\r
-                                                "Using Default Mapping file as Mapping file is not available for Enterprise Id / identifer ID:{}",\r
-                                                collectorIdentifierValue);\r
-                        }\r
-                        \r
-                        Smooks smooksTemp = new Smooks(new ByteArrayInputStream(\r
-                                        configFileData.getBytes(StandardCharsets.UTF_8)));\r
-                        eventToSmooksMapping.put(collectorIdentifierKey, smooksTemp);\r
-                        \r
-                        Object vesEvent = SmooksUtils.getTransformedObjectForInput(smooksTemp,\r
-                                        incomingJsonString);\r
-                        debugLogger.info("Incoming json transformed to VES format successfully:"\r
-                                        + Thread.currentThread().getName());\r
-                        ObjectMapper objectMapper = new ObjectMapper();\r
-                        result = objectMapper.writeValueAsString(vesEvent);\r
-                        debugLogger.info("Serialized VES json");\r
-                } catch (JsonProcessingException exception) {\r
-                        throw new VesException("Unable to convert pojo to VES format, Reason :{}",\r
-                                        exception);\r
-                } catch (SAXException | IOException exception) {\r
-                        // Invalid Mapping file\r
-                        exception.printStackTrace();\r
-                        errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString,\r
-                                        exception.getMessage());\r
-                        \r
-                } catch (JsonSyntaxException exception) {\r
-                        // Invalid Trap\r
-                        errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}",\r
-                                        incomingJsonString, exception);\r
-                } catch (JsonParseException exception) {\r
-                        // Invalid Trap\r
-                        errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}",\r
-                                        incomingJsonString, exception);\r
-                } catch (RuntimeException exception) {\r
-                        \r
-                        exception.printStackTrace();\r
-                        errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString,\r
-                                        exception.getMessage());\r
-                        \r
-                }\r
-                return result;\r
-        }\r
-        \r
-        /**\r
-         * Closes all open smooks' instances before bean is destroyed\r
-         */\r
-        @PreDestroy\r
-        public void destroy() {\r
-                for (Smooks smooks : eventToSmooksMapping.values())\r
-                        smooks.close();\r
-                debugLogger.warn("All Smooks objects closed");\r
-        }\r
-        \r
-        public JsonObject keyObject(JsonObject object, String searchedKey) {\r
-                boolean exists = object.has(searchedKey);\r
-                JsonObject jsonObject = object;\r
-                \r
-                if (!exists) {\r
-                        Iterator<?> keys = object.keySet().iterator();\r
-                        while (keys.hasNext()) {\r
-                                String key = (String) keys.next();\r
-                                if (object.get(key) instanceof JsonObject) {\r
-                                        \r
-                                        jsonObject = (JsonObject) object.get(key);\r
-                                        JsonObject obj = keyObject(jsonObject, searchedKey);\r
-                                        exists = obj.has(searchedKey);\r
-                                }\r
-                        }\r
-                }\r
-                \r
-                return jsonObject;\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.adapter;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.PreDestroy;
+import org.milyn.Smooks;
+import org.onap.universalvesadapter.exception.ConfigFileSmooksConversionException;
+import org.onap.universalvesadapter.exception.VesException;
+import org.onap.universalvesadapter.service.VESAdapterInitializer;
+import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrieval;
+import org.onap.universalvesadapter.utils.SmooksUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.xml.sax.SAXException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSyntaxException;
+
+/**
+ * Default implementation of the Generic Adapter
+ *
+ * @author kmalbari
+ *
+ */
+
+@Component
+public class UniversalEventAdapter implements GenericAdapter {
+    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
+    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
+
+    @Value("${defaultConfigFilelocation}")
+    private String defaultConfigFilelocation;
+    private String collectorIdentifierValue;
+    private String collectorIdentifierKey;
+    private Map<String, Smooks> eventToSmooksMapping = new ConcurrentHashMap<>();
+
+    public UniversalEventAdapter() {
+
+    }
+
+    /**
+     * transforms JSON to VES format and and returns the ves Event
+     *
+     * @param IncomingJason,eventType
+     * @return ves Event
+     */
+    @Override
+    public String transform(String incomingJsonString)
+            throws ConfigFileSmooksConversionException, VesException {
+        String result = "";
+        String configFileData;
+
+        String identifier[] = CollectorConfigPropertyRetrieval.getProperyArray("identifier",
+                defaultConfigFilelocation);
+        String defaultMappingFile =
+                "defaultMappingFile-" + Thread.currentThread().getName();
+        try {
+
+            Gson gson = new Gson();
+            JsonObject body = gson.fromJson(incomingJsonString, JsonObject.class);
+
+            JsonElement results;
+            for (int i = 0; i < identifier.length; i++) {
+                JsonObject obj;
+                if ((obj = keyObject(body, identifier[i])).has(identifier[i])) {
+                    collectorIdentifierKey = identifier[i];
+                    results = obj.get(identifier[i]);
+                    collectorIdentifierValue = results.getAsString();
+
+                }
+
+            }
+            // collectorIdentifierValue = collectorIdentifierValue.substring(0,
+            // collectorIdentifierValue.length() - 4);
+            if (collectorIdentifierKey.equals("notify OID")) {
+                collectorIdentifierValue = collectorIdentifierValue.substring(0,
+                        collectorIdentifierValue.length() - 4);
+            }
+
+            if (VESAdapterInitializer.getMappingFiles()
+                    .containsKey(collectorIdentifierValue)) {
+                configFileData = VESAdapterInitializer.getMappingFiles()
+                        .get(collectorIdentifierValue);
+                debugLogger.debug(
+                        "Using Mapping file as Mapping file is available for collector identifier:{}",
+                        collectorIdentifierValue);
+
+            } else {
+
+                configFileData = VESAdapterInitializer.getMappingFiles()
+                        .get(defaultMappingFile);
+
+                debugLogger.debug(
+                        "Using Default Mapping file as Mapping file is not available for Enterprise Id / identifer ID:{}",
+                        collectorIdentifierValue);
+            }
+
+            Smooks smooksTemp = new Smooks(new ByteArrayInputStream(
+                    configFileData.getBytes(StandardCharsets.UTF_8)));
+            eventToSmooksMapping.put(collectorIdentifierKey, smooksTemp);
+
+            Object vesEvent = SmooksUtils.getTransformedObjectForInput(smooksTemp,
+                    incomingJsonString);
+            debugLogger.info("Incoming json transformed to VES format successfully:"
+                    + Thread.currentThread().getName());
+            ObjectMapper objectMapper = new ObjectMapper();
+            result = objectMapper.writeValueAsString(vesEvent);
+            debugLogger.info("Serialized VES json");
+        } catch (JsonProcessingException exception) {
+            throw new VesException("Unable to convert pojo to VES format, Reason :{}",
+                    exception);
+        } catch (SAXException | IOException exception) {
+            // Invalid Mapping file
+            exception.printStackTrace();
+            errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString,
+                    exception.getMessage());
+
+        } catch (JsonSyntaxException exception) {
+            // Invalid Trap
+            errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}",
+                    incomingJsonString, exception);
+        } catch (JsonParseException exception) {
+            // Invalid Trap
+            errorLogger.error("Dropping this Invalid json Trap :{},  Reason:{}",
+                    incomingJsonString, exception);
+        } catch (RuntimeException exception) {
+
+            exception.printStackTrace();
+            errorLogger.error("Dropping this Trap :{},Reason:{}", incomingJsonString,
+                    exception.getMessage());
+
+        }
+        return result;
+    }
+
+    /**
+     * Closes all open smooks' instances before bean is destroyed
+     */
+    @PreDestroy
+    public void destroy() {
+        for (Smooks smooks : eventToSmooksMapping.values())
+            smooks.close();
+        debugLogger.warn("All Smooks objects closed");
+    }
+
+    public JsonObject keyObject(JsonObject object, String searchedKey) {
+        boolean exists = object.has(searchedKey);
+        JsonObject jsonObject = object;
+
+        if (!exists) {
+            Iterator<?> keys = object.keySet().iterator();
+            while (keys.hasNext()) {
+                String key = (String) keys.next();
+                if (object.get(key) instanceof JsonObject) {
+
+                    jsonObject = (JsonObject) object.get(key);
+                    JsonObject obj = keyObject(jsonObject, searchedKey);
+                    exists = obj.has(searchedKey);
+                }
+            }
+        }
+
+        return jsonObject;
+    }
+
+}
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();
+    }
+
+}
index 644c348..26d4303 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.util.ArrayList;\r
-import java.util.LinkedList;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.concurrent.ExecutorService;\r
-import java.util.concurrent.Executors;\r
-\r
-import org.onap.universalvesadapter.adapter.UniversalEventAdapter;\r
-import org.onap.universalvesadapter.dmaap.Creator;\r
-import org.onap.universalvesadapter.dmaap.MRPublisher.DMaaPMRPublisher;\r
-import org.onap.universalvesadapter.dmaap.MRSubcriber.DMaaPMRSubscriber;\r
-import org.onap.universalvesadapter.exception.DMaapException;\r
-import org.onap.universalvesadapter.exception.MapperConfigException;\r
-import org.onap.universalvesadapter.exception.VesException;\r
-import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrival;\r
-import org.onap.universalvesadapter.utils.DmaapConfig;\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.stereotype.Component;\r
-\r
-/**\r
- * Service that starts the universal ves adapter module to listen for events\r
- * \r
- * @author kmalbari\r
- *\r
- */\r
-/**\r
- * @author PM00501616\r
- *\r
- */\r
-\r
-@Component\r
-public class VesService {\r
-    \r
-    private static final Logger metricsLogger = LoggerFactory.getLogger("metricsLogger");\r
-    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");\r
-    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
-    \r
-    private boolean isRunning = true;\r
-    @Value("${defaultConfigFilelocation}")\r
-    private String defaultConfigFilelocation;\r
-    @Autowired\r
-    private Creator creator;\r
-    @Autowired\r
-    private UniversalEventAdapter eventAdapter;\r
-    @Autowired\r
-    private DmaapConfig dmaapConfig;\r
-    @Autowired\r
-    private CollectorConfigPropertyRetrival collectorConfigPropertyRetrival;\r
-    private static List<String> list = new LinkedList<String>();\r
-    \r
-    \r
-    /**\r
-     * method triggers universal VES adapter module.\r
-     */\r
-    public void start() throws MapperConfigException {\r
-        debugLogger.info("Creating Subcriber and Publisher with creator.............");\r
-        String topicName = null;\r
-        String publisherTopic = null;\r
-        // Hashmap of subscriber and publisher details in correspondence to the respective\r
-        // collectors in kv file\r
-        Map<String, String> dmaapTopics = collectorConfigPropertyRetrival\r
-                .getDmaapTopics("stream_subscriber", "stream_publisher", defaultConfigFilelocation);\r
-        \r
-        ExecutorService executorService = Executors.newFixedThreadPool(dmaapTopics.size());\r
-        for (Map.Entry<String, String> entry : dmaapTopics.entrySet()) {\r
-            String threadName = entry.getKey();\r
-            // subcriber and corresponding publisher topics in a Map\r
-            Map<String, String> subpubTopics = collectorConfigPropertyRetrival\r
-                    .getTopics(entry.getKey(), entry.getValue(), defaultConfigFilelocation);\r
-            for (Map.Entry<String, String> entry2 : subpubTopics.entrySet()) {\r
-                topicName = entry2.getKey();\r
-                publisherTopic = entry2.getValue();\r
-            }\r
-            \r
-            \r
-            // Publisher and subcriber as per each collector\r
-            DMaaPMRSubscriber subcriber = creator.getDMaaPMRSubscriber(topicName);\r
-            \r
-            DMaaPMRPublisher publisher = creator.getDMaaPMRPublisher(publisherTopic);\r
-            debugLogger.info(\r
-                    "Created scriber topic:" + topicName + "publisher topic:" + publisherTopic);\r
-            \r
-            executorService.submit(new Runnable() {\r
-                \r
-                @Override\r
-                public void run() {\r
-                    \r
-                    Thread.currentThread().setName(threadName);\r
-                    metricsLogger.info("fetch and publish from and to Dmaap started:"\r
-                            + Thread.currentThread().getName());\r
-                    int pollingInternalInt = dmaapConfig.getPollingInterval();\r
-                    debugLogger.info(\r
-                            "The Polling Interval in Milli Second is :{}" + pollingInternalInt);\r
-                    debugLogger.info("starting subscriber & publisher thread:{}",\r
-                            Thread.currentThread().getName());\r
-                    while (true) {\r
-                        synchronized (this) {\r
-                            for (String incomingJsonString : subcriber.fetchMessages()\r
-                                    .getFetchedMessages()) {\r
-                                list.add(incomingJsonString);\r
-                                \r
-                            }\r
-                            \r
-                            if (list.isEmpty()) {\r
-                                try {\r
-                                    Thread.sleep(pollingInternalInt);\r
-                                } catch (InterruptedException e) {\r
-                                    e.printStackTrace();\r
-                                }\r
-                            }\r
-                            debugLogger.debug("number of messages to be converted :{}",\r
-                                    list.size());\r
-                            \r
-                            if (!list.isEmpty()) {\r
-                                String val = ((LinkedList<String>) list).removeFirst();\r
-                                List<String> messages = new ArrayList<>();\r
-                                String vesEvent = processReceivedJson(val);\r
-                                if (vesEvent != null\r
-                                        && (!(vesEvent.isEmpty() || vesEvent.equals("")))) {\r
-                                    messages.add(vesEvent);\r
-                                    publisher.publish(messages);\r
-                                    \r
-                                    metricsLogger\r
-                                            .info("Message successfully published to DMaaP Topic-\n"\r
-                                                    + vesEvent);\r
-                                }\r
-                            }\r
-                        }\r
-                    }\r
-                }\r
-            });\r
-        }\r
-        \r
-        \r
-        \r
-    }\r
-    \r
-    /**\r
-     * method stops universal ves adapter module\r
-     */\r
-    public void stop() {\r
-        isRunning = false;\r
-    }\r
-    \r
-    \r
-    /**\r
-     * method for processing the incoming json to ves\r
-     * \r
-     * @param incomingJsonString\r
-     * @return ves\r
-     */\r
-    private String processReceivedJson(String incomingJsonString) {\r
-        String outgoingJsonString = null;\r
-        if (!"".equals(incomingJsonString)) {\r
-            \r
-            try {\r
-                \r
-                outgoingJsonString = eventAdapter.transform(incomingJsonString);\r
-                \r
-            } catch (VesException exception) {\r
-                errorLogger.error("Received exception : {},{}" + exception.getMessage(), exception);\r
-                debugLogger.warn("APPLICATION WILL BE SHUTDOWN UNTIL ABOVE ISSUE IS RESOLVED.");\r
-            } catch (DMaapException e) {\r
-                errorLogger.error("Received exception : {}", e.getMessage());\r
-            }\r
-        }\r
-        return outgoingJsonString;\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.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.onap.universalvesadapter.adapter.UniversalEventAdapter;
+import org.onap.universalvesadapter.dmaap.Creator;
+import org.onap.universalvesadapter.dmaap.MRPublisher.DMaaPMRPublisher;
+import org.onap.universalvesadapter.dmaap.MRSubcriber.DMaaPMRSubscriber;
+import org.onap.universalvesadapter.exception.DMaapException;
+import org.onap.universalvesadapter.exception.MapperConfigException;
+import org.onap.universalvesadapter.exception.VesException;
+import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrieval;
+import org.onap.universalvesadapter.utils.DmaapConfig;
+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.stereotype.Component;
+
+/**
+ * Service that starts the universal ves adapter module to listen for events
+ *
+ * @author kmalbari
+ *
+ */
+/**
+ * @author PM00501616
+ *
+ */
+
+@Component
+public class VesService {
+
+    private static final Logger metricsLogger = LoggerFactory.getLogger("metricsLogger");
+    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
+    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
+
+    private boolean isRunning = true;
+    @Value("${defaultConfigFilelocation}")
+    private String defaultConfigFilelocation;
+    @Autowired
+    private Creator creator;
+    @Autowired
+    private UniversalEventAdapter eventAdapter;
+    @Autowired
+    private DmaapConfig dmaapConfig;
+    @Autowired
+    private CollectorConfigPropertyRetrieval collectorConfigPropertyRetrival;
+    private static List<String> list = new LinkedList<String>();
+
+
+    /**
+     * method triggers universal VES adapter module.
+     */
+    public void start() throws MapperConfigException {
+        debugLogger.info("Creating Subcriber and Publisher with creator.............");
+        String topicName = null;
+        String publisherTopic = null;
+        // Hashmap of subscriber and publisher details in correspondence to the respective
+        // collectors in kv file
+        Map<String, String> dmaapTopics = collectorConfigPropertyRetrival
+                .getDmaapTopics("stream_subscriber", "stream_publisher", defaultConfigFilelocation);
+
+        ExecutorService executorService = Executors.newFixedThreadPool(dmaapTopics.size());
+        for (Map.Entry<String, String> entry : dmaapTopics.entrySet()) {
+            String threadName = entry.getKey();
+            // subcriber and corresponding publisher topics in a Map
+            Map<String, String> subpubTopics = collectorConfigPropertyRetrival
+                    .getTopics(entry.getKey(), entry.getValue(), defaultConfigFilelocation);
+            for (Map.Entry<String, String> entry2 : subpubTopics.entrySet()) {
+                topicName = entry2.getKey();
+                publisherTopic = entry2.getValue();
+            }
+
+
+            // Publisher and subcriber as per each collector
+            DMaaPMRSubscriber subcriber = creator.getDMaaPMRSubscriber(topicName);
+
+            DMaaPMRPublisher publisher = creator.getDMaaPMRPublisher(publisherTopic);
+            debugLogger.info(
+                    "Created scriber topic:" + topicName + "publisher topic:" + publisherTopic);
+
+            executorService.submit(new Runnable() {
+
+                @Override
+                public void run() {
+
+                    Thread.currentThread().setName(threadName);
+                    metricsLogger.info("fetch and publish from and to Dmaap started:"
+                            + Thread.currentThread().getName());
+                    int pollingInternalInt = dmaapConfig.getPollingInterval();
+                    debugLogger.info(
+                            "The Polling Interval in Milli Second is :{}" + pollingInternalInt);
+                    debugLogger.info("starting subscriber & publisher thread:{}",
+                            Thread.currentThread().getName());
+                    while (true) {
+                        synchronized (this) {
+                            for (String incomingJsonString : subcriber.fetchMessages()
+                                    .getFetchedMessages()) {
+                                list.add(incomingJsonString);
+
+                            }
+
+                            if (list.isEmpty()) {
+                                try {
+                                    Thread.sleep(pollingInternalInt);
+                                } catch (InterruptedException e) {
+                                    e.printStackTrace();
+                                }
+                            }
+                            debugLogger.debug("number of messages to be converted :{}",
+                                    list.size());
+
+                            if (!list.isEmpty()) {
+                                String val = ((LinkedList<String>) list).removeFirst();
+                                List<String> messages = new ArrayList<>();
+                                String vesEvent = processReceivedJson(val);
+                                if (vesEvent != null
+                                        && (!(vesEvent.isEmpty() || vesEvent.equals("")))) {
+                                    messages.add(vesEvent);
+                                    publisher.publish(messages);
+
+                                    metricsLogger
+                                    .info("Message successfully published to DMaaP Topic-\n"
+                                            + vesEvent);
+                                }
+                            }
+                        }
+                    }
+                }
+            });
+        }
+
+
+
+    }
+
+    /**
+     * method stops universal ves adapter module
+     */
+    public void stop() {
+        isRunning = false;
+    }
+
+
+    /**
+     * method for processing the incoming json to ves
+     *
+     * @param incomingJsonString
+     * @return ves
+     */
+    private String processReceivedJson(String incomingJsonString) {
+        String outgoingJsonString = null;
+        if (!"".equals(incomingJsonString)) {
+
+            try {
+
+                outgoingJsonString = eventAdapter.transform(incomingJsonString);
+
+            } catch (VesException exception) {
+                errorLogger.error("Received exception : {},{}" + exception.getMessage(), exception);
+                debugLogger.warn("APPLICATION WILL BE SHUTDOWN UNTIL ABOVE ISSUE IS RESOLVED.");
+            } catch (DMaapException e) {
+                errorLogger.error("Received exception : {}", e.getMessage());
+            }
+        }
+        return outgoingJsonString;
+    }
+}
-/*-\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.utils;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.IOException;\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-import java.nio.file.Files;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.json.simple.JSONArray;\r
-import org.json.simple.JSONObject;\r
-import org.json.simple.parser.JSONParser;\r
-import org.json.simple.parser.ParseException;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\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 CollectorConfigPropertyRetrival {\r
-    \r
-    \r
-    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");\r
-    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
-    private static JSONArray array;\r
-    @Autowired\r
-    private DmaapConfig dmaapConfig;\r
-    \r
-    public static JSONArray collectorConfigArray(String configFile) {\r
-        try {\r
-            JSONParser parser = new JSONParser();\r
-            String content = readFile(configFile);\r
-            JSONObject obj = (JSONObject) parser.parse(content);\r
-            JSONObject appobj = (JSONObject) obj.get("app_preferences");\r
-            array = (JSONArray) appobj.get("collectors");\r
-            \r
-            debugLogger.info("Retrieved JsonArray from Collector Config File");\r
-            \r
-        } catch (ParseException e) {\r
-            errorLogger.error("ParseException occured at position:", e.getPosition());\r
-        }\r
-        \r
-        \r
-        return array;\r
-        \r
-    }\r
-    \r
-    public static String[] getProperyArray(String properyName, String defaultConfigFilelocation) {\r
-        JSONArray jsonArray = collectorConfigArray(defaultConfigFilelocation);\r
-        \r
-        String[] propertyArray = new String[jsonArray.size()];\r
-        \r
-        for (int k = 0; k < jsonArray.size(); k++) {\r
-            \r
-            JSONObject collJson = (JSONObject) jsonArray.get(k);\r
-            \r
-            propertyArray[k] = (String) collJson.get(properyName);\r
-        }\r
-        debugLogger.info("returning " + properyName + " array from Collector Config");\r
-        return propertyArray;\r
-        \r
-    }\r
-    \r
-    public Map<String, String> getDmaapTopics(String subscriber, String publisher,\r
-            String defaultConfigFilelocation) {\r
-        JSONArray jsonArray = collectorConfigArray(defaultConfigFilelocation);\r
-        \r
-        Map<String, String> dmaapTopics = new HashMap<>();\r
-        \r
-        for (int k = 0; k < jsonArray.size(); k++) {\r
-            \r
-            JSONObject collJson = (JSONObject) jsonArray.get(k);\r
-            \r
-            dmaapTopics.put(collJson.get(subscriber).toString(),\r
-                    collJson.get(publisher).toString());\r
-            \r
-        }\r
-        debugLogger.info("returning Dmaap topics from Collector Config");\r
-        return dmaapTopics;\r
-        \r
-    }\r
-    \r
-    public Map<String, String> getTopics(String subscriber, String publisher,\r
-            String defaultConfigFilelocation) {\r
-        Map<String, String> dmaapTopics = new HashMap<>();\r
-        \r
-        try {\r
-            \r
-            ObjectMapper objectMapper = new ObjectMapper();\r
-            String content = readFile(defaultConfigFilelocation);\r
-            // read JSON like DOM Parser\r
-            JsonNode rootNode = objectMapper.readTree(content);\r
-            JsonNode subscriberUrl = rootNode.path("streams_subscribes").path(subscriber)\r
-                    .path("dmaap_info").path("topic_url");\r
-            JsonNode publisherUrl = rootNode.path("streams_publishes").path(publisher)\r
-                    .path("dmaap_info").path("topic_url");\r
-            \r
-            dmaapTopics.put(getTopicName(subscriberUrl.asText()),\r
-                    getTopicName(publisherUrl.asText()));\r
-            setDmaapConfig(subscriberUrl.asText());\r
-        } catch (IOException ex) {\r
-            errorLogger.error("IOException occured:" + ex.getMessage());\r
-            \r
-        } catch (URISyntaxException e) {\r
-            \r
-            errorLogger.error("Invalid URI :" + e.getInput() + ": " + e.getReason());\r
-        }\r
-        \r
-        return dmaapTopics;\r
-        \r
-    }\r
-    \r
-    public String getTopicName(String url) throws URISyntaxException {\r
-        URI uri = new URI(url);\r
-        String path = uri.getPath();\r
-        String idStr = path.substring(path.lastIndexOf('/') + 1);\r
-        return idStr;\r
-        \r
-    }\r
-    \r
-    public void setDmaapConfig(String url) throws URISyntaxException {\r
-        URI uri = new URI(url);\r
-        dmaapConfig.setDmaaphost(uri.getHost());\r
-        dmaapConfig.setDEFAULT_PORT_NUMBER(uri.getPort());\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 :", configFileName);\r
-            \r
-        } catch (IOException e) {\r
-            errorLogger.error("unable to read the file , reason:", e.getCause());\r
-        }\r
-        \r
-        return content;\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.utils;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.util.ResourceUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class CollectorConfigPropertyRetrieval {
+
+    private static final Logger debugLogger = LoggerFactory.getLogger("debugLogger");
+    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
+    private static JSONArray array;
+    @Autowired
+    private DmaapConfig dmaapConfig;
+
+    public static JSONArray collectorConfigArray(String configFile) {
+        try {
+            JSONParser parser = new JSONParser();
+            String content = readFile(configFile);
+            JSONObject obj = (JSONObject) parser.parse(content);
+            JSONObject appobj = (JSONObject) obj.get("app_preferences");
+            array = (JSONArray) appobj.get("collectors");
+
+            debugLogger.info("Retrieved JsonArray from Collector Config File");
+
+        } catch (ParseException e) {
+            errorLogger.error("ParseException occured at position:", e);
+        }
+
+        return array;
+
+    }
+
+    public static String[] getProperyArray(String propertyName, String defaultConfigFilelocation) {
+        JSONArray jsonArray = collectorConfigArray(defaultConfigFilelocation);
+
+        String[] propertyArray = new String[jsonArray.size()];
+
+        for (int k = 0; k < jsonArray.size(); k++) {
+
+            JSONObject collJson = (JSONObject) jsonArray.get(k);
+
+            propertyArray[k] = (String) collJson.get(propertyName);
+        }
+        debugLogger.info("returning {} array from Collector Config", propertyName);
+        return propertyArray;
+
+    }
+
+    public Map<String, String> getDmaapTopics(String subscriber, String publisher,
+            String defaultConfigFilelocation) {
+        JSONArray jsonArray = collectorConfigArray(defaultConfigFilelocation);
+
+        Map<String, String> dmaapTopics = new HashMap<>();
+
+        for (int k = 0; k < jsonArray.size(); k++) {
+
+            JSONObject collJson = (JSONObject) jsonArray.get(k);
+
+            dmaapTopics.put(collJson.get(subscriber).toString(),
+                    collJson.get(publisher).toString());
+
+        }
+        debugLogger.info("returning Dmaap topics from Collector Config");
+        return dmaapTopics;
+
+    }
+
+    public Map<String, String> getTopics(String subscriber, String publisher,
+            String defaultConfigFilelocation) {
+        Map<String, String> dmaapTopics = new HashMap<>();
+
+        try {
+
+            ObjectMapper objectMapper = new ObjectMapper();
+            String content = readFile(defaultConfigFilelocation);
+            // read JSON like DOM Parser
+            JsonNode rootNode = objectMapper.readTree(content);
+            JsonNode subscriberUrl = rootNode.path("streams_subscribes").path(subscriber)
+                    .path("dmaap_info").path("topic_url");
+            JsonNode publisherUrl = rootNode.path("streams_publishes").path(publisher)
+                    .path("dmaap_info").path("topic_url");
+
+            dmaapTopics.put(getTopicName(subscriberUrl.asText()),
+                    getTopicName(publisherUrl.asText()));
+            setDmaapConfig(subscriberUrl.asText());
+        } catch (IOException ex) {
+            errorLogger.error("IOException occured:", ex);
+        } catch (URISyntaxException e) {
+            errorLogger.error("Invalid URI :", e);
+        }
+
+        return dmaapTopics;
+    }
+
+    public String getTopicName(String url) throws URISyntaxException {
+        URI uri = new URI(url);
+        String path = uri.getPath();
+        String idStr = path.substring(path.lastIndexOf('/') + 1);
+        return idStr;
+    }
+
+    public void setDmaapConfig(String url) throws URISyntaxException {
+        URI uri = new URI(url);
+        dmaapConfig.setDmaaphost(uri.getHost());
+        dmaapConfig.setDEFAULT_PORT_NUMBER(uri.getPort());
+    }
+
+    public static String readFile(String configFileName) {
+        String content = null;
+        File file = null;
+
+        try {
+            file = ResourceUtils.getFile("classpath:" + configFileName);
+            content = new String(Files.readAllBytes(file.toPath()));
+        } catch (FileNotFoundException e) {
+            errorLogger.error("colud not find file :{}", configFileName);
+
+        } catch (IOException e) {
+            errorLogger.error("unable to read the file , reason:", e);
+        }
+
+        return content;
+    }
+}
index 9493fc6..0c6155c 100644 (file)
-/*-\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
-\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.JSONArray;\r
-import org.json.JSONObject;\r
-import org.json.JSONTokener;\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.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
-       // @Value("${defaultProtocol}")\r
-       static String defaultProtocol = "http";\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
-\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
-       static final EnvProperties env = EnvProperties.fromEnvironment();\r
-\r
-       public FetchDynamicConfig() {\r
-\r
-       }\r
-\r
-       public static void cbsCall(String configFile) {\r
-\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
-                       if (retCBSString!=null) {\r
-                               fc.writefile(retCBSString, configFile);\r
-                       } else {\r
-                               debugLogger.debug("No content recieved from server");\r
-                       }\r
-                       \r
-               } else {\r
-                       debugLogger.info("New config pull results identical -  " + configFile + " NOT refreshed");\r
-               }\r
-       }\r
-\r
-       private static void getconsul() {\r
-               url = defaultProtocol + "://" + env.consulHost() + ":" + env.consulPort() + "/v1/catalog/service/"\r
-                               + env.cbsName();\r
-               retString = fetchResultFromDestination(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(ClassLoader.getSystemResource(configFile.trim()).getFile());\r
-\r
-                       if (f.exists() && !f.isDirectory()) {\r
-                               debugLogger.info("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("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") + ":" + cbsjobj.getInt("ServicePort");\r
-\r
-               }\r
-               debugLogger.info("CONFIG_BINDING_SERVICE HOST:PORT is " + urlPart1);\r
-\r
-               if (env.appName() != null) {\r
-                       url = defaultProtocol + "://" + urlPart1 + "/service_component/" + env.appName();\r
-                       retCBSString = fetchResultFromDestination(url);\r
-                       debugLogger.info("Configuration fetched from CBS successfully..");\r
-               } else {\r
-                       errorLogger.error("Service name environment variable - APP_NAME/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
-               try {\r
-                       debugLogger.info(\r
-                                       "Overwriting local configuration file " + configFile + " with configuartions received from CBS");\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
-                       fstream.close();\r
-\r
-                       debugLogger.info("New Config successfully written to local file to " + configFile);\r
-               } catch (IOException e) {\r
-                       errorLogger.error(\r
-                                       "Error in writing configuration into local KV file " + 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 :", configFileName);\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
-       private static String fetchResultFromDestination(String url) {\r
-               debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : START");\r
-\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
-                       String line = "";\r
-                       while ((line = rd.readLine()) != null) {\r
-                               sb.append(line);\r
-                               sb.append('\n');\r
-                       }\r
-               } catch (ClientProtocolException e) {\r
-                       debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : ClientProtocolException thrown."+e.getMessage());\r
-               } catch (UnsupportedOperationException e) {\r
-                       debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : UnsupportedOperationException thrown."+e.getMessage());\r
-               } catch (IOException e) {\r
-                       debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : IOException thrown."+e.getMessage());\r
-               }\r
-\r
-               debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : END");\r
-               return sb.toString();\r
-       }\r
-\r
-}\r
+/*-
+ * ============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.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.nio.file.Files;
+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.JSONArray;
+import org.json.JSONObject;
+import org.json.JSONTokener;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.util.ResourceUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class FetchDynamicConfig {
+
+    // @Value("${defaultProtocol}")
+    static String defaultProtocol = "http";
+
+    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;
+
+    // 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
+    static final EnvProperties env = EnvProperties.fromEnvironment();
+
+    public FetchDynamicConfig() {
+
+    }
+
+    public static void cbsCall(String configFile) {
+
+        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();
+            if (retCBSString != null) {
+                fc.writefile(retCBSString, configFile);
+            } else {
+                debugLogger.debug("No content recieved from server");
+            }
+        } else {
+            debugLogger.info("New config pull results identical -  {} NOT refreshed", configFile);
+        }
+    }
+
+    private static void getconsul() {
+        url = defaultProtocol + "://" + env.consulHost() + ":" + env.consulPort() + "/v1/catalog/service/"
+                + env.cbsName();
+        retString = fetchResultFromDestination(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(ClassLoader.getSystemResource(configFile.trim()).getFile());
+
+            if (f.exists() && !f.isDirectory()) {
+                debugLogger.info("Comparing local configuration with the configuration fethed from CBS ");
+
+                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);
+
+        }
+
+        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 HOST:PORT is {}", urlPart1);
+
+        if (env.appName() != null) {
+            url = defaultProtocol + "://" + urlPart1 + "/service_component/" + env.appName();
+            retCBSString = fetchResultFromDestination(url);
+            debugLogger.info("Configuration fetched from CBS successfully..");
+        } else {
+            errorLogger.error("Service name environment variable - APP_NAME/SERVICE_NAME not found within container ");
+        }
+    }
+
+    public void writefile(String retCBSString, String configFile) {
+
+        String indentedretstring = (new JSONObject(retCBSString)).toString(4);
+        try {
+            debugLogger.info("Overwriting local configuration file {} with configuartions received from CBS",
+                    configFile);
+
+            File file2 = ResourceUtils.getFile("classpath:" + configFile);
+            try (FileWriter fstream = new FileWriter(file2, false);
+                    PrintWriter printWriter = new PrintWriter(fstream)) {
+                printWriter.print(indentedretstring);
+            }
+
+            debugLogger.info("New Config successfully written to local file to {}", configFile);
+        } catch (IOException e) {
+            errorLogger.error(
+                    "Error in writing configuration into local KV file " + configFile + retString, e);
+        }
+    }
+
+    public static String readFile(String configFileName) {
+        String content = null;
+        File file = null;
+
+        try {
+            file = ResourceUtils.getFile("classpath:" + configFileName);
+            content = new String(Files.readAllBytes(file.toPath()));
+        } catch (FileNotFoundException e) {
+            errorLogger.error("colud not find file :{}", configFileName);
+        } catch (IOException e) {
+            errorLogger.error("unable to read the file , reason:", e);
+        } catch (Exception e) {
+            errorLogger.error("Exception occured , reason:", e);
+        }
+
+        return content;
+    }
+
+    private static String fetchResultFromDestination(String url) {
+        debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : START");
+
+        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()));
+            String line = "";
+            while ((line = rd.readLine()) != null) {
+                sb.append(line);
+                sb.append('\n');
+            }
+        } catch (ClientProtocolException e) {
+            debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : ClientProtocolException thrown.", e);
+        } catch (UnsupportedOperationException e) {
+            debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : UnsupportedOperationException thrown.",
+                    e);
+        } catch (IOException e) {
+            debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : IOException thrown.", e);
+        }
+
+        debugLogger.debug("FetchDynamicConfig : fetchResultFromDestination : END");
+        return sb.toString();
+    }
+
+}
index 233a27a..459047a 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.adapter;\r
-\r
-import static org.junit.Assert.assertNotEquals;\r
-import static org.junit.Assert.assertNotNull;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.InjectMocks;\r
-import org.mockito.Mock;\r
-import org.mockito.MockitoAnnotations;\r
-import org.onap.universalvesadapter.Application;\r
-import org.onap.universalvesadapter.exception.VesException;\r
-import org.onap.universalvesadapter.service.VESAdapterInitializer;\r
-import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrival;\r
-import org.powermock.api.mockito.PowerMockito;\r
-import org.powermock.core.classloader.annotations.PrepareForTest;\r
-import org.powermock.modules.junit4.PowerMockRunner;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-\r
-@RunWith(PowerMockRunner.class)\r
-@SpringBootTest(classes = Application.class)\r
-public class UniversalEventAdapterTest {\r
-        \r
-        private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");\r
-        \r
-        @Mock\r
-        private VESAdapterInitializer vesAdapterInitializer;\r
-        \r
-        @InjectMocks\r
-        private UniversalEventAdapter universalVesAdapter;\r
-        \r
-        @Before\r
-        public void init() {\r
-                MockitoAnnotations.initMocks(this);\r
-        }\r
-        \r
-        @PrepareForTest({CollectorConfigPropertyRetrival.class})\r
-        @Test\r
-        public void testtransform() {\r
-                \r
-                StringBuffer incomingJsonString = new StringBuffer("{\n"\r
-                                + "    \"rule-id\": \"12121\",\n" + "    \"notification\": {\n"\r
-                                + "        \"event-time\": \"2018-03-15T08:15:32.000Z\",\n"\r
-                                + "        \"notification-id\":  \"2541256\",\n"\r
-                                + "        \"message\":  {\n"\r
-                                + "            \"topic\":\"resource\",\n"\r
-                                + "            \"object-type\":\"onu\",               \n"\r
-                                + "            \"version\": \"v1\",               \n"\r
-                                + "            \"operation\": \"create\",   \n"\r
-                                + "            \"target\": \"ont/ont=23hk1231231232\",   \n"\r
-                                + "            \"content\":  {\n" + "                \"onu\":  {\n"\r
-                                + "                    \"sn\":   \"48575443FA637D1A\",\n"\r
-                                + "                    \"refParentNE\":  \"550e8400-e29b-41d4-a716-446655440000\",\n"\r
-                                + "                    \"refParentNeNativeId\":  \"FDN\",\n"\r
-                                + "                    \"refParentLTP\": \"8c0db89e-218c-4e18-b0de-7a6788b3dda4\",\n"\r
-                                + "                    \"refParentLTPNativeId\": \"FDN\",\n"\r
-                                + "                    \"onuId\": \"213\",\n"\r
-                                + "                    \"accessID\": \"HG65875420001\"\n"\r
-                                + "                }\n" + "            }\n" + "        }\n"\r
-                                + "    }\n" + "}");\r
-                Map<String, String> testMap = new HashMap<String, String>();\r
-                testMap.put("defaultMappingFile-" + Thread.currentThread().getName(),\r
-                                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"\r
-                                                + "<smooks-resource-list xmlns=\"http://www.milyn.org/xsd/smooks-1.1.xsd\" xmlns:jb=\"http://www.milyn.org/xsd/smooks/javabean-1.4.xsd\" xmlns:json=\"http://www.milyn.org/xsd/smooks/json-1.1.xsd\">\n"\r
-                                                + "   <json:reader rootName=\"vesevent\" keyWhitspaceReplacement=\"-\">\n"\r
-                                                + "      <json:keyMap>\n"\r
-                                                + "         <json:key from=\"date&amp;time\" to=\"date-and-time\" />\n"\r
-                                                + "      </json:keyMap>\n" + "   </json:reader>\n"\r
-                                                + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.VesEvent\""\r
-                                                + " beanId=\"vesEvent\" createOnElement=\"vesevent\">\n"\r
-                                                + "      <jb:wiring property=\"event\" beanIdRef=\"event\" />\n"\r
-                                                + "   </jb:bean>\n"\r
-                                                + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.Event\" "\r
-                                                + "beanId=\"event\" createOnElement=\"vesevent\">\n"\r
-                                                + "      <jb:wiring property=\"commonEventHeader\" beanIdRef=\"commonEventHeader\" />\n"\r
-                                                + "      <jb:wiring property=\"pnfRegistrationFields\" beanIdRef=\"pnfRegistrationFields\" />\n"\r
-                                                + "   </jb:bean>\n"\r
-                                                + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader\""\r
-                                                + " beanId=\"commonEventHeader\" createOnElement=\"vesevent\">\n"\r
-                                                + "<jb:expression property=\"version\">"\r
-                                                + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Version._4_0_1</jb:expression> \n"\r
-                                                + "<jb:expression property=\"eventType\">\"pnfRegistration\"</jb:expression>\n"\r
-                                                + "<jb:expression property=\"vesEventListenerVersion\">"\r
-                                                + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.VesEventListenerVersion._7_0_1"\r
-                                                + "</jb:expression>\n"\r
-                                                + "       <jb:expression property=\"eventId\" execOnElement=\"vesevent\">"\r
-                                                + "\"registration_\"+commonEventHeader.ts1</jb:expression>\n"\r
-                                                + "<jb:expression property=\"reportingEntityName\">\"VESMapper\"</jb:expression>\n"\r
-                                                + "      <jb:expression property=\"domain\">"\r
-                                                + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Domain.PNF_REGISTRATION"\r
-                                                + "</jb:expression>\n"\r
-                                                + "      <jb:expression property=\"eventName\" execOnElement=\"vesevent\">"\r
-                                                + "commonEventHeader.domain</jb:expression>\n"\r
-                                                + "<jb:value property=\"sequence\" data=\"0\" default=\"0\" decoder=\"Long\" />\n"\r
-                                                + "<jb:expression property=\"lastEpochMicrosec\" execOnElement=\"vesevent\">"\r
-                                                + "commonEventHeader.ts1</jb:expression>\n"\r
-                                                + "      <jb:expression property=\"startEpochMicrosec\" execOnElement=\"vesevent\">"\r
-                                                + "commonEventHeader.ts1</jb:expression>\n"\r
-                                                + "      <jb:expression property=\"priority\">"\r
-                                                + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Priority.NORMAL</jb:expression>\n"\r
-                                                + "      <jb:value property=\"sourceName\" data=\"notification/message/target\" />\n"\r
-                                                + "   </jb:bean>\n"\r
-                                                + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.PnfRegistrationFields\""\r
-                                                + " beanId=\"pnfRegistrationFields\" createOnElement=\"vesevent\">\n"\r
-                                                + "     \n"\r
-                                                + "       <jb:expression property=\"pnfRegistrationFieldsVersion\">"\r
-                                                + "org.onap.dcaegen2.ves.domain.ves70.PnfRegistrationFields.PnfRegistrationFieldsVersion._2_0"\r
-                                                + "</jb:expression>\n"\r
-                                                + "      <jb:value property=\"serialNumber\" data=\"notification/message/content/onu/sn\" />\n"\r
-                                                + "      \n" + "   </jb:bean>\n"\r
-                                                + "</smooks-resource-list>");\r
-                \r
-                try {\r
-                        vesAdapterInitializer.setMappingFiles(testMap);\r
-                        \r
-                        String[] identifiertest = CollectorConfigPropertyRetrival\r
-                                        .getProperyArray("identifier", "kvTest.json");\r
-                        PowerMockito.mockStatic(CollectorConfigPropertyRetrival.class);\r
-                        PowerMockito.when(CollectorConfigPropertyRetrival\r
-                                        .getProperyArray("identifier", null))\r
-                                        .thenReturn(identifiertest);\r
-                        \r
-                        String actualResult = universalVesAdapter\r
-                                        .transform(incomingJsonString.toString());\r
-                        assertNotNull(actualResult);\r
-                        assertNotEquals("", actualResult);\r
-                } catch (VesException exception) {\r
-                        errorLogger.error("Error occurred : {}", exception);\r
-                }\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.adapter;
+
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.universalvesadapter.Application;
+import org.onap.universalvesadapter.exception.VesException;
+import org.onap.universalvesadapter.service.VESAdapterInitializer;
+import org.onap.universalvesadapter.utils.CollectorConfigPropertyRetrieval;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@RunWith(PowerMockRunner.class)
+@SpringBootTest(classes = Application.class)
+public class UniversalEventAdapterTest {
+
+    private static final Logger errorLogger = LoggerFactory.getLogger("errorLogger");
+
+    @Mock
+    private VESAdapterInitializer vesAdapterInitializer;
+
+    @InjectMocks
+    private UniversalEventAdapter universalVesAdapter;
+
+    @Before
+    public void init() {
+        MockitoAnnotations.initMocks(this);
+    }
+
+    @PrepareForTest({ CollectorConfigPropertyRetrieval.class })
+    @Test
+    public void testtransform() {
+
+        StringBuffer incomingJsonString = new StringBuffer("{\n"
+                + "    \"rule-id\": \"12121\",\n" + "    \"notification\": {\n"
+                + "        \"event-time\": \"2018-03-15T08:15:32.000Z\",\n"
+                + "        \"notification-id\":  \"2541256\",\n"
+                + "        \"message\":  {\n"
+                + "            \"topic\":\"resource\",\n"
+                + "            \"object-type\":\"onu\",               \n"
+                + "            \"version\": \"v1\",               \n"
+                + "            \"operation\": \"create\",   \n"
+                + "            \"target\": \"ont/ont=23hk1231231232\",   \n"
+                + "            \"content\":  {\n" + "                \"onu\":  {\n"
+                + "                    \"sn\":   \"48575443FA637D1A\",\n"
+                + "                    \"refParentNE\":  \"550e8400-e29b-41d4-a716-446655440000\",\n"
+                + "                    \"refParentNeNativeId\":  \"FDN\",\n"
+                + "                    \"refParentLTP\": \"8c0db89e-218c-4e18-b0de-7a6788b3dda4\",\n"
+                + "                    \"refParentLTPNativeId\": \"FDN\",\n"
+                + "                    \"onuId\": \"213\",\n"
+                + "                    \"accessID\": \"HG65875420001\"\n"
+                + "                }\n" + "            }\n" + "        }\n"
+                + "    }\n" + "}");
+        Map<String, String> testMap = new HashMap<String, String>();
+        testMap.put("defaultMappingFile-" + Thread.currentThread().getName(),
+                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+                        + "<smooks-resource-list xmlns=\"http://www.milyn.org/xsd/smooks-1.1.xsd\" xmlns:jb=\"http://www.milyn.org/xsd/smooks/javabean-1.4.xsd\" xmlns:json=\"http://www.milyn.org/xsd/smooks/json-1.1.xsd\">\n"
+                        + "   <json:reader rootName=\"vesevent\" keyWhitspaceReplacement=\"-\">\n"
+                        + "      <json:keyMap>\n"
+                        + "         <json:key from=\"date&amp;time\" to=\"date-and-time\" />\n"
+                        + "      </json:keyMap>\n" + "   </json:reader>\n"
+                        + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.VesEvent\""
+                        + " beanId=\"vesEvent\" createOnElement=\"vesevent\">\n"
+                        + "      <jb:wiring property=\"event\" beanIdRef=\"event\" />\n"
+                        + "   </jb:bean>\n"
+                        + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.Event\" "
+                        + "beanId=\"event\" createOnElement=\"vesevent\">\n"
+                        + "      <jb:wiring property=\"commonEventHeader\" beanIdRef=\"commonEventHeader\" />\n"
+                        + "      <jb:wiring property=\"pnfRegistrationFields\" beanIdRef=\"pnfRegistrationFields\" />\n"
+                        + "   </jb:bean>\n"
+                        + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader\""
+                        + " beanId=\"commonEventHeader\" createOnElement=\"vesevent\">\n"
+                        + "<jb:expression property=\"version\">"
+                        + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Version._4_0_1</jb:expression> \n"
+                        + "<jb:expression property=\"eventType\">\"pnfRegistration\"</jb:expression>\n"
+                        + "<jb:expression property=\"vesEventListenerVersion\">"
+                        + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.VesEventListenerVersion._7_0_1"
+                        + "</jb:expression>\n"
+                        + "       <jb:expression property=\"eventId\" execOnElement=\"vesevent\">"
+                        + "\"registration_\"+commonEventHeader.ts1</jb:expression>\n"
+                        + "<jb:expression property=\"reportingEntityName\">\"VESMapper\"</jb:expression>\n"
+                        + "      <jb:expression property=\"domain\">"
+                        + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Domain.PNF_REGISTRATION"
+                        + "</jb:expression>\n"
+                        + "      <jb:expression property=\"eventName\" execOnElement=\"vesevent\">"
+                        + "commonEventHeader.domain</jb:expression>\n"
+                        + "<jb:value property=\"sequence\" data=\"0\" default=\"0\" decoder=\"Long\" />\n"
+                        + "<jb:expression property=\"lastEpochMicrosec\" execOnElement=\"vesevent\">"
+                        + "commonEventHeader.ts1</jb:expression>\n"
+                        + "      <jb:expression property=\"startEpochMicrosec\" execOnElement=\"vesevent\">"
+                        + "commonEventHeader.ts1</jb:expression>\n"
+                        + "      <jb:expression property=\"priority\">"
+                        + "org.onap.dcaegen2.ves.domain.ves70.CommonEventHeader.Priority.NORMAL</jb:expression>\n"
+                        + "      <jb:value property=\"sourceName\" data=\"notification/message/target\" />\n"
+                        + "   </jb:bean>\n"
+                        + "   <jb:bean class=\"org.onap.dcaegen2.ves.domain.ves70.PnfRegistrationFields\""
+                        + " beanId=\"pnfRegistrationFields\" createOnElement=\"vesevent\">\n"
+                        + "     \n"
+                        + "       <jb:expression property=\"pnfRegistrationFieldsVersion\">"
+                        + "org.onap.dcaegen2.ves.domain.ves70.PnfRegistrationFields.PnfRegistrationFieldsVersion._2_0"
+                        + "</jb:expression>\n"
+                        + "      <jb:value property=\"serialNumber\" data=\"notification/message/content/onu/sn\" />\n"
+                        + "      \n" + "   </jb:bean>\n"
+                        + "</smooks-resource-list>");
+
+        try {
+            vesAdapterInitializer.setMappingFiles(testMap);
+
+            String[] identifiertest = CollectorConfigPropertyRetrieval
+                    .getProperyArray("identifier", "kvTest.json");
+            PowerMockito.mockStatic(CollectorConfigPropertyRetrieval.class);
+            PowerMockito.when(CollectorConfigPropertyRetrieval
+                    .getProperyArray("identifier", null))
+                    .thenReturn(identifiertest);
+
+            String actualResult = universalVesAdapter
+                    .transform(incomingJsonString.toString());
+            assertNotNull(actualResult);
+            assertNotEquals("", actualResult);
+        } catch (VesException exception) {
+            errorLogger.error("Error occurred : {}", exception);
+        }
+    }
+}