Split Restconf implementations (draft02 and RFC) - Prepare modules
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / 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.netconf.sal.streams.websockets;
10
11 import static io.netty.handler.codec.http.HttpHeaders.Names.HOST;
12 import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;
13 import static io.netty.handler.codec.http.HttpHeaders.setContentLength;
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 java.util.List;
39 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
40 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
41 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
42 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
48  * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
49  */
50 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
51
52     private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
53
54     private WebSocketServerHandshaker handshaker;
55
56     @Override
57     protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
58         if (msg instanceof FullHttpRequest) {
59             handleHttpRequest(ctx, (FullHttpRequest) msg);
60         } else if (msg instanceof WebSocketFrame) {
61             handleWebSocketFrame(ctx, (WebSocketFrame) msg);
62         }
63     }
64
65     /**
66      * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
67      *
68      * @param ctx
69      *            ChannelHandlerContext
70      * @param req
71      *            FullHttpRequest
72      */
73     private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
74         // Handle a bad request.
75         if (!req.getDecoderResult().isSuccess()) {
76             sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
77             return;
78         }
79
80         // Allow only GET methods.
81         if (req.getMethod() != GET) {
82             sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
83             return;
84         }
85
86         final String streamName = Notificator.createStreamNameFromUri(req.getUri());
87         if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
88             final ListenerAdapter listener = Notificator.getListenerFor(streamName);
89             if (listener != null) {
90                 listener.addSubscriber(ctx.channel());
91                 LOG.debug("Subscriber successfully registered.");
92             } else {
93                 LOG.error("Listener for stream with name '{}' was not found.", streamName);
94                 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
95             }
96         } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
97             final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
98             if (!listeners.isEmpty() && (listeners != null)) {
99                 for (final NotificationListenerAdapter listener : listeners) {
100                     listener.addSubscriber(ctx.channel());
101                     LOG.debug("Subscriber successfully registered.");
102                 }
103             } else {
104                 LOG.error("Listener for stream with name '{}' was not found.", streamName);
105                 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
106             }
107         }
108
109         // Handshake
110         final WebSocketServerHandshakerFactory wsFactory =
111                 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
112                 null, false);
113         this.handshaker = wsFactory.newHandshaker(req);
114         if (this.handshaker == null) {
115             WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
116         } else {
117             this.handshaker.handshake(ctx.channel(), req);
118         }
119
120     }
121
122     /**
123      * Checks response status, send response and close connection if necessary.
124      *
125      * @param ctx
126      *            ChannelHandlerContext
127      * @param req
128      *            HttpRequest
129      * @param res
130      *            FullHttpResponse
131      */
132     private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
133             final FullHttpResponse res) {
134         // Generate an error page if response getStatus code is not OK (200).
135         if (res.getStatus().code() != 200) {
136             final ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
137             res.content().writeBytes(buf);
138             buf.release();
139             setContentLength(res, res.content().readableBytes());
140         }
141
142         // Send the response and close the connection if necessary.
143         final ChannelFuture f = ctx.channel().writeAndFlush(res);
144         if (!isKeepAlive(req) || (res.getStatus().code() != 200)) {
145             f.addListener(ChannelFutureListener.CLOSE);
146         }
147     }
148
149     /**
150      * Handles web socket frame.
151      *
152      * @param ctx
153      *            {@link ChannelHandlerContext}
154      * @param frame
155      *            {@link WebSocketFrame}
156      */
157     private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
158         if (frame instanceof CloseWebSocketFrame) {
159             this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
160             final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
161             if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
162                 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
163                 if (listener != null) {
164                     listener.removeSubscriber(ctx.channel());
165                     LOG.debug("Subscriber successfully registered.");
166                 }
167                 Notificator.removeListenerIfNoSubscriberExists(listener);
168             } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
169                 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
170                 if (!listeners.isEmpty() && (listeners != null)) {
171                     for (final NotificationListenerAdapter listener : listeners) {
172                         listener.removeSubscriber(ctx.channel());
173                     }
174                 }
175             }
176             return;
177         } else if (frame instanceof PingWebSocketFrame) {
178             ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
179             return;
180         }
181     }
182
183     @Override
184     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
185         if (!(cause instanceof java.nio.channels.ClosedChannelException)) {
186             // LOG.info("Not expected error cause: ", cause.toString());
187         }
188         ctx.close();
189     }
190
191     /**
192      * Get web socket location from HTTP request.
193      *
194      * @param req
195      *            HTTP request from which the location will be returned
196      * @return String representation of web socket location.
197      */
198     private static String getWebSocketLocation(final HttpRequest req) {
199         return "ws://" + req.headers().get(HOST) + req.getUri();
200     }
201
202 }