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
8 package org.opendaylight.netconf.sal.streams.websockets;
10 import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
11 import static io.netty.handler.codec.http.HttpMethod.GET;
12 import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
13 import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
14 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
15 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
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.netconf.sal.restconf.impl.RestconfImpl;
39 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
40 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
41 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
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> {
50 private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
52 private WebSocketServerHandshaker handshaker;
55 protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
56 if (msg instanceof FullHttpRequest) {
57 handleHttpRequest(ctx, (FullHttpRequest) msg);
58 } else if (msg instanceof WebSocketFrame) {
59 handleWebSocketFrame(ctx, (WebSocketFrame) msg);
64 * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
66 * @param ctx ChannelHandlerContext
67 * @param req FullHttpRequest
69 private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
70 // Handle a bad request.
71 if (!req.decoderResult().isSuccess()) {
72 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
76 // Allow only GET methods.
77 if (req.method() != GET) {
78 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
82 final String streamName = Notificator.createStreamNameFromUri(req.uri());
83 if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
84 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
85 if (listener != null) {
86 listener.addSubscriber(ctx.channel());
87 LOG.debug("Subscriber successfully registered.");
89 LOG.error("Listener for stream with name '{}' was not found.", streamName);
90 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
92 } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
93 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
94 if (listeners != null && !listeners.isEmpty()) {
95 for (final NotificationListenerAdapter listener : listeners) {
96 listener.addSubscriber(ctx.channel());
97 LOG.debug("Subscriber successfully registered.");
100 LOG.error("Listener for stream with name '{}' was not found.", streamName);
101 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
106 final WebSocketServerHandshakerFactory wsFactory =
107 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
109 this.handshaker = wsFactory.newHandshaker(req);
110 if (this.handshaker == null) {
111 WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
113 this.handshaker.handshake(ctx.channel(), req);
118 * Checks response status, send response and close connection if necessary.
120 * @param ctx ChannelHandlerContext
121 * @param req HttpRequest
122 * @param res FullHttpResponse
124 private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
125 final FullHttpResponse res) {
126 // Generate an error page if response getStatus code is not OK (200).
127 final boolean notOkay = !OK.equals(res.status());
129 final ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
130 res.content().writeBytes(buf);
132 setContentLength(res, res.content().readableBytes());
135 // Send the response and close the connection if necessary.
136 final ChannelFuture f = ctx.channel().writeAndFlush(res);
137 if (notOkay || !isKeepAlive(req)) {
138 f.addListener(ChannelFutureListener.CLOSE);
143 * Handles web socket frame.
145 * @param ctx {@link ChannelHandlerContext}
146 * @param frame {@link WebSocketFrame}
148 private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
149 if (frame instanceof CloseWebSocketFrame) {
150 this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
151 final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
152 if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
153 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
154 if (listener != null) {
155 listener.removeSubscriber(ctx.channel());
156 LOG.debug("Subscriber successfully registered.");
158 Notificator.removeListenerIfNoSubscriberExists(listener);
160 } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
161 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
162 if (listeners != null && !listeners.isEmpty()) {
163 for (final NotificationListenerAdapter listener : listeners) {
164 listener.removeSubscriber(ctx.channel());
169 } else if (frame instanceof PingWebSocketFrame) {
170 ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
176 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
181 * Get web socket location from HTTP request.
183 * @param req HTTP request from which the location will be returned
184 * @return String representation of web socket location.
186 private static String getWebSocketLocation(final HttpRequest req) {
187 return "ws://" + req.headers().get(HOST) + req.uri();