Merge "Changed lookup of Controller IP to the following: - Start with OVSDB config...
[netvirt.git] / ovsdb / 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.*;
14 import io.netty.channel.nio.NioEventLoopGroup;
15 import io.netty.channel.socket.SocketChannel;
16 import io.netty.channel.socket.nio.NioServerSocketChannel;
17
18 import java.util.concurrent.TimeUnit;
19
20 public class NettyBootStrapper {
21
22     EventLoopGroup bossGroup = null;
23     EventLoopGroup workerGroup = null;
24     ChannelFuture f = null;
25
26     public ChannelFuture startServer(int localPort, final ChannelHandler... handlers) throws Exception {
27         // Configure the server.
28         bossGroup = new NioEventLoopGroup();
29         workerGroup = new NioEventLoopGroup();
30         ServerBootstrap b = new ServerBootstrap();
31         b.group(bossGroup, workerGroup)
32                 .channel(NioServerSocketChannel.class)
33                 .option(ChannelOption.SO_BACKLOG, 100)
34                 .localAddress(localPort)
35                 .childOption(ChannelOption.TCP_NODELAY, true)
36                 .childHandler(new ChannelInitializer<SocketChannel>() {
37
38                     @Override
39                     public void initChannel(SocketChannel ch) throws Exception {
40                         for (ChannelHandler handler : handlers) {
41                             ch.pipeline().addLast(handler);
42                         }
43                     }
44                 });
45
46         // Start the server.
47         f = b.bind().sync();
48         return f;
49     }
50
51     public void stopServer() throws InterruptedException {
52         try {
53
54             ChannelFuture channelFuture = f.channel().closeFuture();
55             channelFuture.get(1000, TimeUnit.MILLISECONDS);
56             if (!channelFuture.isDone()) {
57                 f.channel().unsafe().closeForcibly();
58             }
59
60             bossGroup.shutdownGracefully();
61             workerGroup.shutdownGracefully();
62
63             // Wait until all threads are terminated.
64             bossGroup.terminationFuture().sync();
65             workerGroup.terminationFuture().sync();
66         } catch (Exception e) {
67             //ignore
68         }
69     }
70
71 }