Merge "Make TCP netconf endpoint configurable" into stable/lithium
[controller.git] / opendaylight / netconf / netconf-tcp / src / main / java / org / opendaylight / controller / config / yang / netconf / northbound / tcp / NetconfNorthboundTcpModule.java
1 package org.opendaylight.controller.config.yang.netconf.northbound.tcp;
2
3 import io.netty.channel.ChannelFuture;
4 import java.net.InetAddress;
5 import java.net.InetSocketAddress;
6 import java.net.UnknownHostException;
7 import org.opendaylight.controller.netconf.api.NetconfServerDispatcher;
8
9 public class NetconfNorthboundTcpModule extends org.opendaylight.controller.config.yang.netconf.northbound.tcp.AbstractNetconfNorthboundTcpModule {
10     public NetconfNorthboundTcpModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
11         super(identifier, dependencyResolver);
12     }
13
14     public NetconfNorthboundTcpModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.netconf.northbound.tcp.NetconfNorthboundTcpModule oldModule, java.lang.AutoCloseable oldInstance) {
15         super(identifier, dependencyResolver, oldModule, oldInstance);
16     }
17
18     @Override
19     public void customValidation() {
20         // add custom validation form module attributes here.
21     }
22
23     @Override
24     public java.lang.AutoCloseable createInstance() {
25         final NetconfServerDispatcher dispatch = getDispatcherDependency();
26         final ChannelFuture tcpServer = dispatch.createServer(getInetAddress());
27         return new NetconfServerCloseable(tcpServer);
28     }
29
30     private InetSocketAddress getInetAddress() {
31         try {
32             final InetAddress inetAd = InetAddress.getByName(getBindingAddress().getIpv4Address() == null ? getBindingAddress().getIpv6Address().getValue() : getBindingAddress().getIpv4Address().getValue());
33             return new InetSocketAddress(inetAd, getPort().getValue());
34         } catch (final UnknownHostException e) {
35             throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + getBindingAddress(), e);
36         }
37     }
38
39     private static final class NetconfServerCloseable implements AutoCloseable {
40         private final ChannelFuture localServer;
41
42         public NetconfServerCloseable(final ChannelFuture localServer) {
43             this.localServer = localServer;
44         }
45
46         @Override
47         public void close() throws Exception {
48             if(localServer.isDone()) {
49                 localServer.channel().close();
50             } else {
51                 localServer.cancel(true);
52             }
53         }
54     }
55
56 }