2 * Copyright (c) 2014 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.controller.netconf.netty;
11 import io.netty.bootstrap.ServerBootstrap;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelHandler;
14 import io.netty.channel.ChannelInitializer;
15 import io.netty.channel.ChannelOption;
16 import io.netty.channel.EventLoopGroup;
17 import io.netty.channel.local.LocalAddress;
18 import io.netty.channel.nio.NioEventLoopGroup;
19 import io.netty.channel.socket.SocketChannel;
20 import io.netty.channel.socket.nio.NioServerSocketChannel;
21 import io.netty.handler.logging.LogLevel;
22 import io.netty.handler.logging.LoggingHandler;
23 import java.net.InetSocketAddress;
24 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
26 public class ProxyServer implements Runnable {
27 private final ProxyHandlerFactory proxyHandlerFactory;
29 public ProxyServer(ProxyHandlerFactory proxyHandlerFactory) {
30 this.proxyHandlerFactory = proxyHandlerFactory;
34 // Configure the server.
35 final EventLoopGroup bossGroup = new NioEventLoopGroup();
36 EventLoopGroup workerGroup = new NioEventLoopGroup();
38 final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();
39 ServerBootstrap serverBootstrap = new ServerBootstrap();
40 serverBootstrap.group(bossGroup, workerGroup)
41 .channel(NioServerSocketChannel.class)
42 .option(ChannelOption.SO_BACKLOG, 100)
43 .handler(new LoggingHandler(LogLevel.INFO))
44 .childHandler(new ChannelInitializer<SocketChannel>() {
46 public void initChannel(SocketChannel ch) throws Exception {
47 ch.pipeline().addLast(proxyHandlerFactory.create(bossGroup, localAddress));
52 InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
53 ChannelFuture f = serverBootstrap.bind(address).sync();
55 // Wait until the server socket is closed.
56 f.channel().closeFuture().sync();
57 } catch (Exception e) {
58 throw new RuntimeException(e);
60 // Shut down all event loops to terminate all threads.
61 bossGroup.shutdownGracefully();
62 workerGroup.shutdownGracefully();
65 public static interface ProxyHandlerFactory {
66 ChannelHandler create(EventLoopGroup bossGroup, LocalAddress localAddress);
69 public static void main(String[] args) {
70 ProxyHandlerFactory proxyHandlerFactory = new ProxyHandlerFactory() {
72 public ChannelHandler create(EventLoopGroup bossGroup, LocalAddress localAddress) {
73 return new ProxyServerHandler(bossGroup, localAddress);
76 start(proxyHandlerFactory);
79 public static void start(ProxyHandlerFactory proxyHandlerFactory) {
80 new Thread(new EchoServer()).start();
81 new Thread(new ProxyServer(proxyHandlerFactory)).start();