Code ReOrganization and Re-Architecture changes
[ovsdb.git] / library / src / test / java / org / opendaylight / ovsdb / lib / jsonrpc / NettyBootStrapper.java
1 /*
2  * Copyright (C) 2013 EBay Software Foundation
3  *
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
7  *
8  * Authors : Aswin Raveendran
9  */
10 package org.opendaylight.ovsdb.lib.jsonrpc;
11
12 import io.netty.bootstrap.ServerBootstrap;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.channel.ChannelHandler;
15 import io.netty.channel.ChannelInitializer;
16 import io.netty.channel.ChannelOption;
17 import io.netty.channel.EventLoopGroup;
18 import io.netty.channel.nio.NioEventLoopGroup;
19 import io.netty.channel.socket.SocketChannel;
20 import io.netty.channel.socket.nio.NioServerSocketChannel;
21
22 import java.util.concurrent.TimeUnit;
23
24 public class NettyBootStrapper {
25
26     EventLoopGroup bossGroup = null;
27     EventLoopGroup workerGroup = null;
28     ChannelFuture f = null;
29
30     public ChannelFuture startServer(int localPort, final ChannelHandler... handlers) throws Exception {
31         // Configure the server.
32         bossGroup = new NioEventLoopGroup();
33         workerGroup = new NioEventLoopGroup();
34         ServerBootstrap b = new ServerBootstrap();
35         b.group(bossGroup, workerGroup)
36                 .channel(NioServerSocketChannel.class)
37                 .option(ChannelOption.SO_BACKLOG, 100)
38                 .localAddress(localPort)
39                 .childOption(ChannelOption.TCP_NODELAY, true)
40                 .childHandler(new ChannelInitializer<SocketChannel>() {
41
42                     @Override
43                     public void initChannel(SocketChannel ch) throws Exception {
44                         for (ChannelHandler handler : handlers) {
45                             ch.pipeline().addLast(handler);
46                         }
47                     }
48                 });
49
50         // Start the server.
51         f = b.bind().sync();
52         return f;
53     }
54
55     public void stopServer() throws InterruptedException {
56         try {
57
58             ChannelFuture channelFuture = f.channel().closeFuture();
59             channelFuture.get(1000, TimeUnit.MILLISECONDS);
60             if (!channelFuture.isDone()) {
61                 f.channel().unsafe().closeForcibly();
62             }
63
64             bossGroup.shutdownGracefully();
65             workerGroup.shutdownGracefully();
66
67             // Wait until all threads are terminated.
68             bossGroup.terminationFuture().sync();
69             workerGroup.terminationFuture().sync();
70         } catch (Exception e) {
71             //ignore
72         }
73     }
74
75 }