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.channel.ChannelFuture;
21 import io.netty.channel.ChannelFutureListener;
22 import io.netty.channel.ChannelHandlerContext;
23 import io.netty.channel.SimpleChannelInboundHandler;
24 import io.netty.handler.codec.http.DefaultFullHttpResponse;
25 import io.netty.handler.codec.http.FullHttpRequest;
26 import io.netty.handler.codec.http.FullHttpResponse;
27 import io.netty.handler.codec.http.HttpRequest;
28 import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
29 import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
30 import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
31 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
32 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
33 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
34 import io.netty.util.CharsetUtil;
35 import java.util.List;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
37 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
38 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
39 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
45 * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
47 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
48 private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
50 private WebSocketServerHandshaker handshaker;
53 protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
54 if (msg instanceof FullHttpRequest) {
55 handleHttpRequest(ctx, (FullHttpRequest) msg);
56 } else if (msg instanceof WebSocketFrame) {
57 handleWebSocketFrame(ctx, (WebSocketFrame) msg);
62 * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
64 * @param ctx ChannelHandlerContext
65 * @param req FullHttpRequest
67 private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) {
68 // Handle a bad request.
69 if (!req.decoderResult().isSuccess()) {
70 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
74 // Allow only GET methods.
75 if (req.method() != GET) {
76 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
80 final String streamName = Notificator.createStreamNameFromUri(req.uri());
81 if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
82 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
83 if (listener != null) {
84 listener.addSubscriber(ctx.channel());
85 LOG.debug("Subscriber successfully registered.");
87 LOG.error("Listener for stream with name '{}' was not found.", streamName);
88 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
90 } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
91 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
92 if (listeners != null && !listeners.isEmpty()) {
93 for (final NotificationListenerAdapter listener : listeners) {
94 listener.addSubscriber(ctx.channel());
95 LOG.debug("Subscriber successfully registered.");
98 LOG.error("Listener for stream with name '{}' was not found.", streamName);
99 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
104 final WebSocketServerHandshakerFactory wsFactory =
105 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
107 this.handshaker = wsFactory.newHandshaker(req);
108 if (this.handshaker == null) {
109 WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
111 this.handshaker.handshake(ctx.channel(), req);
116 * Checks response status, send response and close connection if necessary.
118 * @param ctx ChannelHandlerContext
119 * @param req HttpRequest
120 * @param res FullHttpResponse
122 private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
123 final FullHttpResponse res) {
124 // Generate an error page if response getStatus code is not OK (200).
125 final boolean notOkay = !OK.equals(res.status());
127 res.content().writeCharSequence(res.status().toString(), CharsetUtil.UTF_8);
128 setContentLength(res, res.content().readableBytes());
131 // Send the response and close the connection if necessary.
132 final ChannelFuture f = ctx.channel().writeAndFlush(res);
133 if (notOkay || !isKeepAlive(req)) {
134 f.addListener(ChannelFutureListener.CLOSE);
139 * Handles web socket frame.
141 * @param ctx {@link ChannelHandlerContext}
142 * @param frame {@link WebSocketFrame}
144 private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {
145 if (frame instanceof CloseWebSocketFrame) {
146 this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
147 final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
148 if (streamName.contains(RestconfImpl.DATA_SUBSCR)) {
149 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
150 if (listener != null) {
151 listener.removeSubscriber(ctx.channel());
152 LOG.debug("Subscriber successfully registered.");
154 Notificator.removeListenerIfNoSubscriberExists(listener);
156 } else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
157 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
158 if (listeners != null && !listeners.isEmpty()) {
159 for (final NotificationListenerAdapter listener : listeners) {
160 listener.removeSubscriber(ctx.channel());
165 } else if (frame instanceof PingWebSocketFrame) {
166 ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
172 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
177 * Get web socket location from HTTP request.
179 * @param req HTTP request from which the location will be returned
180 * @return String representation of web socket location.
182 private static String getWebSocketLocation(final HttpRequest req) {
183 return "ws://" + req.headers().get(HOST) + req.uri();