1 package org.opendaylight.controller.sal.streams.websockets;
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;
29 import java.io.IOException;
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;
37 * {@link WebSocketServerHandler} is implementation of
38 * {@link SimpleChannelInboundHandler} which allow handle
39 * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
41 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
43 private static final Logger logger = LoggerFactory
44 .getLogger(WebSocketServerHandler.class);
46 private WebSocketServerHandshaker handshaker;
49 protected void channelRead0(ChannelHandlerContext ctx, Object msg)
51 if (msg instanceof FullHttpRequest) {
52 handleHttpRequest(ctx, (FullHttpRequest) msg);
53 } else if (msg instanceof WebSocketFrame) {
54 handleWebSocketFrame(ctx, (WebSocketFrame) msg);
59 * Checks if HTTP request method is GET and if is possible to decode HTTP
63 * ChannelHandlerContext
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,
76 // Allow only GET methods.
77 if (req.getMethod() != GET) {
78 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
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.");
89 logger.error("Listener for stream with name '{}' was not found.",
91 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
92 INTERNAL_SERVER_ERROR));
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());
103 handshaker.handshake(ctx.channel(), req);
109 * Checks response status, send response and close connection if necessary
112 * ChannelHandlerContext
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(),
124 res.content().writeBytes(buf);
126 setContentLength(res, res.content().readableBytes());
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);
137 * Handles web socket frame.
140 * {@link ChannelHandlerContext}
142 * {@link WebSocketFrame}
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)
152 ListenerAdapter listener = Notificator.getListenerFor(streamName);
153 if (listener != null) {
154 listener.removeSubscriber(ctx.channel());
155 logger.debug("Subscriber successfully registered.");
157 Notificator.removeListenerIfNoSubscriberExists(listener);
159 } else if (frame instanceof PingWebSocketFrame) {
161 new PongWebSocketFrame(frame.content().retain()));
167 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
169 if (cause instanceof java.nio.channels.ClosedChannelException == false) {
170 // cause.printStackTrace();
176 * Get web socket location from HTTP request.
179 * HTTP request from which the location will be returned
180 * @return String representation of web socket location.
182 private static String getWebSocketLocation(HttpRequest req) {
183 return "http://" + req.headers().get(HOST) + req.getUri();