2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.restconf.nb.rfc8040.streams.websockets;
11 import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
12 import static io.netty.handler.codec.http.HttpMethod.GET;
13 import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
14 import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
15 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
16 import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
17 import static io.netty.handler.codec.http.HttpUtil.setContentLength;
18 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
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.util.List;
38 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenerAdapter;
39 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
40 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.Notificator;
41 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
47 * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
49 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
51 private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
53 private WebSocketServerHandshaker handshaker;
56 protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
57 if (msg instanceof FullHttpRequest) {
58 handleHttpRequest(ctx, (FullHttpRequest) msg);
59 } else if (msg instanceof WebSocketFrame) {
60 handleWebSocketFrame(ctx, (WebSocketFrame) msg);
65 * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
67 * @param ctx ChannelHandlerContext
68 * @param req FullHttpRequest
70 private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
71 // Handle a bad request.
72 if (!req.decoderResult().isSuccess()) {
73 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
77 // Allow only GET methods.
78 if (req.method() != GET) {
79 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
83 final String streamName = Notificator.createStreamNameFromUri(req.uri());
84 if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
85 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
86 if (listener != null) {
87 listener.addSubscriber(ctx.channel());
88 LOG.debug("Subscriber successfully registered.");
90 LOG.error("Listener for stream with name '{}' was not found.", streamName);
91 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
93 } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
94 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
95 if (listeners != null && !listeners.isEmpty()) {
96 for (final NotificationListenerAdapter listener : listeners) {
97 listener.addSubscriber(ctx.channel());
98 LOG.debug("Subscriber successfully registered.");
101 LOG.error("Listener for stream with name '{}' was not found.", streamName);
102 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
107 final WebSocketServerHandshakerFactory wsFactory =
108 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
110 this.handshaker = wsFactory.newHandshaker(req);
111 if (this.handshaker == null) {
112 WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
114 this.handshaker.handshake(ctx.channel(), req);
120 * Checks response status, send response and close connection if necessary.
122 * @param ctx ChannelHandlerContext
123 * @param req HttpRequest
124 * @param res FullHttpResponse
126 private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
127 final FullHttpResponse res) {
128 // Generate an error page if response getStatus code is not OK (200).
129 if (res.status().code() != 200) {
130 final ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
131 res.content().writeBytes(buf);
133 setContentLength(res, res.content().readableBytes());
136 // Send the response and close the connection if necessary.
137 final ChannelFuture f = ctx.channel().writeAndFlush(res);
138 if (!isKeepAlive(req) || res.status().code() != 200) {
139 f.addListener(ChannelFutureListener.CLOSE);
144 * Handles web socket frame.
147 * {@link ChannelHandlerContext}
149 * {@link WebSocketFrame}
151 private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
152 if (frame instanceof CloseWebSocketFrame) {
153 this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
154 final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
155 if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
156 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
157 if (listener != null) {
158 listener.removeSubscriber(ctx.channel());
159 LOG.debug("Subscriber successfully registered.");
160 Notificator.removeListenerIfNoSubscriberExists(listener);
162 } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
163 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
164 if (listeners != null && !listeners.isEmpty()) {
165 for (final NotificationListenerAdapter listener : listeners) {
166 listener.removeSubscriber(ctx.channel());
171 } else if (frame instanceof PingWebSocketFrame) {
172 ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
178 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
183 * Get web socket location from HTTP request.
185 * @param req HTTP request from which the location will be returned
186 * @return String representation of web socket location.
188 private static String getWebSocketLocation(final HttpRequest req) {
189 return "ws://" + req.headers().get(HOST) + req.uri();