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