Refactoring of web-sockets in RESTCONF RFC-8040
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / websockets / WebSocketServerHandler.java
index 7438ced14b297b8eb027241172a6a76637cd9de8..880c59a5260b410ea8a3230249bae3d7c89245a4 100755 (executable)
@@ -8,18 +8,6 @@
 
 package org.opendaylight.restconf.nb.rfc8040.streams.websockets;
 
-import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
-import static io.netty.handler.codec.http.HttpMethod.GET;
-import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
-import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
-import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
-import static io.netty.handler.codec.http.HttpResponseStatus.OK;
-import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
-import static io.netty.handler.codec.http.HttpUtil.setContentLength;
-import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
@@ -27,7 +15,12 @@ import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.handler.codec.http.DefaultFullHttpResponse;
 import io.netty.handler.codec.http.FullHttpRequest;
 import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
 import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpUtil;
+import io.netty.handler.codec.http.HttpVersion;
 import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
@@ -35,10 +28,10 @@ import io.netty.handler.codec.http.websocketx.WebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
 import io.netty.util.CharsetUtil;
-import java.util.List;
+import java.util.Optional;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenerAdapter;
+import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
-import org.opendaylight.restconf.nb.rfc8040.streams.listeners.Notificator;
 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -48,7 +41,6 @@ import org.slf4j.LoggerFactory;
  * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
  */
 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
-
     private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
 
     private WebSocketServerHandshaker handshaker;
@@ -71,43 +63,47 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
         // Handle a bad request.
         if (!req.decoderResult().isSuccess()) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
+                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
             return;
         }
 
         // Allow only GET methods.
-        if (req.method() != GET) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
+        if (req.method() != HttpMethod.GET) {
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
+                    HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
             return;
         }
 
-        final String streamName = Notificator.createStreamNameFromUri(req.uri());
+        final String streamName = ListenersBroker.createStreamNameFromUri(req.uri());
         if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
-            final ListenerAdapter listener = Notificator.getListenerFor(streamName);
-            if (listener != null) {
-                listener.addSubscriber(ctx.channel());
+            final Optional<ListenerAdapter> listener =
+                    ListenersBroker.getInstance().getDataChangeListenerFor(streamName);
+            if (listener.isPresent()) {
+                listener.get().addSubscriber(ctx.channel());
                 LOG.debug("Subscriber successfully registered.");
             } else {
                 LOG.error("Listener for stream with name '{}' was not found.", streamName);
-                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
+                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
+                        HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR));
             }
         } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
-            final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
-            if (listeners != null && !listeners.isEmpty()) {
-                for (final NotificationListenerAdapter listener : listeners) {
-                    listener.addSubscriber(ctx.channel());
-                    LOG.debug("Subscriber successfully registered.");
-                }
+            final Optional<NotificationListenerAdapter> listener =
+                    ListenersBroker.getInstance().getNotificationListenerFor(streamName);
+            if (listener.isPresent()) {
+                listener.get().addSubscriber(ctx.channel());
+                LOG.debug("Subscriber successfully registered.");
             } else {
                 LOG.error("Listener for stream with name '{}' was not found.", streamName);
-                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
+                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
+                        HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR));
             }
         }
 
         // Handshake
         final WebSocketServerHandshakerFactory wsFactory =
                 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
-                null, false);
+                        null, false);
         this.handshaker = wsFactory.newHandshaker(req);
         if (this.handshaker == null) {
             WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
@@ -125,19 +121,17 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param res FullHttpResponse
      */
     private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
-            final FullHttpResponse res) {
+                                         final FullHttpResponse res) {
         // Generate an error page if response getStatus code is not OK (200).
-        final boolean notOkay = !OK.equals(res.status());
+        final boolean notOkay = !HttpResponseStatus.OK.equals(res.status());
         if (notOkay) {
-            final ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
-            res.content().writeBytes(buf);
-            buf.release();
-            setContentLength(res, res.content().readableBytes());
+            res.content().writeCharSequence(res.status().toString(), CharsetUtil.UTF_8);
+            HttpUtil.setContentLength(res, res.content().readableBytes());
         }
 
         // Send the response and close the connection if necessary.
         final ChannelFuture f = ctx.channel().writeAndFlush(res);
-        if (notOkay || !isKeepAlive(req)) {
+        if (notOkay || !HttpUtil.isKeepAlive(req)) {
             f.addListener(ChannelFutureListener.CLOSE);
         }
     }
@@ -145,34 +139,37 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     /**
      * Handles web socket frame.
      *
-     * @param ctx
-     *            {@link ChannelHandlerContext}
-     * @param frame
-     *            {@link WebSocketFrame}
+     * @param ctx {@link ChannelHandlerContext}
+     * @param frame {@link WebSocketFrame}
      */
     private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
         if (frame instanceof CloseWebSocketFrame) {
             this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
-            final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
+            final String streamName = ListenersBroker.createStreamNameFromUri(
+                    ((CloseWebSocketFrame) frame).reasonText());
             if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
-                final ListenerAdapter listener = Notificator.getListenerFor(streamName);
-                if (listener != null) {
-                    listener.removeSubscriber(ctx.channel());
-                    LOG.debug("Subscriber successfully registered.");
-                    Notificator.removeListenerIfNoSubscriberExists(listener);
+                final Optional<ListenerAdapter> listener = ListenersBroker.getInstance()
+                        .getDataChangeListenerFor(streamName);
+                if (listener.isPresent()) {
+                    listener.get().removeSubscriber(ctx.channel());
+                    LOG.debug("Subscriber successfully removed.");
+                    if (!listener.get().hasSubscribers()) {
+                        ListenersBroker.getInstance().removeAndCloseDataChangeListener(listener.get());
+                    }
                 }
             } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
-                final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
-                if (listeners != null && !listeners.isEmpty()) {
-                    for (final NotificationListenerAdapter listener : listeners) {
-                        listener.removeSubscriber(ctx.channel());
+                final Optional<NotificationListenerAdapter> listener
+                        = ListenersBroker.getInstance().getNotificationListenerFor(streamName);
+                if (listener.isPresent()) {
+                    listener.get().removeSubscriber(ctx.channel());
+                    LOG.debug("Subscriber successfully removed.");
+                    if (!listener.get().hasSubscribers()) {
+                        ListenersBroker.getInstance().removeAndCloseNotificationListener(listener.get());
                     }
                 }
             }
-            return;
         } else if (frame instanceof PingWebSocketFrame) {
             ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
-            return;
         }
     }
 
@@ -184,10 +181,10 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     /**
      * Get web socket location from HTTP request.
      *
-     * @param req HTTP request from which the location will be returned
+     * @param req HTTP request from which the location will be returned.
      * @return String representation of web socket location.
      */
     private static String getWebSocketLocation(final HttpRequest req) {
-        return "ws://" + req.headers().get(HOST) + req.uri();
+        return "ws://" + req.headers().get(HttpHeaderNames.HOST) + req.uri();
     }
-}
+}
\ No newline at end of file