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.netconf.netty;
11 import io.netty.bootstrap.Bootstrap;
12 import io.netty.buffer.Unpooled;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import io.netty.channel.ChannelInitializer;
18 import io.netty.channel.EventLoopGroup;
19 import io.netty.channel.local.LocalAddress;
20 import io.netty.channel.local.LocalChannel;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 public class ProxyServerHandler extends ChannelInboundHandlerAdapter {
25 private static final Logger LOG = LoggerFactory.getLogger(ProxyServerHandler.class);
26 private final Bootstrap clientBootstrap;
27 private final LocalAddress localAddress;
30 private Channel clientChannel;
32 public ProxyServerHandler(EventLoopGroup bossGroup, LocalAddress localAddress) {
33 clientBootstrap = new Bootstrap();
34 clientBootstrap.group(bossGroup).channel(LocalChannel.class);
35 this.localAddress = localAddress;
39 public void channelActive(ChannelHandlerContext remoteCtx) {
40 final ProxyClientHandler clientHandler = new ProxyClientHandler(remoteCtx);
41 clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
43 public void initChannel(LocalChannel ch) throws Exception {
44 ch.pipeline().addLast(clientHandler);
47 ChannelFuture clientChannelFuture = clientBootstrap.connect(localAddress).awaitUninterruptibly();
48 clientChannel = clientChannelFuture.channel();
49 clientChannel.writeAndFlush(Unpooled.copiedBuffer("connected\n".getBytes()));
53 public void channelInactive(ChannelHandlerContext ctx) {
54 LOG.info("channelInactive - closing client connection");
55 clientChannel.close();
59 public void channelRead(ChannelHandlerContext ctx, final Object msg) {
60 LOG.debug("Writing to client {}", msg);
61 clientChannel.write(msg);
65 public void channelReadComplete(ChannelHandlerContext ctx) {
66 LOG.debug("flushing");
67 clientChannel.flush();
71 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
72 // Close the connection when an exception is raised.
73 LOG.warn("Unexpected exception from downstream.", cause);