[SEBA-627] Add more test case of testing of importer

Change-Id: Ief2671f7ba1d4855066a8cc28d41b8e3b5f6983f
diff --git a/demo_test/cmd_client/Makefile b/demo_test/cmd_client/Makefile
new file mode 100644
index 0000000..4c9a95e
--- /dev/null
+++ b/demo_test/cmd_client/Makefile
@@ -0,0 +1,17 @@
+# Copyright 2018-present Open Networking Foundation
+#
+# 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.
+
+cmd_cl:
+	go build -i -v -o $@
+
diff --git a/demo_test/cmd_client/Note b/demo_test/cmd_client/Note
new file mode 100644
index 0000000..74b6916
--- /dev/null
+++ b/demo_test/cmd_client/Note
@@ -0,0 +1,96 @@
+// Copyright 2018 Open Networking Foundation
+//
+// 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.
+
+At the root of the device-management source tree
+1. cd demotest
+   make demotest
+   ./demotest
+2. Create another ssh session
+   cd ./demotest/cmd_cleint
+   make cmd_cl
+   ./cmd_cl
+
+   then it will have "CMD to send:" prompt
+   You can use the following "client cmd" to test.
+
+   Example:
+
+   For the first time, you need to use "attach:ipaddress:port:vendorname:freq" to set the device's IP related info.
+   If successful, you will get "[ipaddress:port]CMD to send:" prompt to indicate what device you attached now. 
+   This attach will subscribe default 3 types events into the server.  
+   You can use the following wget to check if any events subscriptions on the device.
+
+   wget --no-check-certificate  \
+   -qO- https://RFSERVERIP:8888/redfish/v1/EventService/Subscriptions/ \
+   | python -m json.tool
+
+   You can also use "unsub:add:rm:alert" to unsubscribe all 3 types of event subscriptions on the device.
+
+   And use "QUIT" to leave test.
+
+--------------------------------------------------------------------------------------
+Test items								client cmd
+--------------------------------------------------------------------------------------
+set device info								Example:
+
+Set IP 192.168.4.27 port 8888 vendor "edgecore" freq 180
+									attach:192.168.4.27:8888:edgecore:180
+--------------------------------------------------------------------------------------
+set multi-deivies info                                                  Example:
+
+									attach:192.168.4.27:8888:edgecore:180
+									attach:192.168.3.34:8888:edgecore:180
+--------------------------------------------------------------------------------------
+UnSubscribe all events(ResourceAdded/ResourceRemoved/Alert)		unsub:add:rm:alert
+--------------------------------------------------------------------------------------
+Subscribe all events(ResourceAdded/ResourceRemoved/Alert) 		sub:add:rm:alert
+--------------------------------------------------------------------------------------
+Subscribe and unsubscribe an event					Example:	
+
+Subscribe ResourceAdded event 						sub:add
+Subscribe ResourceRemoved event						sub:rm
+Subscribe Alert event							sub:alert
+Unsubscribe ResourceAdded event						unsub:add
+Unsubscribe ResourceRemoved event					unsub:rm
+Unsubscribe Alert event							unsub:alert
+--------------------------------------------------------------------------------------
+Subscribe and unsubscribe multiple events, out of order			Use the above commands to do test.
+--------------------------------------------------------------------------------------
+Subscribe an unsupported event						sub:update
+--------------------------------------------------------------------------------------
+Subscribe to an already subscribed event				Example:
+
+									sub:add
+									sub:add
+--------------------------------------------------------------------------------------
+Unsubscribe  an unsupported event					unsub:update
+--------------------------------------------------------------------------------------
+Unsubscribe a supported but not-subscribed event			Example:
+
+									unsub:add:rm:alert
+									unsub:add
+									unsub:rm
+									unsub:alert
+--------------------------------------------------------------------------------------
+Change polling interval 						Example: 
+
+Set frequecny to 30 seconds
+									period:30
+--------------------------------------------------------------------------------------
+Show support event list							showeventlist	
+--------------------------------------------------------------------------------------
+* During and after each test, verify the list of events subscribed	wget --no-check-certificate  \
+									-qO- https://192.168.4.27:8888/redfish/v1/EventService/Subscriptions/ \
+									| python -m json.tool
+--------------------------------------------------------------------------------------
diff --git a/demo_test/cmd_client/cmd_cl.go b/demo_test/cmd_client/cmd_cl.go
new file mode 100644
index 0000000..e1ee3bb
--- /dev/null
+++ b/demo_test/cmd_client/cmd_cl.go
@@ -0,0 +1,60 @@
+// Copyright 2018-present Open Networking Foundation
+//
+// 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.
+
+package main
+
+import "net"
+import "fmt"
+import "bufio"
+import "os"
+import "strings"
+
+var attach_ip string = ""
+
+func main() {
+	// connect to this socket
+	var message string = ""
+	conn, _ := net.Dial("tcp", "127.0.0.1:9999")
+	reader := bufio.NewReader(os.Stdin)
+	for {
+		// read in input from stdin
+		if(attach_ip != ""){
+			fmt.Printf("[%v] CMD to send :", attach_ip)
+		}else{
+			fmt.Print("CMD to send :")
+		}
+		text, _ := reader.ReadString('\n')
+
+		// send to socket
+		fmt.Fprintf(conn, text + "\n")
+
+                cmd := strings.TrimSuffix(text, "\n")
+                s := strings.Split(cmd, ":")
+                cmd = s[0]
+
+		if(cmd == "attach"){
+			// listen for reply
+			t_attach_ip, _ := bufio.NewReader(conn).ReadString('\n')
+			attach_ip = strings.TrimSuffix(t_attach_ip, "\n")
+		}else{
+			// listen for reply
+			message, _ = bufio.NewReader(conn).ReadString('\n')
+			fmt.Print("Return from server: " + message)
+		}
+
+		if message == "QUIT\n"{
+			break
+		}
+	}
+}
diff --git a/demo_test/demotest b/demo_test/demotest
deleted file mode 100755
index ed7c50b..0000000
--- a/demo_test/demotest
+++ /dev/null
Binary files differ
diff --git a/demo_test/test.go b/demo_test/test.go
index b0502ac..70c2df6 100644
--- a/demo_test/test.go
+++ b/demo_test/test.go
@@ -16,6 +16,8 @@
 
 import (
         "fmt"
+        "net"
+        "bufio"
         "os"
         "os/signal"
         "os/exec"
@@ -24,23 +26,134 @@
         "golang.org/x/net/context"
         importer "./proto"
         log "github.com/Sirupsen/logrus"
-	"time"
 	"bytes"
 	"strings"
-
+        "net/http"
+        "crypto/tls"
+        "strconv"
 )
 
-const (
-	 address     = "localhost:31085"
-	vendor       = "edgecore"
-//	device_ip    = "192.168.3.44:9888"
-	device_ip    = "192.168.4.27:8888"
-	protocol     = "https"
-	freq         = 180
-)
-var importerTopic = "importer"
+var REDFISH_ROOT		= "/redfish/v1"
+var CONTENT_TYPE		= "application/json"
+var EVENTS_MAP = map[string]string{
+"add":"ResourceAdded",
+"rm":"ResourceRemoved",
+"alert":"Alert",
+"update":"Update"}
+
+var default_address string	= "localhost:31085"
+var default_port    string	= "8888"
+var default_vendor  string	= "edgecore"
+var default_freq    uint64	= 180
+var attach_device_ip string	= ""
+var importerTopic		= "importer"
 var DataConsumer sarama.Consumer
 
+var cc	   importer.DeviceManagementClient
+var ctx	   context.Context
+var conn   * grpc.ClientConn
+
+type Device struct {
+	deviceinfo * importer.DeviceInfo
+	eventlist  * importer.EventList
+}
+
+var devicemap map[string]* Device
+
+/*///////////////////////////////////////////////////////////////////////*/
+// Allows user to register the device for data collection and frequency.
+//
+//
+/*///////////////////////////////////////////////////////////////////////*/
+func (s * Device) Attach(aip string, avendor string, afreq uint32) (error, string) {
+        fmt.Println("Received Attach\n")
+	var default_protocol string	= "https"
+
+	s.deviceinfo = new(importer.DeviceInfo)
+	s.eventlist  = new(importer.EventList)
+	s.deviceinfo.IpAddress  = aip
+	s.deviceinfo.Vendor     = avendor
+	s.deviceinfo.Frequency  = afreq
+	s.deviceinfo.Protocol   = default_protocol
+	_, err := cc.SendDeviceInfo(ctx, s.deviceinfo)
+
+	if err != nil {
+		return err ,"attach error!!"
+	}else{
+		return nil,""
+	}
+}
+
+/*///////////////////////////////////////////////////////////////////////*/
+// Allows user to change the frequency of data collection
+//
+//
+/*///////////////////////////////////////////////////////////////////////*/
+func (s * Device) UpdateFreq(wd uint32)(error, string) {
+        fmt.Println("Received Period\n")
+	s.deviceinfo.Frequency  = wd
+	_, err := cc.SetFrequency(ctx, s.deviceinfo)
+
+	if err != nil {
+		return err, "period error!!"
+	}else{
+		return nil,""
+	}
+}
+
+/*///////////////////////////////////////////////////////////////////////*/
+// Allows user to unsubscribe events
+//
+//
+/*///////////////////////////////////////////////////////////////////////*/
+func (s * Device) Subscribe(eventlist []string) (error, string) {
+        fmt.Println("Received Subscribe\n")
+	s.eventlist.Events = eventlist
+	s.eventlist.EventIpAddress = s.deviceinfo.IpAddress
+	_, err := cc.SubsrcribeGivenEvents(ctx, s.eventlist)
+
+	if err != nil {
+		return err, "sub error!!"
+	}else{
+		return nil,""
+	}
+}
+
+/*///////////////////////////////////////////////////////////////////////*/
+// Allows user to unsubscribe events
+//
+//
+/*///////////////////////////////////////////////////////////////////////*/
+func (s * Device) UnSubscribe(eventlist []string) (error, string) {
+        fmt.Println("Received UnSubscribe\n")
+	s.eventlist.Events = eventlist
+	s.eventlist.EventIpAddress = s.deviceinfo.IpAddress
+	_, err := cc.UnSubsrcribeGivenEvents(ctx, s.eventlist)
+
+	if err != nil {
+		return err, "unsub error!!"
+	}else{
+		return nil,""
+	}
+}
+
+/*///////////////////////////////////////////////////////////////////////*/
+// Allows user to get the events supported by device
+//
+//
+/*///////////////////////////////////////////////////////////////////////*/
+func (s * Device) GetEventSupportList() (error, []string) {
+        fmt.Println("Received GetEventSupportList\n")
+	var ret_msg * importer.SupportedEventList
+	ret_msg, err :=cc.GetEventList(ctx, devicemap[s.deviceinfo.IpAddress].deviceinfo);
+	if err != nil {
+		return err,ret_msg.Events
+	}else{
+		fmt.Println("show all event subs:", ret_msg)
+		return nil , ret_msg.Events
+	}
+}
+
 func init() {
         Formatter := new(log.TextFormatter)
         Formatter.TimestampFormat = "02-01-2006 15:04:05"
@@ -67,7 +180,7 @@
 				log.Info("Got message on topic=[%s]: %s", *topic, string(msg.Value))
 			case <-signals:
 				log.Warn("Interrupt is detected")
-				doneCh <- struct{}{}
+		                os.Exit(1)
 			}
 		}
 	}()
@@ -100,37 +213,194 @@
 	go topicListener(&importerTopic, master)
 }
 func main() {
+	http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
+	fmt.Println("Launching server...")
 	log.Info("kafkaInit starting")
 	kafkainit()
-	// Set up a connection to the server.
-	fmt.Println("Starting connection")
-	conn, err := grpc.Dial(address, grpc.WithInsecure())
-	if err != nil {
-	        fmt.Println("could not connect")
-		log.Fatal("did not connect: %v", err)
-	}
-	defer conn.Close()
-	c := importer.NewDeviceManagementClient(conn)
 
-	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
-	defer cancel()
-	deviceinfo := new(importer.DeviceInfo)
-	deviceinfo.IpAddress  = device_ip
-	deviceinfo.Vendor     = vendor
-	deviceinfo.Frequency   = freq
-	deviceinfo.Protocol    = protocol
-	_, err = c.SendDeviceInfo(ctx, deviceinfo)
-	if err != nil {
-		log.Fatal("could not SendDeviceInfo: %v", err)
-	}
-        quit := make(chan os.Signal)
-        signal.Notify(quit, os.Interrupt)
-
-        select {
-        case sig := <-quit:
-                fmt.Println("Shutting down:", sig)
-                DataConsumer.Close()
-                        panic(err)
+	ln, err := net.Listen("tcp", ":9999")
+        if err != nil {
+                fmt.Println("could not listen")
+                log.Fatal("did not listen: %v", err)
         }
+	defer ln.Close()
 
+	connS, err := ln.Accept()
+	if err != nil {
+                fmt.Println("Accept error")
+                log.Fatal("Accept error: %v", err)
+	}else{
+
+		conn, err = grpc.Dial(default_address, grpc.WithInsecure())
+		if err != nil {
+		        fmt.Println("could not connect")
+			log.Fatal("did not connect: %v", err)
+		}
+		defer conn.Close()
+
+		cc = importer.NewDeviceManagementClient(conn)
+		ctx = context.Background()
+
+		devicemap = make(map[string] *Device)
+		loop := true
+
+		for loop == true {
+			cmd, _ := bufio.NewReader(connS).ReadString('\n')
+
+			cmd = strings.TrimSuffix(cmd, "\n")
+			s := strings.Split(cmd, ":")
+			newmessage := "cmd error!!"
+			cmd = s[0]
+
+			switch string(cmd) {
+
+			case "attach" :
+				cmd_size := len(s)
+				var err	error
+				var aport   string = default_port
+				var avendor string = default_vendor
+				var uafreq  uint64 = default_freq
+
+				if (cmd_size == 2 || cmd_size == 5){
+					aip    := s[1]
+					if(cmd_size == 5){
+						aport	= s[2]
+						avendor	= s[3]
+						afreq	:= s[4]
+						uafreq, err = strconv.ParseUint(afreq, 10, 64)
+
+						if err != nil {
+							fmt.Print("ParseUint error!!")
+						}
+
+						attach_device_ip = aip + ":" + aport
+					}else{
+						attach_device_ip = aip + ":" + default_port
+					}
+
+					if (devicemap[attach_device_ip] == nil){
+						dev := new (Device)
+						err, newmessage = dev.Attach(attach_device_ip, avendor, uint32(uafreq))
+						if err != nil {
+							fmt.Print("attach error!!")
+						}else{
+							fmt.Print("attatch IP:", attach_device_ip)
+							newmessage = attach_device_ip
+							devicemap[attach_device_ip] = dev
+						}
+					}else{
+						fmt.Print("Change attach IP to %v", attach_device_ip)
+						newmessage = attach_device_ip
+					}
+				}else{
+					fmt.Print("Need IP address !!")
+					newmessage = "Need IP address !!"
+
+				}
+			break
+
+			case "period" :
+				cmd_size := len(s)
+				if (cmd_size == 2 ){
+					if (devicemap[attach_device_ip] != nil){
+						pv  := s[1]
+						fmt.Print("pv:", pv)
+						u, err := strconv.ParseUint(pv, 10, 64)
+
+						if err != nil {
+							fmt.Print("ParseUint error!!")
+						}else{
+							wd := uint32(u)
+							dev := devicemap[attach_device_ip]
+							err, newmessage =  dev.UpdateFreq(wd)
+
+							if err != nil {
+								fmt.Print("period error!!")
+							}else{
+								newmessage = strings.ToUpper(cmd)
+							}
+						}
+					}else{
+						fmt.Print("need attach first!!")
+						newmessage = "need attach first!!"
+					}
+				}else{
+					fmt.Print("Need period value !!")
+					newmessage = "Need period value !!"
+				}
+
+			break
+
+			case "sub","unsub" :
+				cmd_size := len(s)
+				fmt.Print("cmd is :", cmd)
+				if(cmd_size > 4 || cmd_size <0){
+					fmt.Print("error event !!")
+					newmessage = "error event !!"
+				}else{
+					var events_list []string
+					for i := 1; i < cmd_size; i++ {
+						if value, ok := EVENTS_MAP[s[i]]; ok {
+							events_list = append(events_list,value)
+						} else {
+							fmt.Println("key not found")
+						}
+					}
+
+					if (devicemap[attach_device_ip] != nil){
+						dev := devicemap[attach_device_ip]
+						if(string(cmd) == "sub"){
+							err, newmessage =  dev.Subscribe(events_list)
+							if err != nil {
+								fmt.Print("sub error!!")
+								newmessage = "sub error!!"
+							}else{
+								newmessage = strings.ToUpper(cmd)
+							}
+						}else{
+							err, newmessage =  dev.UnSubscribe(events_list)
+							if err != nil {
+								fmt.Print("unsub error!!")
+								newmessage = "unsub error!!"
+							}else{
+								newmessage = strings.ToUpper(cmd)
+							}
+						}
+					}else{
+						fmt.Print("need attach first !!")
+						newmessage = "need attach first !!"
+					}
+				}
+			break
+
+			case "showeventlist" :
+				if (devicemap[attach_device_ip] != nil){
+					dev := devicemap[attach_device_ip]
+					err, supportlist :=  dev.GetEventSupportList()
+
+					if err != nil {
+						fmt.Print("showeventlist error!!")
+					}else{
+						fmt.Print("showeventlist ", supportlist)
+						newmessage = strings.Join(supportlist[:],",")
+					}
+				}else{
+					fmt.Print("need attach first !!")
+					newmessage = "need attach first !!"
+				}
+
+			break
+
+			case "QUIT" :
+				loop = false
+	                        newmessage="QUIT"
+			break
+
+			default :
+			break
+			}
+			// send string back to client
+			connS.Write([]byte(newmessage + "\n"))
+	        }
+	}
 }
diff --git a/event_subscriber.go b/event_subscriber.go
index 0fb3294..9fe0308 100644
--- a/event_subscriber.go
+++ b/event_subscriber.go
@@ -23,7 +23,7 @@
 	"os"
 )
 
-const RF_SUBSCRIPTION = "/EventService/Subscriptions"
+const RF_SUBSCRIPTION = "/EventService/Subscriptions/"
 
 func (s *Server) add_subscription(ip string, event string, f *os.File) (rtn bool) {
 	rtn = false
@@ -59,7 +59,7 @@
 
 	if f != nil {
 		b, err := json.Marshal(s.devicemap[ip])
-fmt.Println(string(b))
+		fmt.Println(string(b))
 		if err != nil {
 			fmt.Println(err)
 		} else {
@@ -81,7 +81,7 @@
 
 func (s *Server) remove_subscription(ip string, event string, f *os.File) bool {
 	id := s.devicemap[ip].Subscriptions[event]
-	uri := s.devicemap[ip].Protocol + "://" + ip + REDFISH_ROOT + RF_SUBSCRIPTION + "/" + id
+	uri := s.devicemap[ip].Protocol + "://" + ip + REDFISH_ROOT + RF_SUBSCRIPTION + id
 	req, _ := http.NewRequest("DELETE", uri, nil)
 	resp, err := http.DefaultClient.Do(req)
 	if err != nil {