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.netconf.sal.streams.websockets;
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;
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;
47 * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
48 * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
50 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
52 private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
54 private WebSocketServerHandshaker handshaker;
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);
66 * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
69 * ChannelHandlerContext
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));
80 // Allow only GET methods.
81 if (req.getMethod() != GET) {
82 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
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.");
93 LOG.error("Listener for stream with name '{}' was not found.", streamName);
94 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
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.");
104 LOG.error("Listener for stream with name '{}' was not found.", streamName);
105 sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
110 final WebSocketServerHandshakerFactory wsFactory =
111 new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
113 this.handshaker = wsFactory.newHandshaker(req);
114 if (this.handshaker == null) {
115 WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
117 this.handshaker.handshake(ctx.channel(), req);
123 * Checks response status, send response and close connection if necessary.
126 * ChannelHandlerContext
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);
139 setContentLength(res, res.content().readableBytes());
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);
150 * Handles web socket frame.
153 * {@link ChannelHandlerContext}
155 * {@link WebSocketFrame}
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.");
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());
177 } else if (frame instanceof PingWebSocketFrame) {
178 ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
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());
192 * Get web socket location from HTTP request.
195 * HTTP request from which the location will be returned
196 * @return String representation of web socket location.
198 private static String getWebSocketLocation(final HttpRequest req) {
199 return "ws://" + req.headers().get(HOST) + req.getUri();