Adding ServerSentEvents to Rest Southbound interface

Change-Id: I77411df608be8a1cab9d828db17202f88b969a0f
diff --git a/protocols/rest/api/src/main/java/org/onosproject/protocol/http/HttpSBController.java b/protocols/rest/api/src/main/java/org/onosproject/protocol/http/HttpSBController.java
index ada5496..0f5b32b 100644
--- a/protocols/rest/api/src/main/java/org/onosproject/protocol/http/HttpSBController.java
+++ b/protocols/rest/api/src/main/java/org/onosproject/protocol/http/HttpSBController.java
@@ -18,8 +18,10 @@
 
 import java.io.InputStream;
 import java.util.Map;
+import java.util.function.Consumer;
 
 import javax.ws.rs.core.MediaType;
+import javax.ws.rs.sse.InboundSseEvent;
 
 import org.onlab.packet.IpAddress;
 import org.onosproject.net.DeviceId;
@@ -125,7 +127,8 @@
     InputStream get(DeviceId device, String request, MediaType mediaType);
 
     /**
-     * Does a HTTP POST request with specified parameters to the device.
+     * Does a HTTP POST request with specified parameters to the device and
+     * extracts an object of type T from the response entity field.
      *
      * @param <T> post return type
      * @param device device to make the request to
@@ -138,5 +141,27 @@
      */
      <T> T post(DeviceId device, String request, InputStream payload, MediaType mediaType, Class<T> responseClass);
 
+    /**
+     * Does a HTTP GET against a Server Sent Events (SSE_INBOUND) resource on the device.
+     *
+     * This is a low level function that can take callbacks.
+     * For a higher level function that emits events based on this callback
+     * see startServerSentEvents() in the RestSBController
+     *
+     * @param deviceId device to make the request to
+     * @param request url of the request
+     * @param onEvent A consumer of inbound SSE_INBOUND events
+     * @param onError A consumer of inbound SSE_INBOUND errors
+     * @return status Commonly used status codes defined by HTTP
+     */
+     int getServerSentEvents(DeviceId deviceId, String request,
+                             Consumer<InboundSseEvent> onEvent, Consumer<Throwable> onError);
 
+    /**
+     * Cancels a Server Sent Events listener to a device.
+     *
+     * @param deviceId device to cancel the listener for
+     * @return status Commonly used status codes defined by HTTP
+     */
+    int cancelServerSentEvents(DeviceId deviceId);
 }
diff --git a/protocols/rest/api/src/main/java/org/onosproject/protocol/http/ctl/HttpSBControllerImpl.java b/protocols/rest/api/src/main/java/org/onosproject/protocol/http/ctl/HttpSBControllerImpl.java
index e8fcca0..e4ba243 100644
--- a/protocols/rest/api/src/main/java/org/onosproject/protocol/http/ctl/HttpSBControllerImpl.java
+++ b/protocols/rest/api/src/main/java/org/onosproject/protocol/http/ctl/HttpSBControllerImpl.java
@@ -45,6 +45,8 @@
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.sse.InboundSseEvent;
+import javax.ws.rs.sse.SseEventSource;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -57,6 +59,7 @@
 import java.util.Base64;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
@@ -80,6 +83,7 @@
 
     private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
     private final Map<DeviceId, Client> clientMap = new ConcurrentHashMap<>();
+    private final Map<DeviceId, SseEventSource> sseEventSourceMap = new ConcurrentHashMap<>();
 
     public Map<DeviceId, RestSBDevice> getDeviceMap() {
         return deviceMap;
@@ -89,6 +93,10 @@
         return clientMap;
     }
 
+    public Map<DeviceId, SseEventSource> getSseEventSourceMap() {
+        return sseEventSourceMap;
+    }
+
     @Override
     public Map<DeviceId, RestSBDevice> getDevices() {
         return ImmutableMap.copyOf(deviceMap);
@@ -121,6 +129,7 @@
     public void removeDevice(DeviceId deviceId) {
         clientMap.remove(deviceId);
         deviceMap.remove(deviceId);
+        sseEventSourceMap.remove(deviceId);
     }
 
     @Override
@@ -251,6 +260,58 @@
         return response.getStatus();
     }
 
+    @Override
+    public int getServerSentEvents(DeviceId deviceId, String request,
+                                   Consumer<InboundSseEvent> onEvent,
+                                   Consumer<Throwable> onError) {
+        if (deviceId == null) {
+            log.warn("Device ID is null", request);
+            return Status.PRECONDITION_FAILED.getStatusCode();
+        }
+
+        if (request == null || request.isEmpty()) {
+            log.warn("Request cannot be empty", request);
+            return Status.PRECONDITION_FAILED.getStatusCode();
+        }
+
+        if (sseEventSourceMap.containsKey(deviceId)) {
+            log.warn("Device", deviceId, "is already listening to an SSE stream");
+            return Status.CONFLICT.getStatusCode();
+        }
+
+        WebTarget wt = getWebTarget(deviceId, request);
+        SseEventSource sseEventSource = SseEventSource.target(wt).build();
+        sseEventSource.register(onEvent, onError);
+        sseEventSource.open();
+        if (sseEventSource.isOpen()) {
+            sseEventSourceMap.put(deviceId, sseEventSource);
+            log.info("Opened Server Sent Events request to ", request, "on", deviceId);
+            while (sseEventSource.isOpen()) {
+                try {
+                    Thread.sleep(1010);
+                    System.out.println("Listening for SSEs");
+                } catch (InterruptedException e) {
+                    log.error("Error", e);
+                }
+            }
+            return Status.NO_CONTENT.getStatusCode();
+        } else {
+            log.error("Unable to open Server Sent Events request to ", request, "to", deviceId);
+            return Status.INTERNAL_SERVER_ERROR.getStatusCode();
+        }
+    }
+
+    @Override
+    public int cancelServerSentEvents(DeviceId deviceId) {
+        if (sseEventSourceMap.containsKey(deviceId)) {
+            sseEventSourceMap.get(deviceId).close();
+            sseEventSourceMap.remove(deviceId);
+            return Status.OK.getStatusCode();
+        } else {
+            return Status.NOT_FOUND.getStatusCode();
+        }
+    }
+
     private MediaType typeOfMediaType(String type) {
         switch (type) {
         case XML:
diff --git a/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBController.java b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBController.java
index 551ddcb..c67609a 100644
--- a/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBController.java
+++ b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBController.java
@@ -56,4 +56,22 @@
      * @return the corresponding REST proxied device
      */
     RestSBDevice getProxySBDevice(DeviceId deviceId);
+
+    /**
+     * Call on the Rest SB interface for a device to request ServerSentEvents from events URL.
+     *
+     * These events will be converted to ONOS events and forwarded to any registered listener
+     * through the EventDispatcher system. Drivers can implement listeners in their
+     * own particular way depending on the type of data expected.
+     *
+     * To register and unregister listeners use the addListener and removeListener
+     * methods. These listeners will get messages from all devices.
+     *
+     * To stop a particular device's event stream use the cancelServerSentEvents
+     * for that device.
+     *
+     * @param deviceId the id of the device exposed to ONOS
+     * @param eventsUrl The resource on the device that supplies an SSE_INBOUND stream
+     */
+    void startServerSentEvents(DeviceId deviceId, String eventsUrl);
 }
diff --git a/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBEventListener.java b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBEventListener.java
new file mode 100644
index 0000000..d96599c
--- /dev/null
+++ b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBEventListener.java
@@ -0,0 +1,25 @@
+/*
+ * 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 org.onosproject.protocol.rest;
+
+import org.onosproject.event.EventListener;
+
+/**
+ * Listener interface for Server Sent Events from Rest SB.
+ */
+public interface RestSBEventListener extends EventListener<RestSBServerSentEvent> {
+}
diff --git a/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBServerSentEvent.java b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBServerSentEvent.java
new file mode 100644
index 0000000..30d35ee
--- /dev/null
+++ b/protocols/rest/api/src/main/java/org/onosproject/protocol/rest/RestSBServerSentEvent.java
@@ -0,0 +1,94 @@
+/*
+ * 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 org.onosproject.protocol.rest;
+
+import org.onosproject.event.AbstractEvent;
+import org.onosproject.net.DeviceId;
+
+import javax.ws.rs.sse.InboundSseEvent;
+
+import java.util.Objects;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Event received on the REST SB interface as ServerSentEvent (SSE_INBOUND).
+ */
+public class RestSBServerSentEvent extends AbstractEvent<RestSBServerSentEvent.Type, DeviceId> {
+
+    private String id;
+    private String comment;
+    private String data;
+    private String name;
+
+    /**
+     * SSE Event types supported.
+     */
+    public enum Type {
+        SSE_INBOUND
+    }
+
+    public RestSBServerSentEvent(Type type, DeviceId deviceId, InboundSseEvent sseEvent) {
+        super(type, deviceId);
+        checkNotNull(sseEvent);
+        data = sseEvent.readData();
+        id = sseEvent.getId();
+        name = sseEvent.getName();
+        comment = sseEvent.getComment();
+    }
+
+    public String getData() {
+        return data;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public String getComment() {
+        return comment;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public String toString() {
+        return super.toString() + ", id=" + id + ", name=" + name + ", comment=" + comment;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        RestSBServerSentEvent that = (RestSBServerSentEvent) o;
+        return Objects.equals(id, that.id) &&
+                Objects.equals(comment, that.comment) &&
+                Objects.equals(data, that.data) &&
+                Objects.equals(name, that.name);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(id, comment, data, name);
+    }
+}