Merge "BUG-614: migrate RuntimeGeneratedInvoker"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / streams / websockets / WebSocketServerHandler.java
1 package org.opendaylight.controller.sal.streams.websockets;
2
3 import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;
4 import static io.netty.handler.codec.http.HttpHeaders.setContentLength;
5 import static io.netty.handler.codec.http.HttpHeaders.Names.HOST;
6 import static io.netty.handler.codec.http.HttpMethod.GET;
7 import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
8 import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
9 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
10 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.Unpooled;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.channel.ChannelFutureListener;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.SimpleChannelInboundHandler;
17 import io.netty.handler.codec.http.DefaultFullHttpResponse;
18 import io.netty.handler.codec.http.FullHttpRequest;
19 import io.netty.handler.codec.http.FullHttpResponse;
20 import io.netty.handler.codec.http.HttpRequest;
21 import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
22 import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
23 import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
24 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
25 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
26 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
27 import io.netty.util.CharsetUtil;
28
29 import java.io.IOException;
30
31 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
32 import org.opendaylight.controller.sal.streams.listeners.Notificator;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * {@link WebSocketServerHandler} is implementation of
38  * {@link SimpleChannelInboundHandler} which allow handle
39  * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
40  */
41 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
42
43     private static final Logger logger = LoggerFactory
44             .getLogger(WebSocketServerHandler.class);
45
46     private WebSocketServerHandshaker handshaker;
47
48     @Override
49     protected void channelRead0(ChannelHandlerContext ctx, Object msg)
50             throws Exception {
51         if (msg instanceof FullHttpRequest) {
52             handleHttpRequest(ctx, (FullHttpRequest) msg);
53         } else if (msg instanceof WebSocketFrame) {
54             handleWebSocketFrame(ctx, (WebSocketFrame) msg);
55         }
56     }
57
58     /**
59      * Checks if HTTP request method is GET and if is possible to decode HTTP
60      * result of request.
61      *
62      * @param ctx
63      *            ChannelHandlerContext
64      * @param req
65      *            FullHttpRequest
66      */
67     private void handleHttpRequest(ChannelHandlerContext ctx,
68             FullHttpRequest req) throws Exception {
69         // Handle a bad request.
70         if (!req.getDecoderResult().isSuccess()) {
71             sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
72                     BAD_REQUEST));
73             return;
74         }
75
76         // Allow only GET methods.
77         if (req.getMethod() != GET) {
78             sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
79                     FORBIDDEN));
80             return;
81         }
82
83         String streamName = Notificator.createStreamNameFromUri(req.getUri());
84         ListenerAdapter listener = Notificator.getListenerFor(streamName);
85         if (listener != null) {
86             listener.addSubscriber(ctx.channel());
87             logger.debug("Subscriber successfully registered.");
88         } else {
89             logger.error("Listener for stream with name '{}' was not found.",
90                     streamName);
91             sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
92                     INTERNAL_SERVER_ERROR));
93         }
94
95         // Handshake
96         WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
97                 getWebSocketLocation(req), null, false);
98         handshaker = wsFactory.newHandshaker(req);
99         if (handshaker == null) {
100             WebSocketServerHandshakerFactory
101                     .sendUnsupportedWebSocketVersionResponse(ctx.channel());
102         } else {
103             handshaker.handshake(ctx.channel(), req);
104         }
105
106     }
107
108     /**
109      * Checks response status, send response and close connection if necessary
110      *
111      * @param ctx
112      *            ChannelHandlerContext
113      * @param req
114      *            HttpRequest
115      * @param res
116      *            FullHttpResponse
117      */
118     private static void sendHttpResponse(ChannelHandlerContext ctx,
119             HttpRequest req, FullHttpResponse res) {
120         // Generate an error page if response getStatus code is not OK (200).
121         if (res.getStatus().code() != 200) {
122             ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
123                     CharsetUtil.UTF_8);
124             res.content().writeBytes(buf);
125             buf.release();
126             setContentLength(res, res.content().readableBytes());
127         }
128
129         // Send the response and close the connection if necessary.
130         ChannelFuture f = ctx.channel().writeAndFlush(res);
131         if (!isKeepAlive(req) || res.getStatus().code() != 200) {
132             f.addListener(ChannelFutureListener.CLOSE);
133         }
134     }
135
136     /**
137      * Handles web socket frame.
138      *
139      * @param ctx
140      *            {@link ChannelHandlerContext}
141      * @param frame
142      *            {@link WebSocketFrame}
143      */
144     private void handleWebSocketFrame(ChannelHandlerContext ctx,
145             WebSocketFrame frame) throws IOException {
146         if (frame instanceof CloseWebSocketFrame) {
147             handshaker.close(ctx.channel(),
148                     (CloseWebSocketFrame) frame.retain());
149             String streamName = Notificator
150                     .createStreamNameFromUri(((CloseWebSocketFrame) frame)
151                             .reasonText());
152             ListenerAdapter listener = Notificator.getListenerFor(streamName);
153             if (listener != null) {
154                 listener.removeSubscriber(ctx.channel());
155                 logger.debug("Subscriber successfully registered.");
156             }
157             Notificator.removeListenerIfNoSubscriberExists(listener);
158             return;
159         } else if (frame instanceof PingWebSocketFrame) {
160             ctx.channel().write(
161                     new PongWebSocketFrame(frame.content().retain()));
162             return;
163         }
164     }
165
166     @Override
167     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
168             throws Exception {
169         if (cause instanceof java.nio.channels.ClosedChannelException == false) {
170             // cause.printStackTrace();
171         }
172         ctx.close();
173     }
174
175     /**
176      * Get web socket location from HTTP request.
177      *
178      * @param req
179      *            HTTP request from which the location will be returned
180      * @return String representation of web socket location.
181      */
182     private static String getWebSocketLocation(HttpRequest req) {
183         return "http://" + req.headers().get(HOST) + req.getUri();
184     }
185
186 }