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.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 import io.netty.buffer.ByteBuf;
20 import io.netty.buffer.Unpooled;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.ChannelFutureListener;
23 import io.netty.channel.ChannelHandlerContext;
24 import io.netty.channel.SimpleChannelInboundHandler;
25 import io.netty.handler.codec.http.DefaultFullHttpResponse;
26 import io.netty.handler.codec.http.FullHttpRequest;
27 import io.netty.handler.codec.http.FullHttpResponse;
28 import io.netty.handler.codec.http.HttpRequest;
29 import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
30 import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
31 import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
32 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
33 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
34 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
35 import io.netty.util.CharsetUtil;
36 import java.io.IOException;
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) throws Exception {
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.
68 * ChannelHandlerContext
72 private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
73 // Handle a bad request.
74 if (!req.getDecoderResult().isSuccess()) {
75 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
79 // Allow only GET methods.
80 if (req.getMethod() != GET) {
81 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
85 final String streamName = Notificator.createStreamNameFromUri(req.getUri());
86 if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
87 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
88 if (listener != null) {
89 listener.addSubscriber(ctx.channel());
90 LOG.debug("Subscriber successfully registered.");
92 LOG.error("Listener for stream with name '{}' was not found.", streamName);
93 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
95 } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
96 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
97 if (!listeners.isEmpty() && (listeners != null)) {
98 for (final NotificationListenerAdapter listener : listeners) {
99 listener.addSubscriber(ctx.channel());
100 LOG.debug("Subscriber successfully registered.");
103 LOG.error("Listener for stream with name '{}' was not found.", streamName);
104 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
109 final WebSocketServerHandshakerFactory wsFactory =
110 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
112 this.handshaker = wsFactory.newHandshaker(req);
113 if (this.handshaker == null) {
114 WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
116 this.handshaker.handshake(ctx.channel(), req);
122 * Checks response status, send response and close connection if necessary.
125 * ChannelHandlerContext
131 private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
132 final FullHttpResponse res) {
133 // Generate an error page if response getStatus code is not OK (200).
134 if (res.getStatus().code() != 200) {
135 final ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
136 res.content().writeBytes(buf);
138 setContentLength(res, res.content().readableBytes());
141 // Send the response and close the connection if necessary.
142 final ChannelFuture f = ctx.channel().writeAndFlush(res);
143 if (!isKeepAlive(req) || (res.getStatus().code() != 200)) {
144 f.addListener(ChannelFutureListener.CLOSE);
149 * Handles web socket frame.
152 * {@link ChannelHandlerContext}
154 * {@link WebSocketFrame}
156 private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
157 if (frame instanceof CloseWebSocketFrame) {
158 this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
159 final String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
160 if (streamName.contains(RestconfConstants.DATA_SUBSCR)) {
161 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
162 if (listener != null) {
163 listener.removeSubscriber(ctx.channel());
164 LOG.debug("Subscriber successfully registered.");
166 Notificator.removeListenerIfNoSubscriberExists(listener);
167 } else if (streamName.contains(RestconfConstants.NOTIFICATION_STREAM)) {
168 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
169 if (!listeners.isEmpty() && (listeners != null)) {
170 for (final NotificationListenerAdapter listener : listeners) {
171 listener.removeSubscriber(ctx.channel());
176 } else if (frame instanceof PingWebSocketFrame) {
177 ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
183 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
184 if (!(cause instanceof java.nio.channels.ClosedChannelException)) {
185 // LOG.info("Not expected error cause: ", cause.toString());
191 * Get web socket location from HTTP request.
194 * HTTP request from which the location will be returned
195 * @return String representation of web socket location.
197 private static String getWebSocketLocation(final HttpRequest req) {
198 return "ws://" + req.headers().get(HOST) + req.getUri();