BUG-868: donot use deprecated call
[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(final ChannelHandlerContext ctx, final 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(final ChannelHandlerContext ctx,
68             final 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.sendUnsupportedVersionResponse(ctx.channel());
101         } else {
102             handshaker.handshake(ctx.channel(), req);
103         }
104
105     }
106
107     /**
108      * Checks response status, send response and close connection if necessary
109      *
110      * @param ctx
111      *            ChannelHandlerContext
112      * @param req
113      *            HttpRequest
114      * @param res
115      *            FullHttpResponse
116      */
117     private static void sendHttpResponse(final ChannelHandlerContext ctx,
118             final HttpRequest req, final FullHttpResponse res) {
119         // Generate an error page if response getStatus code is not OK (200).
120         if (res.getStatus().code() != 200) {
121             ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
122                     CharsetUtil.UTF_8);
123             res.content().writeBytes(buf);
124             buf.release();
125             setContentLength(res, res.content().readableBytes());
126         }
127
128         // Send the response and close the connection if necessary.
129         ChannelFuture f = ctx.channel().writeAndFlush(res);
130         if (!isKeepAlive(req) || res.getStatus().code() != 200) {
131             f.addListener(ChannelFutureListener.CLOSE);
132         }
133     }
134
135     /**
136      * Handles web socket frame.
137      *
138      * @param ctx
139      *            {@link ChannelHandlerContext}
140      * @param frame
141      *            {@link WebSocketFrame}
142      */
143     private void handleWebSocketFrame(final ChannelHandlerContext ctx,
144             final WebSocketFrame frame) throws IOException {
145         if (frame instanceof CloseWebSocketFrame) {
146             handshaker.close(ctx.channel(),
147                     (CloseWebSocketFrame) frame.retain());
148             String streamName = Notificator
149                     .createStreamNameFromUri(((CloseWebSocketFrame) frame)
150                             .reasonText());
151             ListenerAdapter listener = Notificator.getListenerFor(streamName);
152             if (listener != null) {
153                 listener.removeSubscriber(ctx.channel());
154                 logger.debug("Subscriber successfully registered.");
155             }
156             Notificator.removeListenerIfNoSubscriberExists(listener);
157             return;
158         } else if (frame instanceof PingWebSocketFrame) {
159             ctx.channel().write(
160                     new PongWebSocketFrame(frame.content().retain()));
161             return;
162         }
163     }
164
165     @Override
166     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause)
167             throws Exception {
168         if (cause instanceof java.nio.channels.ClosedChannelException == false) {
169             // cause.printStackTrace();
170         }
171         ctx.close();
172     }
173
174     /**
175      * Get web socket location from HTTP request.
176      *
177      * @param req
178      *            HTTP request from which the location will be returned
179      * @return String representation of web socket location.
180      */
181     private static String getWebSocketLocation(final HttpRequest req) {
182         return "http://" + req.headers().get(HOST) + req.getUri();
183     }
184
185 }