fix sonar issue and additional test 21/32421/1
authorVijay VK <vv770d@att.com>
Wed, 21 Feb 2018 16:52:31 +0000 (16:52 +0000)
committerVENKATESH KUMAR <vv770d@att.com>
Wed, 21 Feb 2018 16:53:15 +0000 (11:53 -0500)
Change-Id: If32e2319c71b947b7e5c68410f32b19ba5ac8125
Signed-off-by: VENKATESH KUMAR <vv770d@att.com>
Issue-ID: DCAEGEN2-227

src/main/java/org/onap/dcae/commonFunction/EventProcessor.java
src/main/java/org/onap/dcae/controller/FetchDynamicConfig.java
src/main/java/org/onap/dcae/restapi/RestfulCollectorServlet.java
src/test/java/org/onap/dcae/vestest/TestCommonStartup.java
src/test/java/org/onap/dcae/vestest/TestEventReceipt.java
src/test/java/org/onap/dcae/vestest/TestFetchConfig.java

index 6811c67..462287e 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.dcae.commonFunction;
-
-import com.att.nsa.clock.SaClock;
-import com.att.nsa.logging.LoggingContext;
-import com.att.nsa.logging.log4j.EcompFields;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonParser;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.FileReader;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.TimeZone;
-
-public class EventProcessor implements Runnable {
-
-       private static final Logger log = LoggerFactory.getLogger(EventProcessor.class);
-       private static final String EVENT_LITERAL = "event";
-       private static final String COMMON_EVENT_HEADER = "commonEventHeader";
-
-       private static HashMap<String, String[]> streamid_hash = new HashMap<String, String[]>();
-       public JSONObject event;
-
-       public EventProcessor() {
-               log.debug("EventProcessor: Default Constructor");
-
-               String[] list = CommonStartup.streamid.split("\\|");
-               for (String aList : list) {
-                       String domain = aList.split("=")[0];
-                       // String streamIdList[] = list[i].split("=")[1].split(",");
-                       String[] streamIdList = aList.substring(aList.indexOf('=') + 1).split(",");
-
-                       log.debug(String.format("Domain: %s streamIdList:%s", domain, Arrays.toString(streamIdList)));
-                       streamid_hash.put(domain, streamIdList);
-               }
-
-       }
-
-       @Override
-       public void run() {
-
-               try {
-
-                       event = CommonStartup.fProcessingInputQueue.take();
-                       log.info("QueueSize:" + CommonStartup.fProcessingInputQueue.size()+  "\tEventProcessor\tRemoving element: " + event );
-
-                       // EventPublisher Ep=new EventPublisher();
-                       while (event != null) {
-                               // As long as the producer is running we remove elements from
-                               // the queue.
-
-                               // UUID uuid =
-                               // UUID.fromString(event.get("VESuniqueId").toString());
-                               String uuid = event.get("VESuniqueId").toString();
-                               LoggingContext localLC = VESLogger.getLoggingContextForThread(uuid);
-                               localLC.put(EcompFields.kBeginTimestampMs, SaClock.now());
-
-                               log.debug("event.VESuniqueId" + event.get("VESuniqueId") + "event.commonEventHeader.domain:"
-                                               + event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER).getString("domain"));
-                               String[] streamIdList = streamid_hash
-                                               .get(event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER).getString("domain"));
-                               log.debug("streamIdList:" + streamIdList);
-
-                               if (streamIdList.length == 0) {
-                                       log.error("No StreamID defined for publish - Message dropped" + event);
-                               } else {
-                                       for (String aStreamIdList : streamIdList) {
-                                               log.info("Invoking publisher for streamId:" + aStreamIdList);
-                                               this.overrideEvent();
-                                               //EventPublisher.getInstance(aStreamIdList).sendEvent(event);
-                                               EventPublisherHash.getInstance().sendEvent(event, aStreamIdList);
-
-                                       }
-                               }
-                               log.debug("Message published" + event);
-                               event = CommonStartup.fProcessingInputQueue.take();
-                               // log.info("EventProcessor\tRemoving element: " +
-                               // this.queue.remove());
-                       }
-               } catch (InterruptedException e) {
-                       log.error("EventProcessor InterruptedException" + e.getMessage());
-               }
-
-       }
-
-       @SuppressWarnings({ "unchecked", "rawtypes" })
-       public void overrideEvent() {
-               // Set collector timestamp in event payload before publish
-               final Date currentTime = new Date();
-               final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM dd yyyy hh:mm:ss z");
-               sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
-
-               JSONObject collectorTimeStamp = new JSONObject().put("collectorTimeStamp", sdf.format(currentTime));
-               JSONObject commonEventHeaderkey = event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER);
-               commonEventHeaderkey.put("internalHeaderFields", collectorTimeStamp);
-               event.getJSONObject(EVENT_LITERAL).put(COMMON_EVENT_HEADER, commonEventHeaderkey);
-
-               if (CommonStartup.eventTransformFlag == 1) {
-                       // read the mapping json file
-                       final JsonParser parser = new JsonParser();
-                       FileReader fr = null;
-                       try {
-                               fr = new FileReader("./etc/eventTransform.json");
-                               final JsonArray jo = (JsonArray) parser.parse(fr);
-                               log.info("parse eventTransform.json");
-                               // now convert to org.json
-                               final String jsonText = jo.toString();
-                               final JSONArray topLevel = new JSONArray(jsonText);
-                               // log.info("topLevel == " + topLevel);
-
-                               Class[] paramJSONObject = new Class[1];
-                               paramJSONObject[0] = JSONObject.class;
-                               // load VESProcessors class at runtime
-                               Class cls = Class.forName("org.onap.dcae.commonFunction.ConfigProcessors");
-                               Constructor constr = cls.getConstructor(paramJSONObject);
-                               Object obj = constr.newInstance(event);
-
-                               for (int j = 0; j < topLevel.length(); j++) {
-                                       JSONObject filterObj = topLevel.getJSONObject(j).getJSONObject("filter");
-                                       Method method = cls.getDeclaredMethod("isFilterMet", paramJSONObject);
-                                       boolean filterMet = (boolean) method.invoke(obj, filterObj);
-                                       if (filterMet) {
-                                               final JSONArray processors = topLevel.getJSONObject(j).getJSONArray("processors");
-
-                                               // call the processor method
-                                               for (int i = 0; i < processors.length(); i++) {
-                                                       final JSONObject processorList = processors.getJSONObject(i);
-                                                       final String functionName = processorList.getString("functionName");
-                                                       final JSONObject args = processorList.getJSONObject("args");
-                                                       // final JSONObject filter =
-                                                       // processorList.getJSONObject("filter");
-
-                                                       log.info(String.format("functionName==%s | args==%s", functionName, args));
-                                                       // reflect method call
-                                                       method = cls.getDeclaredMethod(functionName, paramJSONObject);
-                                                       method.invoke(obj, args);
-                                               }
-                                       }
-                               }
-
-                       } catch (Exception e) {
-
-                               log.error("EventProcessor Exception" + e.getMessage() + e + e.getCause());
-                       } finally {
-                               // close the file
-                               if (fr != null) {
-                                       try {
-                                               fr.close();
-                                       } catch (IOException e) {
-                                               log.error("Error closing file reader stream : " + e.toString());
-                                       }
-
-                               }
-                       }
-               }
-               // Remove VESversion from event. This field is for internal use and must
-               // be removed after use.
-               if (event.has("VESversion"))
-                       event.remove("VESversion");
-
-               log.debug("Modified event:" + event);
-
-       }
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * PROJECT\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\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.dcae.commonFunction;\r
+\r
+import com.att.nsa.clock.SaClock;\r
+import com.att.nsa.logging.LoggingContext;\r
+import com.att.nsa.logging.log4j.EcompFields;\r
+import com.google.gson.JsonArray;\r
+import com.google.gson.JsonParser;\r
+import org.json.JSONArray;\r
+import org.json.JSONObject;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+import java.io.IOException;\r
+import java.io.FileReader;\r
+import java.lang.reflect.Constructor;\r
+import java.lang.reflect.Method;\r
+import java.text.SimpleDateFormat;\r
+import java.util.Arrays;\r
+import java.util.Date;\r
+import java.util.HashMap;\r
+import java.util.TimeZone;\r
+\r
+public class EventProcessor implements Runnable {\r
+\r
+       private static final Logger log = LoggerFactory.getLogger(EventProcessor.class);\r
+       private static final String EVENT_LITERAL = "event";\r
+       private static final String COMMON_EVENT_HEADER = "commonEventHeader";\r
+\r
+       private static HashMap<String, String[]> streamid_hash = new HashMap<String, String[]>();\r
+       public JSONObject event;\r
+\r
+       public EventProcessor() {\r
+               log.debug("EventProcessor: Default Constructor");\r
+\r
+               String[] list = CommonStartup.streamid.split("\\|");\r
+               for (String aList : list) {\r
+                       String domain = aList.split("=")[0];\r
+                       // String streamIdList[] = list[i].split("=")[1].split(",");\r
+                       String[] streamIdList = aList.substring(aList.indexOf('=') + 1).split(",");\r
+\r
+                       log.debug(String.format("Domain: %s streamIdList:%s", domain, Arrays.toString(streamIdList)));\r
+                       streamid_hash.put(domain, streamIdList);\r
+               }\r
+\r
+       }\r
+\r
+       @Override\r
+       public void run() {\r
+\r
+               try {\r
+\r
+                       event = CommonStartup.fProcessingInputQueue.take();\r
+                       log.info("QueueSize:" + CommonStartup.fProcessingInputQueue.size()+  "\tEventProcessor\tRemoving element: " + event );\r
+\r
+                       // EventPublisher Ep=new EventPublisher();\r
+                       while (event != null) {\r
+                               // As long as the producer is running we remove elements from\r
+                               // the queue.\r
+\r
+                               String uuid = event.get("VESuniqueId").toString();\r
+                               LoggingContext localLC = VESLogger.getLoggingContextForThread(uuid);\r
+                               localLC.put(EcompFields.kBeginTimestampMs, SaClock.now());\r
+\r
+                               log.debug("event.VESuniqueId" + event.get("VESuniqueId") + "event.commonEventHeader.domain:"\r
+                                               + event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER).getString("domain"));\r
+                               String[] streamIdList = streamid_hash\r
+                                               .get(event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER).getString("domain"));\r
+                               log.debug("streamIdList:" + streamIdList);\r
+\r
+                               if (streamIdList.length == 0) {\r
+                                       log.error("No StreamID defined for publish - Message dropped" + event);\r
+                               } else {\r
+                                       for (String aStreamIdList : streamIdList) {\r
+                                               log.info("Invoking publisher for streamId:" + aStreamIdList);\r
+                                               this.overrideEvent();\r
+                                               //EventPublisher.getInstance(aStreamIdList).sendEvent(event);\r
+                                               EventPublisherHash.getInstance().sendEvent(event, aStreamIdList);\r
+\r
+                                       }\r
+                               }\r
+                               log.debug("Message published" + event);\r
+                               event = CommonStartup.fProcessingInputQueue.take();\r
+\r
+                       }\r
+               } catch (InterruptedException e) {\r
+                       log.error("EventProcessor InterruptedException" + e.getMessage());\r
+                       Thread.currentThread().interrupt();\r
+               }\r
+\r
+       }\r
+\r
+       @SuppressWarnings({ "unchecked", "rawtypes" })\r
+       public void overrideEvent() {\r
+               // Set collector timestamp in event payload before publish\r
+               final Date currentTime = new Date();\r
+               final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM dd yyyy hh:mm:ss z");\r
+               sdf.setTimeZone(TimeZone.getTimeZone("GMT"));\r
+\r
+               JSONObject collectorTimeStamp = new JSONObject().put("collectorTimeStamp", sdf.format(currentTime));\r
+               JSONObject commonEventHeaderkey = event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER);\r
+               commonEventHeaderkey.put("internalHeaderFields", collectorTimeStamp);\r
+               event.getJSONObject(EVENT_LITERAL).put(COMMON_EVENT_HEADER, commonEventHeaderkey);\r
+\r
+               if (CommonStartup.eventTransformFlag == 1) {\r
+                       // read the mapping json file\r
+                       final JsonParser parser = new JsonParser();\r
+                       FileReader fr = null;\r
+                       try {\r
+                               fr = new FileReader("./etc/eventTransform.json");\r
+                               final JsonArray jo = (JsonArray) parser.parse(fr);\r
+                               log.info("parse eventTransform.json");\r
+                               // now convert to org.json\r
+                               final String jsonText = jo.toString();\r
+                               final JSONArray topLevel = new JSONArray(jsonText);\r
+                               // log.info("topLevel == " + topLevel);\r
+\r
+                               Class[] paramJSONObject = new Class[1];\r
+                               paramJSONObject[0] = JSONObject.class;\r
+                               // load VESProcessors class at runtime\r
+                               Class cls = Class.forName("org.onap.dcae.commonFunction.ConfigProcessors");\r
+                               Constructor constr = cls.getConstructor(paramJSONObject);\r
+                               Object obj = constr.newInstance(event);\r
+\r
+                               for (int j = 0; j < topLevel.length(); j++) {\r
+                                       JSONObject filterObj = topLevel.getJSONObject(j).getJSONObject("filter");\r
+                                       Method method = cls.getDeclaredMethod("isFilterMet", paramJSONObject);\r
+                                       boolean filterMet = (boolean) method.invoke(obj, filterObj);\r
+                                       if (filterMet) {\r
+                                               final JSONArray processors = topLevel.getJSONObject(j).getJSONArray("processors");\r
+\r
+                                               // call the processor method\r
+                                               for (int i = 0; i < processors.length(); i++) {\r
+                                                       final JSONObject processorList = processors.getJSONObject(i);\r
+                                                       final String functionName = processorList.getString("functionName");\r
+                                                       final JSONObject args = processorList.getJSONObject("args");\r
+                                       \r
+\r
+                                                       log.info(String.format("functionName==%s | args==%s", functionName, args));\r
+                                                       // reflect method call\r
+                                                       method = cls.getDeclaredMethod(functionName, paramJSONObject);\r
+                                                       method.invoke(obj, args);\r
+                                               }\r
+                                       }\r
+                               }\r
+\r
+                       } catch (Exception e) {\r
+\r
+                               log.error("EventProcessor Exception" + e.getMessage() + e + e.getCause());\r
+                       } finally {\r
+                               // close the file\r
+                               if (fr != null) {\r
+                                       try {\r
+                                               fr.close();\r
+                                       } catch (IOException e) {\r
+                                               log.error("Error closing file reader stream : " + e.toString());\r
+                                       }\r
+\r
+                               }\r
+                       }\r
+               }\r
+               // Remove VESversion from event. This field is for internal use and must\r
+               // be removed after use.\r
+               if (event.has("VESversion"))\r
+                       event.remove("VESversion");\r
+\r
+               log.debug("Modified event:" + event);\r
+\r
+       }\r
+}\r
index 95e9574..7b2e0b3 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.dcae.controller;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.json.JSONTokener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.Map;
-
-public class FetchDynamicConfig {
-
-       private static final Logger log = LoggerFactory.getLogger(FetchDynamicConfig.class);
-
-       public static String configFile = "/opt/app/KV-Configuration.json";
-       static String url;
-       static String retString;
-
-       public FetchDynamicConfig() {
-       }
-
-       public static void main(String[] args) {
-               Map<String, String> env = System.getenv();
-               for (Map.Entry<String, String> entry : env.entrySet()) {
-                       log.info("%s=%s%n", entry.getKey(), entry.getValue());
-               }
-
-               if (env.containsKey("CONSUL_HOST") && env.containsKey("CONFIG_BINDING_SERVICE")) {
-//                             && env.containsKey("HOSTNAME")) {
-                       log.info(">>>Dynamic configuration to be fetched from ConfigBindingService");
-                       url = env.get("CONSUL_HOST") + ":8500/v1/catalog/service/" + env.get("CONFIG_BINDING_SERVICE");
-
-                       retString = executecurl(url);
-                       // 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");
-                       }
-
-                       log.info("CONFIG_BINDING_SERVICE DNS RESOLVED:" + urlPart1);
-                       FetchDynamicConfig fc= new FetchDynamicConfig();
-                       if (env.containsKey("HOSTNAME"))
-                       {
-                               url = urlPart1 + "/service_component/" + env.get("HOSTNAME");
-                               retString = executecurl(url);
-                       }
-                       else if (env.containsKey("SERVICE_NAME"))
-                       {
-                               url = urlPart1 + "/service_component/" + env.get("SERVICE_NAME");
-                               retString = executecurl(url);
-                       }
-                       else
-                       {
-                               log.error("Service name environment variable - HOSTNAME/SERVICE_NAME not found within container ");
-                       }
-                       fc.writefile(retString);
-                       
-                       
-               } else {
-                       log.info(">>>Static configuration to be used");
-               }
-
-       }
-       
-       public void writefile (String retString)
-       {
-               log.info("URL to fetch configuration:" + url  + " Return String:" + retString);
-
-               
-               String indentedretstring=(new JSONObject(retString)).toString(4);
-               
-               try (FileWriter file = new FileWriter(FetchDynamicConfig.configFile)) {
-                       file.write(indentedretstring);
-
-                       log.info("Successfully Copied JSON Object to file /opt/app/KV-Configuration.json");
-               } catch (IOException e) {
-                       log.error("Error in writing configuration into file /opt/app/KV-Configuration.json " + retString, e);
-                       e.printStackTrace();
-               }
-               
-       }
-
-       public static String executecurl(String url) {
-
-               String[] command = { "curl", "-v", url };
-               ProcessBuilder process = new ProcessBuilder(command);
-               Process p;
-               String result = null;
-               try {
-                       p = process.start();
-                       InputStreamReader ipr = new InputStreamReader(p.getInputStream());
-                       BufferedReader reader = new BufferedReader(ipr);
-                       StringBuilder builder = new StringBuilder();
-                       String line;
-
-                       while ((line = reader.readLine()) != null) {
-                               builder.append(line);
-                       }
-                       result = builder.toString();
-                       log.info(result);
-
-                       reader.close();
-                       ipr.close();
-               } catch (IOException e) {
-                       log.error("error", e);
-                       e.printStackTrace();
-               }
-               return result;
-
-       }
-
-}
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * PROJECT\r
+ * ================================================================================\r
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.\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.dcae.controller;\r
+\r
+import org.json.JSONArray;\r
+import org.json.JSONObject;\r
+import org.json.JSONTokener;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.FileWriter;\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+import java.util.Map;\r
+\r
+public class FetchDynamicConfig {\r
+\r
+       private static final Logger log = LoggerFactory.getLogger(FetchDynamicConfig.class);\r
+\r
+       public static String configFile = "/opt/app/KV-Configuration.json";\r
+       static String url;\r
+       public static String retString;\r
+       public static String retCBSString;              \r
+       public static Map<String, String> env;\r
+       \r
+       public FetchDynamicConfig() {\r
+       }\r
+\r
+       public static void main(String[] args) {\r
+               \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
+               //Write data returned into configFile for LoadDynamicConfig process to pickup\r
+               FetchDynamicConfig fc= new FetchDynamicConfig();\r
+               fc.writefile(retCBSString);\r
+       }\r
+       \r
+       public  static void getconsul()\r
+       {\r
+               \r
+               env = System.getenv();\r
+               for (Map.Entry<String, String> entry : env.entrySet()) {\r
+                       log.info( entry.getKey() + ":"+ entry.getValue());\r
+               }\r
+\r
+               if (env.containsKey("CONSUL_HOST") && env.containsKey("CONFIG_BINDING_SERVICE")) {\r
+//                             && env.containsKey("HOSTNAME")) {\r
+                       log.info(">>>Dynamic configuration to be fetched from ConfigBindingService");\r
+                       url = env.get("CONSUL_HOST") + ":8500/v1/catalog/service/" + env.get("CONFIG_BINDING_SERVICE");\r
+\r
+                       retString = executecurl(url);\r
+                       \r
+                       \r
+               } else {\r
+                       log.info(">>>Static configuration to be used");\r
+               }\r
+\r
+               \r
+       }\r
+\r
+       public static void getCBS()\r
+       {\r
+\r
+               env = System.getenv();\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
+                       urlPart1 = cbsjobj.getString("ServiceAddress") + ":" + cbsjobj.getInt("ServicePort");\r
+               }\r
+\r
+               log.info("CONFIG_BINDING_SERVICE DNS RESOLVED:" + urlPart1);\r
+               \r
+               if (env.containsKey("HOSTNAME"))\r
+               {\r
+                       url = urlPart1 + "/service_component/" + env.get("HOSTNAME");\r
+                       retCBSString = executecurl(url);\r
+               }\r
+               else if (env.containsKey("SERVICE_NAME"))\r
+               {\r
+                       url = urlPart1 + "/service_component/" + env.get("SERVICE_NAME");\r
+                       retCBSString = executecurl(url);\r
+               }\r
+               else\r
+               {\r
+                       log.error("Service name environment variable - HOSTNAME/SERVICE_NAME not found within container ");\r
+               }\r
+       \r
+       }\r
+       \r
+       public void writefile (String retCBSString)\r
+       {\r
+               log.info("URL to fetch configuration:" + url  + " Return String:" + retCBSString);\r
+\r
+               \r
+               String indentedretstring=(new JSONObject(retCBSString)).toString(4);\r
+               \r
+               try (FileWriter file = new FileWriter(FetchDynamicConfig.configFile)) {\r
+                       file.write(indentedretstring);\r
+\r
+                       log.info("Successfully Copied JSON Object to file " + configFile);\r
+               } catch (IOException e) {\r
+                       log.error("Error in writing configuration into file " + configFile  + retString +  e.getMessage());\r
+                       e.printStackTrace();\r
+               }\r
+               \r
+       }\r
+\r
+       public static String executecurl(String url) {\r
+\r
+               String[] command = { "curl", "-v", url };\r
+               ProcessBuilder process = new ProcessBuilder(command);\r
+               Process p;\r
+               String result = null;\r
+               try {\r
+                       p = process.start();\r
+                       InputStreamReader ipr = new InputStreamReader(p.getInputStream());\r
+                       BufferedReader reader = new BufferedReader(ipr);\r
+                       StringBuilder builder = new StringBuilder();\r
+                       String line;\r
+\r
+                       while ((line = reader.readLine()) != null) {\r
+                               builder.append(line);\r
+                       }\r
+                       result = builder.toString();\r
+                       log.info(result);\r
+\r
+                       reader.close();\r
+                       ipr.close();\r
+               } catch (IOException e) {\r
+                       log.error("error", e);\r
+                       e.printStackTrace();\r
+               }\r
+               return result;\r
+\r
+       }\r
+\r
+}\r
index 1fa3c41..7aa82c9 100644 (file)
-
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.dcae.restapi;
-
-import java.io.IOException;
-import java.net.URL;
-
-import javax.servlet.ServletException;
-
-import org.apache.tomcat.util.codec.binary.Base64;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.VESLogger;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.att.nsa.apiServer.CommonServlet;
-import com.att.nsa.configs.ConfigDbException;
-import com.att.nsa.drumlin.service.framework.DrumlinErrorHandler;
-import com.att.nsa.drumlin.service.framework.context.DrumlinRequestContext;
-import com.att.nsa.drumlin.service.framework.routing.DrumlinRequestRouter;
-import com.att.nsa.drumlin.service.framework.routing.playish.DrumlinPlayishRoutingFileSource;
-import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
-import com.att.nsa.drumlin.till.nv.rrNvReadable;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
-import com.att.nsa.security.NsaAuthenticator;
-
-import com.att.nsa.security.authenticators.SimpleAuthenticator;
-import com.att.nsa.security.db.simple.NsaSimpleApiKey;
-
-
-public class RestfulCollectorServlet extends CommonServlet
-{
-       String authid=null;
-       String authpwd=null;
-       public String authlist;
-       
-       public RestfulCollectorServlet ( rrNvReadable settings ) throws loadException, missingReqdSetting
-       {
-               super ( settings, "collector", false );
-               authlist = settings.getString(CommonStartup.KSETTING_AUTHLIST,null);
-       }
-
-
-
-
-       /**
-        * This is called once at server start. Use it to init any shared objects and setup the route mapping.
-        */
-       @Override
-       protected void servletSetup () throws rrNvReadable.missingReqdSetting, rrNvReadable.invalidSettingValue, ServletException
-       {
-               super.servletSetup ();
-
-               try
-               {
-                       // the base class provides a bunch of things like API authentication and ECOMP compliant
-                       // logging. The Restful Collector likely doesn't need API authentication, so for now,
-                       // we init the base class services with an in-memory (and empty!) config DB.
-                       commonServletSetup ( ConfigDbType.MEMORY );
-                       
-                       VESLogger.setUpEcompLogging();
-
-                       // setup the servlet routing and error handling
-                       final DrumlinRequestRouter drr = getRequestRouter ();
-
-                       // you can tell the request router what to do when a particular kind of exception is thrown.
-                       drr.setHandlerForException( IllegalArgumentException.class, new DrumlinErrorHandler()
-                       {
-                               @Override
-                               public void handle ( DrumlinRequestContext ctx, Throwable cause )
-                               {
-                                       sendJsonReply ( ctx, HttpStatusCodes.k400_badRequest, cause.getMessage() );
-                               }
-                       });
-
-                       // load the routes from the config file
-                       final URL routes = findStream ( "routes.conf" );
-                       if ( routes == null ) throw new rrNvReadable.missingReqdSetting ( "No routing configuration." );
-                       final DrumlinPlayishRoutingFileSource drs = new DrumlinPlayishRoutingFileSource ( routes );
-                       drr.addRouteSource ( drs );
-
-                       if (CommonStartup.authflag > 0) {
-                               NsaAuthenticator<NsaSimpleApiKey> NsaAuth;
-                               NsaAuth = AuthlistHandler(authlist);
-                               
-                               this.getSecurityManager().addAuthenticator(NsaAuth);
-                       }
-                       
-                       log.info ( "Restful Collector Servlet is up." );
-               }
-               catch ( SecurityException e )
-               {
-                       throw new ServletException ( e );
-               }
-               catch ( IOException e )
-               {
-                       throw new ServletException ( e );
-               }
-               catch ( ConfigDbException e )
-               {
-                       throw new ServletException ( e );
-               }
-       }
-
-       public NsaAuthenticator<NsaSimpleApiKey> AuthlistHandler (String authlist)
-       {
-               NsaAuthenticator<NsaSimpleApiKey> NsaAuth = new SimpleAuthenticator ();
-               if (authlist != null)
-               {
-                       String authpair[] = authlist.split("\\|");
-                       for (String pair: authpair) {           
-                                       String lineid[] = pair.split(",");
-                                       String listauthid =  lineid[0]; 
-                                       String listauthpwd =  new String(Base64.decodeBase64(lineid[1]));
-                                       ((SimpleAuthenticator) NsaAuth).add(listauthid,listauthpwd);
-                   }
-                       
-               }
-               else if (authid != null)
-               {
-                       ((SimpleAuthenticator) NsaAuth).add(authid,authpwd);
-               }
-               else
-               {
-                       //add a default test account
-                       ((SimpleAuthenticator) NsaAuth).add("admin","collectorpasscode");
-               }
-               return NsaAuth;
-
-       }
-       
-
-       private static final long serialVersionUID = 1L;
-       private static final Logger log = LoggerFactory.getLogger ( RestfulCollectorServlet.class );
-}
+\r
+/*\r
+ * ============LICENSE_START=======================================================\r
+ * PROJECT\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\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.dcae.restapi;\r
+\r
+import java.io.IOException;\r
+import java.net.URL;\r
+\r
+import javax.servlet.ServletException;\r
+\r
+import org.apache.tomcat.util.codec.binary.Base64;\r
+import org.onap.dcae.commonFunction.CommonStartup;\r
+import org.onap.dcae.commonFunction.VESLogger;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+import com.att.nsa.apiServer.CommonServlet;\r
+import com.att.nsa.configs.ConfigDbException;\r
+import com.att.nsa.drumlin.service.framework.DrumlinErrorHandler;\r
+import com.att.nsa.drumlin.service.framework.context.DrumlinRequestContext;\r
+import com.att.nsa.drumlin.service.framework.routing.DrumlinRequestRouter;\r
+import com.att.nsa.drumlin.service.framework.routing.playish.DrumlinPlayishRoutingFileSource;\r
+import com.att.nsa.drumlin.service.standards.HttpStatusCodes;\r
+import com.att.nsa.drumlin.till.nv.rrNvReadable;\r
+import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;\r
+import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;\r
+import com.att.nsa.security.NsaAuthenticator;\r
+\r
+import com.att.nsa.security.authenticators.SimpleAuthenticator;\r
+import com.att.nsa.security.db.simple.NsaSimpleApiKey;\r
+\r
+\r
+public class RestfulCollectorServlet extends CommonServlet\r
+{\r
+\r
+       public static String authlist;\r
+       \r
+       public RestfulCollectorServlet ( rrNvReadable settings ) throws loadException, missingReqdSetting\r
+       {\r
+               super ( settings, "collector", false );\r
+               authlist = settings.getString(CommonStartup.KSETTING_AUTHLIST,null);\r
+       }\r
+\r
+\r
+\r
+\r
+       /**\r
+        * This is called once at server start. Use it to init any shared objects and setup the route mapping.\r
+        */\r
+       @Override\r
+       protected void servletSetup () throws rrNvReadable.missingReqdSetting, rrNvReadable.invalidSettingValue, ServletException\r
+       {\r
+               super.servletSetup ();\r
+\r
+               try\r
+               {\r
+                       // the base class provides a bunch of things like API authentication and ECOMP compliant\r
+                       // logging. The Restful Collector likely doesn't need API authentication, so for now,\r
+                       // we init the base class services with an in-memory (and empty!) config DB.\r
+                       commonServletSetup ( ConfigDbType.MEMORY );\r
+                       \r
+                       VESLogger.setUpEcompLogging();\r
+\r
+                       // setup the servlet routing and error handling\r
+                       final DrumlinRequestRouter drr = getRequestRouter ();\r
+\r
+                       // you can tell the request router what to do when a particular kind of exception is thrown.\r
+                       drr.setHandlerForException( IllegalArgumentException.class, new DrumlinErrorHandler()\r
+                       {\r
+                               @Override\r
+                               public void handle ( DrumlinRequestContext ctx, Throwable cause )\r
+                               {\r
+                                       sendJsonReply ( ctx, HttpStatusCodes.k400_badRequest, cause.getMessage() );\r
+                               }\r
+                       });\r
+\r
+                       // load the routes from the config file\r
+                       final URL routes = findStream ( "routes.conf" );\r
+                       if ( routes == null ) throw new rrNvReadable.missingReqdSetting ( "No routing configuration." );\r
+                       final DrumlinPlayishRoutingFileSource drs = new DrumlinPlayishRoutingFileSource ( routes );\r
+                       drr.addRouteSource ( drs );\r
+\r
+                       if (CommonStartup.authflag > 0) {\r
+                               NsaAuthenticator<NsaSimpleApiKey> NsaAuth;\r
+                               NsaAuth = AuthlistHandler(authlist);\r
+                               \r
+                               this.getSecurityManager().addAuthenticator(NsaAuth);\r
+                       }\r
+                       \r
+                       log.info ( "Restful Collector Servlet is up." );\r
+               }\r
+               catch ( SecurityException e )\r
+               {\r
+                       throw new ServletException ( e );\r
+               }\r
+               catch ( IOException e )\r
+               {\r
+                       throw new ServletException ( e );\r
+               }\r
+               catch ( ConfigDbException e )\r
+               {\r
+                       throw new ServletException ( e );\r
+               }\r
+       }\r
+\r
+       public NsaAuthenticator<NsaSimpleApiKey> AuthlistHandler (String authlist)\r
+       {\r
+               NsaAuthenticator<NsaSimpleApiKey> NsaAuth = new SimpleAuthenticator ();\r
+               if (authlist != null)\r
+               {\r
+                       String authpair[] = authlist.split("\\|");\r
+                       for (String pair: authpair) {           \r
+                                       String lineid[] = pair.split(",");\r
+                                       String listauthid =  lineid[0]; \r
+                                       String listauthpwd =  new String(Base64.decodeBase64(lineid[1]));\r
+                                       ((SimpleAuthenticator) NsaAuth).add(listauthid,listauthpwd);\r
+                   }\r
+                       \r
+               }\r
+               else\r
+               {\r
+                       //add a default test account\r
+                       ((SimpleAuthenticator) NsaAuth).add("admin","collectorpasscode");\r
+               }\r
+               return NsaAuth;\r
+\r
+       }\r
+       \r
+\r
+       private static final long serialVersionUID = 1L;\r
+       private static final Logger log = LoggerFactory.getLogger ( RestfulCollectorServlet.class );\r
+}\r
index 0cf9075..aa56c61 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.dcae.vestest;
-
-import java.io.FileReader;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Map;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.EventProcessor;
-import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;
-import org.onap.dcae.restapi.RestfulCollectorServlet;
-
-import com.att.nsa.cmdLine.NsaCommandLineUtil;
-import com.att.nsa.drumlin.service.framework.DrumlinServlet;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;
-import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
-import com.att.nsa.security.NsaAuthenticator;
-import com.att.nsa.security.authenticators.SimpleAuthenticator;
-import com.att.nsa.security.db.simple.NsaSimpleApiKey;
-import com.google.gson.JsonParser;
-import com.att.nsa.drumlin.till.nv.impl.nvPropertiesFile;
-import com.att.nsa.drumlin.till.nv.impl.nvReadableStack;
-import com.att.nsa.drumlin.till.nv.impl.nvReadableTable;
-
-
-public class TestCommonStartup {
-
-        String payload = null;
-        @Before
-        public void setUp() throws Exception {
-
-                // process command line arguments
-                payload = new JsonParser().parse(new FileReader("src/test/resources/VES_valid.txt")).toString();
-                CommonStartup.fProcessingInputQueue = new LinkedBlockingQueue<JSONObject> (CommonStartup.KDEFAULT_MAXQUEUEDEVENTS);
-        }
-
-        @After
-        public void tearDown() throws Exception {
-
-        }
-
-        @Test
-        public void testCommonStartupload() {
-
-                String args[] = { "junittest" };
-                final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine(args, true);
-                final String config = NsaCommandLineUtil.getSetting(argMap, "c", "collector.properties");
-                final URL settingStream = DrumlinServlet.findStream(config, CommonStartup.class);
-
-                final nvReadableStack settings = new nvReadableStack();
-                try {
-                        settings.push(new nvPropertiesFile(settingStream));
-                } catch (loadException e) {
-                        // TODO Auto-generated catch block
-                        e.printStackTrace();
-                }
-                settings.push(new nvReadableTable(argMap));
-                Assert.assertEquals("true", "true");
-        }
-
-        @Test
-        public void testhandleevent() {
-                JSONArray jsonArrayMod = new JSONArray().put(new JSONObject(payload));
-                try {
-
-
-                        CommonStartup.handleEvents (jsonArrayMod);
-                } catch ( JSONException | QueueFullException | IOException e) {
-                        // TODO Auto-generated catch block
-                        //e.printStackTrace();
-                        System.out.println("junit reported:" + e.getMessage());
-                }
-                Assert.assertEquals("true", "true");
-        }
-
-
-/*
-        @Test
-        public void testServlet()  {
-                try
-                {
-                        RestfulCollectorServlet rsv = new RestfulCollectorServlet(null);
-                }
-                catch (NullPointerException|loadException| missingReqdSetting e){
-                        System.out.println("junit reported:" + e.getMessage());
-                }
-                Assert.assertEquals("true", "true");
-        }
-*/
-
-
-        @Test
-        public void testEventProcessorinstantiation()
-        {
-                CommonStartup.streamid="fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling";
-                EventProcessor ep = new EventProcessor ();
-                Thread epThread=new Thread(ep);
-                epThread.start();
-                 Assert.assertEquals("true", "true");
-                epThread.stop();
-
-        }
-
-        @Test
-        public void testAuthListHandler()
-        {
-               
-               final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine ( new String[0], true );
-                       final String config = NsaCommandLineUtil.getSetting ( argMap, "c", "collector.properties" );
-                       final URL settingStream = DrumlinServlet.findStream ( config, CommonStartup.class );
-
-                       final nvReadableStack settings = new nvReadableStack ();
-                       try {
-                               settings.push ( new nvPropertiesFile ( settingStream ) );
-                               settings.push ( new nvReadableTable ( argMap ) );
-                       } catch (loadException e1) {
-                               // TODO Auto-generated catch block
-                               e1.printStackTrace();
-                       }
-                       
-                       
-               RestfulCollectorServlet rsv = null;
-               NsaAuthenticator<NsaSimpleApiKey> NsaAuth = null;
-               Boolean flag = false;
-                   try
-                   {
-                           rsv = new RestfulCollectorServlet(settings);
-                   }
-                   catch (NullPointerException|loadException| missingReqdSetting e){
-                           System.out.println("junit reported:" + e.getMessage());
-                   }
-                   String authlist = "secureid,IWRjYWVSb2FkbTEyMyEt|sample1,c2FtcGxlMQ==|vdnsagg,dmRuc2FnZw==";
-                   NsaAuth = rsv.AuthlistHandler(authlist);
-                   if (NsaAuth != null)
-                   {
-                       flag = true;
-                   }
-                Assert.assertEquals(true, flag);
-              
-
-        }
-}
-
-
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * PROJECT\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\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
+package org.onap.dcae.vestest;\r
+\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.net.URL;\r
+import java.util.Map;\r
+import java.util.concurrent.LinkedBlockingQueue;\r
+\r
+import org.json.JSONArray;\r
+import org.json.JSONException;\r
+import org.json.JSONObject;\r
+import org.junit.After;\r
+import org.junit.Assert;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.onap.dcae.commonFunction.CommonStartup;\r
+import org.onap.dcae.commonFunction.EventProcessor;\r
+import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;\r
+import org.onap.dcae.restapi.RestfulCollectorServlet;\r
+\r
+import com.att.nsa.cmdLine.NsaCommandLineUtil;\r
+import com.att.nsa.drumlin.service.framework.DrumlinServlet;\r
+import com.att.nsa.drumlin.till.nv.rrNvReadable.loadException;\r
+import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;\r
+import com.att.nsa.security.NsaAuthenticator;\r
+import com.att.nsa.security.authenticators.SimpleAuthenticator;\r
+import com.att.nsa.security.db.simple.NsaSimpleApiKey;\r
+import com.google.gson.JsonParser;\r
+import com.att.nsa.drumlin.till.nv.impl.nvPropertiesFile;\r
+import com.att.nsa.drumlin.till.nv.impl.nvReadableStack;\r
+import com.att.nsa.drumlin.till.nv.impl.nvReadableTable;\r
+\r
+\r
+public class TestCommonStartup {\r
+\r
+        String payload = null;\r
+        @Before\r
+        public void setUp() throws Exception {\r
+\r
+                // process command line arguments\r
+                payload = new JsonParser().parse(new FileReader("src/test/resources/VES_valid.txt")).toString();\r
+                CommonStartup.fProcessingInputQueue = new LinkedBlockingQueue<JSONObject> (CommonStartup.KDEFAULT_MAXQUEUEDEVENTS);\r
+        }\r
+\r
+        @After\r
+        public void tearDown() throws Exception {\r
+\r
+        }\r
+\r
+        @Test\r
+        public void testCommonStartupload() {\r
+\r
+                String args[] = { "junittest" };\r
+                final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine(args, true);\r
+                final String config = NsaCommandLineUtil.getSetting(argMap, "c", "collector.properties");\r
+                final URL settingStream = DrumlinServlet.findStream(config, CommonStartup.class);\r
+\r
+                final nvReadableStack settings = new nvReadableStack();\r
+                try {\r
+                        settings.push(new nvPropertiesFile(settingStream));\r
+                } catch (loadException e) {\r
+                        // TODO Auto-generated catch block\r
+                        e.printStackTrace();\r
+                }\r
+                settings.push(new nvReadableTable(argMap));\r
+                Assert.assertEquals("true", "true");\r
+        }\r
+\r
+        @Test\r
+        public void testhandleevent() {\r
+                JSONArray jsonArrayMod = new JSONArray().put(new JSONObject(payload));\r
+                try {\r
+\r
+\r
+                        CommonStartup.handleEvents (jsonArrayMod);\r
+                } catch ( JSONException | QueueFullException | IOException e) {\r
+                        // TODO Auto-generated catch block\r
+                        //e.printStackTrace();\r
+                        System.out.println("junit reported:" + e.getMessage());\r
+                }\r
+                Assert.assertEquals("true", "true");\r
+        }\r
+\r
+\r
+/*\r
+        @Test\r
+        public void testServlet()  {\r
+                try\r
+                {\r
+                        RestfulCollectorServlet rsv = new RestfulCollectorServlet(null);\r
+                }\r
+                catch (NullPointerException|loadException| missingReqdSetting e){\r
+                        System.out.println("junit reported:" + e.getMessage());\r
+                }\r
+                Assert.assertEquals("true", "true");\r
+        }\r
+*/\r
+\r
+\r
+     \r
+               @Test\r
+        public void testEventProcessorinstantiation()\r
+        {\r
+                CommonStartup.streamid="fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling";\r
+                EventProcessor ep = new EventProcessor ();\r
+                Thread epThread=new Thread(ep);\r
+                epThread.start();\r
+                 Assert.assertEquals("true", "true");\r
+                epThread.interrupt();\r
+\r
+        }\r
+\r
+        @Test\r
+        public void testAuthListHandler()\r
+        {\r
+               \r
+               final Map<String, String> argMap = NsaCommandLineUtil.processCmdLine ( new String[0], true );\r
+                       final String config = NsaCommandLineUtil.getSetting ( argMap, "c", "collector.properties" );\r
+                       final URL settingStream = DrumlinServlet.findStream ( config, CommonStartup.class );\r
+\r
+                       final nvReadableStack settings = new nvReadableStack ();\r
+                       try {\r
+                               settings.push ( new nvPropertiesFile ( settingStream ) );\r
+                               settings.push ( new nvReadableTable ( argMap ) );\r
+                       } catch (loadException e1) {\r
+                               // TODO Auto-generated catch block\r
+                               e1.printStackTrace();\r
+                       }\r
+                       \r
+                       \r
+               RestfulCollectorServlet rsv = null;\r
+               NsaAuthenticator<NsaSimpleApiKey> NsaAuth = null;\r
+               Boolean flag = false;\r
+                   try\r
+                   {\r
+                           rsv = new RestfulCollectorServlet(settings);\r
+                   }\r
+                   catch (NullPointerException|loadException| missingReqdSetting e){\r
+                           System.out.println("junit reported:" + e.getMessage());\r
+                   }\r
+                   String authlist = "secureid,IWRjYWVSb2FkbTEyMyEt|sample1,c2FtcGxlMQ==|vdnsagg,dmRuc2FnZw==";\r
+                   NsaAuth = rsv.AuthlistHandler(authlist);\r
+                   if (NsaAuth != null)\r
+                   {\r
+                       flag = true;\r
+                   }\r
+                Assert.assertEquals(true, flag);\r
+              \r
+\r
+        }\r
+}\r
+\r
+\r
index 668c718..3af66fb 100644 (file)
@@ -34,6 +34,7 @@ import org.onap.dcae.commonFunction.CommonStartup;
 import org.onap.dcae.commonFunction.CommonStartup.QueueFullException;\r
 import org.onap.dcae.commonFunction.CustomExceptionLoader;\r
 import org.onap.dcae.restapi.endpoints.EventReceipt;\r
+import org.onap.dcae.restapi.endpoints.Ui;\r
 \r
 import com.att.nsa.apiServer.endpoints.NsaBaseEndpoint;\r
 import com.att.nsa.drumlin.service.framework.context.DrumlinRequestContext;\r
@@ -120,4 +121,18 @@ public class TestEventReceipt extends NsaBaseEndpoint {
                }\r
                assertEquals(true, true);\r
        }\r
+       \r
+       @Test\r
+       public void testUI() {\r
+\r
+        try {\r
+               Ui.hello(null);\r
+        }\r
+        catch (Exception e)\r
+        {\r
+               //As context object is null, handling null pointer exception.\r
+               Log.debug("Response object creation failure");\r
+        }\r
+               assertEquals(true, true);\r
+       }\r
 }\r
index ed3e108..2f18e82 100644 (file)
-/*-
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.dcae.vestest;
-
-import static org.junit.Assert.*;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.FileReader;
-import java.io.IOException;
-import org.json.JSONObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonObject;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.CommonStartup;
-import org.onap.dcae.commonFunction.DmaapPropertyReader;
-import org.onap.dcae.commonFunction.EventProcessor;
-import org.onap.dcae.commonFunction.EventPublisherHash;
-import org.onap.dcae.controller.FetchDynamicConfig;
-
-
-public class TestFetchConfig {
-
-       JSONObject jsonObject;
-       
-       @Before
-       public void setUp() throws Exception {
-
-
-       }
-
-       @After
-       public void tearDown() throws Exception {
-       }
-       
-
-       
-       @Test
-       public void testwritefile() {
-               Boolean flag = false;
-               
-               FetchDynamicConfig fc = new FetchDynamicConfig();
-               FetchDynamicConfig.configFile = "src/test/resources/controller-config_formatted_op.json";
-
-               
-               
-               try{
-                        JsonParser parser = new JsonParser();
-                       FileReader fr = new FileReader ("src/test/resources/controller-config_singleline_ip.json"  );
-                       final JsonObject jo =  (JsonObject) parser.parse (fr);
-                       final String jsonText = jo.toString ();
-                       jsonObject = new JSONObject ( jsonText );
-                       fc.writefile(jsonObject.toString());
-               }
-               catch(Exception e){
-                       System.out.println("Exception while opening the file");
-                       e.printStackTrace();
-               }
-               if(jsonObject.has("streams_publishes"))
-               {
-                       flag = true;
-               }
-               
-               assertEquals(true, flag);
-               
-       }
-
-
-}
-
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * PROJECT\r
+ * ================================================================================\r
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.\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
+package org.onap.dcae.vestest;\r
+\r
+import static org.junit.Assert.*;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import java.io.FileReader;\r
+import java.io.IOException;\r
+import java.util.Map;\r
+import java.util.Properties;\r
+\r
+import org.json.JSONObject;\r
+import com.google.gson.JsonParser;\r
+import com.google.gson.JsonObject;\r
+\r
+import org.junit.After;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.onap.dcae.commonFunction.CommonStartup;\r
+import org.onap.dcae.commonFunction.DmaapPropertyReader;\r
+import org.onap.dcae.commonFunction.EventProcessor;\r
+import org.onap.dcae.commonFunction.EventPublisherHash;\r
+import org.onap.dcae.controller.FetchDynamicConfig;\r
+\r
+\r
+public class TestFetchConfig {\r
+\r
+       JSONObject jsonObject;\r
+       \r
+       @Before\r
+       public void setUp() throws Exception {\r
+\r
+               \r
+               System.setProperty("CONSUL_HOST", "localhost");\r
+               System.setProperty("CONFIG_BINDING_SERVICE", "localhost");\r
+               System.setProperty("HOSTNAME", "localhost");\r
+       }\r
+\r
+       @After\r
+       public void tearDown() throws Exception {\r
+       }\r
+       \r
+\r
+       \r
+       @Test\r
+       public void testwritefile() {\r
+               Boolean flag = false;\r
+               \r
+               FetchDynamicConfig fc = new FetchDynamicConfig();\r
+               //Used for writing the configuration output\r
+               FetchDynamicConfig.configFile = "src/test/resources/controller-config_formatted_op.json";\r
+\r
+               \r
+               \r
+               try{\r
+                       JsonParser parser = new JsonParser();\r
+                       FileReader fr = new FileReader ("src/test/resources/controller-config_singleline_ip.json"  );\r
+                       final JsonObject jo =  (JsonObject) parser.parse (fr);\r
+                       final String jsonText = jo.toString ();\r
+                       jsonObject = new JSONObject ( jsonText );\r
+                       \r
+                       fc.writefile(jsonObject.toString());\r
+               }\r
+               catch(Exception e){\r
+                       System.out.println("Exception while opening the file");\r
+                       e.printStackTrace();\r
+               }\r
+               if(jsonObject.has("streams_publishes"))\r
+               {\r
+                       flag = true;\r
+               }\r
+               \r
+               assertEquals(true, flag);\r
+               \r
+       }\r
+       \r
+       @Test\r
+       public void testgetConsul() {\r
+               Boolean flag = false;\r
+\r
+               \r
+               try{\r
+\r
+                       FetchDynamicConfig.getconsul();\r
+                       flag = true;\r
+               }\r
+               catch(Exception e){\r
+                       System.out.println("Exception while getting to consul");\r
+                       e.printStackTrace();\r
+               }\r
+               assertEquals(true, flag);\r
+               \r
+       }\r
+\r
+       @Test\r
+       public void testgetCBS() {\r
+               Boolean flag = false;\r
+               \r
+               try{\r
+                       \r
+                       \r
+                       JsonParser parser = new JsonParser();\r
+                       FileReader fr = new FileReader ("src/test/resources/controller-config_singleline_ip.json"  );\r
+                       final JsonObject jo =  (JsonObject) parser.parse (fr);\r
+                       final String jsonText = jo.toString ();\r
+                       jsonObject = new JSONObject ( jsonText );\r
+                       \r
+                       //retstring from Consul is parsed\r
+                       FetchDynamicConfig.retString = "[{\"ID\":\"81bc2a17-8cfa-3f6f-30a9-a545a9b6ac2f\",\"Node\":\"zldcrdm5bdcc2dokr00\",\"Address\":\"135.25.108.161\",\"Datacenter\":\"zldcrdm5bdcc2\",\"TaggedAddresses\":{\"lan\":\"135.25.108.161\",\"wan\":\"135.25.108.161\"},\"NodeMeta\":{\"fqdn\":\"zldcrdm5bdcc2dokr00.2f3fb3.rdm5b.tci.att.com\"},\"ServiceID\":\"20299a144716:config_binding_service:10000\",\"ServiceName\":\"config_binding_service\",\"ServiceTags\":[],\"ServiceAddress\":\"135.25.108.161\",\"ServicePort\":10000,\"ServiceEnableTagOverride\":false,\"CreateIndex\":9153156,\"ModifyIndex\":9153156}]";\r
+                       \r
+                       //Mock the return CBS output\r
+                       FetchDynamicConfig.retCBSString = jsonObject.toString();\r
+                       FetchDynamicConfig.getCBS();\r
+                       flag = true;\r
+               }\r
+               catch(Exception e){\r
+                       System.out.println("Exception while fetching cbs configuration");\r
+                       e.printStackTrace();\r
+               }\r
+               assertEquals(true, flag);\r
+               \r
+       }\r
+       \r
+}\r
+\r