Merge "BUG-868: use a single version of ClassLoaderUtils"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / streams / websockets / WebSocketServer.java
1 package org.opendaylight.controller.sal.streams.websockets;
2
3 import io.netty.bootstrap.ServerBootstrap;
4 import io.netty.channel.Channel;
5 import io.netty.channel.EventLoopGroup;
6 import io.netty.channel.nio.NioEventLoopGroup;
7 import io.netty.channel.socket.nio.NioServerSocketChannel;
8
9 import org.opendaylight.controller.sal.streams.listeners.Notificator;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12
13 /**
14  * {@link WebSocketServer} is responsible to start and stop web socket server at
15  * {@link #PORT}.
16  */
17 public class WebSocketServer implements Runnable {
18
19     private static final Logger logger = LoggerFactory
20             .getLogger(WebSocketServer.class);
21
22     public static final int PORT = 8181;
23     private EventLoopGroup bossGroup;
24     private EventLoopGroup workerGroup;
25
26     @Override
27     public void run() {
28         bossGroup = new NioEventLoopGroup();
29         workerGroup = new NioEventLoopGroup();
30         try {
31             ServerBootstrap b = new ServerBootstrap();
32             b.group(bossGroup, workerGroup)
33                     .channel(NioServerSocketChannel.class)
34                     .childHandler(new WebSocketServerInitializer());
35
36             Channel ch = b.bind(PORT).sync().channel();
37             logger.info("Web socket server started at port {}.", PORT);
38
39             ch.closeFuture().sync();
40         } catch (InterruptedException e) {
41             // NOOP
42         } finally {
43             stop();
44         }
45     }
46
47     /**
48      * Stops the web socket server and removes all listeners.
49      */
50     private void stop() {
51         Notificator.removeAllListeners();
52         if (bossGroup != null) {
53             bossGroup.shutdownGracefully();
54         }
55         if (workerGroup != null) {
56             workerGroup.shutdownGracefully();
57         }
58     }
59
60 }