Merge changes from topic 'bug/6023'
authorJakub Morvay <jmorvay@cisco.com>
Mon, 7 Nov 2016 11:59:29 +0000 (11:59 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 7 Nov 2016 11:59:29 +0000 (11:59 +0000)
* changes:
  Add netconf-util tests for package org.opendaylight.netconf.util.osgi
  Bug 6023 - Adress for config subsystem netconf endpoint is not configurable

15 files changed:
netconf/netconf-impl/pom.xml
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfImplActivator.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/osgi/NetconfTCPActivator.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationActivator.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationHolder.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationActivatorTest.java [new file with mode: 0644]
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationTest.java [new file with mode: 0644]

index a4ff368ca7215bacbed181196842c6859890167a..c78eb147a937f2a6aa6eae4c7eb8f57196e6de27 100644 (file)
       <artifactId>xmlunit</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.osgi</groupId>
+      <artifactId>org.osgi.compendium</artifactId>
+    </dependency>
   </dependencies>
 
   <build>
index 9d520bea56b82da45857f9e4029c24882d69762c..8feaef6aedc9366381d35cea1a9cc78a8599edf0 100644 (file)
@@ -24,6 +24,7 @@ import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactoryListen
 import org.opendaylight.netconf.notifications.BaseNotificationPublisherRegistration;
 import org.opendaylight.netconf.notifications.NetconfNotificationCollector;
 import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
+import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceReference;
@@ -52,7 +53,8 @@ public class NetconfImplActivator implements BundleActivator {
 
             SessionIdProvider idProvider = new SessionIdProvider();
             timer = new HashedWheelTimer();
-            long connectionTimeoutMillis = NetconfConfigUtil.extractTimeoutMillis(context);
+
+            long connectionTimeoutMillis = NetconfConfiguration.DEFAULT_TIMEOUT_MILLIS;
 
             final NetconfMonitoringServiceImpl monitoringService = startMonitoringService(context, factoriesListener);
 
@@ -70,7 +72,7 @@ public class NetconfImplActivator implements BundleActivator {
                     serverNegotiatorFactory);
             NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
 
-            LocalAddress address = NetconfConfigUtil.getNetconfLocalAddress();
+            LocalAddress address = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
             LOG.trace("Starting local netconf server at {}", address);
             dispatch.createLocalServer(address);
 
index 14cbae81e1891edb357717c5f0dfc88e88dcd545..537ea993d1b113b5b46d76b06fd777ed13dca151 100644 (file)
@@ -84,7 +84,7 @@ public class NetconfSSHActivator implements BundleActivator {
         final InetSocketAddress sshSocketAddress = netconfConfiguration.getSshServerAddress();
         LOG.info("Starting netconf SSH server at {}", sshSocketAddress);
 
-        final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();
+        final LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
         authProviderTracker = new AuthProviderTracker(bundleContext);
 
         final String path = netconfConfiguration.getPrivateKeyPath();
index 53a54dc601ef6525c5d3aa6cb638b7a39100352c..a6f9e6cb66595bd0616c35774684571fe683a11b 100644 (file)
@@ -21,7 +21,7 @@ import io.netty.handler.logging.LogLevel;
 import io.netty.handler.logging.LoggingHandler;
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
-import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
+import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,7 +49,7 @@ public class EchoServer implements Runnable {
                     });
 
             // Start the server.
-            LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();
+            LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
             ChannelFuture f = b.bind(localAddress).sync();
 
             // Wait until the server socket is closed.
index 8294a35c954b3326f42c87d27466907f83aec515..2d9b67d42dd7dd2d54759747f2d61a9767f31935 100644 (file)
@@ -22,6 +22,7 @@ import io.netty.handler.logging.LogLevel;
 import io.netty.handler.logging.LoggingHandler;
 import java.net.InetSocketAddress;
 import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
+import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 
 public class ProxyServer implements Runnable {
     private final ProxyHandlerFactory proxyHandlerFactory;
@@ -35,7 +36,7 @@ public class ProxyServer implements Runnable {
         final EventLoopGroup bossGroup = new NioEventLoopGroup();
         EventLoopGroup workerGroup = new NioEventLoopGroup();
         try {
-            final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();
+            final LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
             ServerBootstrap serverBootstrap = new ServerBootstrap();
             serverBootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel.class)
index b7379808cf3d941374abd6b4f025b59c3243771e..759b96210bdd068c05f1a6309b223c3d026e40ab 100644 (file)
@@ -36,7 +36,7 @@ import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswo
 import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
 import org.opendaylight.netconf.ssh.SshProxyServer;
 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
-import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
+import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -74,7 +74,7 @@ public class SSHTest {
         final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831);
         final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec);
         sshProxyServer.bind(
-                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()).setAuthenticator(new AuthProvider() {
+                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
                     @Override
                     public boolean authenticated(final String username, final String password) {
                         return true;
index f0350247187a925132de8aae7fab374d863bc0ca..7c7ef6383d9882e1ae5887b73688d00062e6238a 100644 (file)
@@ -34,6 +34,7 @@ import org.opendaylight.netconf.auth.AuthProvider;
 import org.opendaylight.netconf.ssh.SshProxyServer;
 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
 import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
+import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceListener;
 import org.osgi.framework.ServiceReference;
@@ -73,7 +74,7 @@ public class SSHServerTest {
         final InetSocketAddress addr = InetSocketAddress.createUnresolved(HOST, PORT);
         server = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
         server.bind(
-                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()).setAuthenticator(new AuthProvider() {
+                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
                     @Override
                     public boolean authenticated(final String username, final String password) {
                         return true;
index d972a32ba70c9ede29a146cdc572bd610f979862..2d6798cfb75298f8b7c6d77d40c0e8c6274e2ef6 100644 (file)
@@ -11,7 +11,6 @@ package org.opendaylight.netconf.tcp.osgi;
 import java.net.InetSocketAddress;
 import org.opendaylight.netconf.tcp.netty.ProxyServer;
 import org.opendaylight.netconf.util.osgi.NetconfConfigUtil;
-import org.opendaylight.netconf.util.osgi.NetconfConfigUtil.InfixProp;
 import org.opendaylight.netconf.util.osgi.NetconfConfiguration;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
@@ -33,11 +32,11 @@ public class NetconfTCPActivator implements BundleActivator {
         final InetSocketAddress address = netconfConfiguration.getTcpServerAddress();
 
         if (address.getAddress().isAnyLocalAddress()) {
-            LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. Consider changing {} to 127.0.0.1",
-                    NetconfConfigUtil.getNetconfServerAddressKey(InfixProp.tcp));
+            LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. " +
+                            "Consider changing tcp-address in netconf.cfg to 127.0.0.1");
         }
         LOG.info("Starting TCP netconf server at {}", address);
-        proxyServer = new ProxyServer(address, NetconfConfigUtil.getNetconfLocalAddress());
+        proxyServer = new ProxyServer(address, NetconfConfiguration.NETCONF_LOCAL_ADDRESS);
     }
 
     @Override
index 9d4b5a123839fa39eaa39a119560dc116deb7cb3..63bec7c525362593537c2dd2b48824ec73f15613 100644 (file)
@@ -8,11 +8,8 @@
 
 package org.opendaylight.netconf.util.osgi;
 
-import com.google.common.base.Optional;
-import io.netty.channel.local.LocalAddress;
-import java.net.InetSocketAddress;
 import java.util.Collection;
-import java.util.concurrent.TimeUnit;
+import java.util.Optional;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
@@ -23,111 +20,23 @@ import org.slf4j.LoggerFactory;
 public final class NetconfConfigUtil {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfConfigUtil.class);
 
-    private static final String PREFIX_PROP = "netconf.";
-
     private NetconfConfigUtil() {
     }
 
-    public enum InfixProp {
-        tcp, ssh
-    }
-
-    private static final String PORT_SUFFIX_PROP = ".port";
-    private static final String ADDRESS_SUFFIX_PROP = ".address";
-    private static final String PRIVATE_KEY_PATH_PROP = ".pk.path";
-
-    private static final String CONNECTION_TIMEOUT_MILLIS_PROP = "connectionTimeoutMillis";
-    private static final String LOCAL_HOST = "127.0.0.1";
-    private static final String INADDR_ANY = "0.0.0.0";
-    public static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(30);
-    private static final LocalAddress NETCONF_LOCAL_ADDRESS = new LocalAddress("netconf");
-    public static final String DEFAULT_PRIVATE_KEY_PATH = "./configuration/RSA.pk";
-    public static final InetSocketAddress DEFAULT_TCP_SERVER_ADRESS = new InetSocketAddress(LOCAL_HOST, 8383);
-    public static final InetSocketAddress DEFAULT_SSH_SERVER_ADRESS = new InetSocketAddress(INADDR_ANY, 1830);
-
-    public static LocalAddress getNetconfLocalAddress() {
-        return NETCONF_LOCAL_ADDRESS;
-    }
-
-    public static long extractTimeoutMillis(final BundleContext bundleContext) {
-        final String key = PREFIX_PROP + CONNECTION_TIMEOUT_MILLIS_PROP;
-        final String timeoutString = bundleContext.getProperty(key);
-        if (timeoutString == null || timeoutString.length() == 0) {
-            return DEFAULT_TIMEOUT_MILLIS;
-        }
-        try {
-            return Long.parseLong(timeoutString);
-        } catch (final NumberFormatException e) {
-            LOG.warn("Cannot parse {} property: {}, using defaults", key, timeoutString, e);
-            return DEFAULT_TIMEOUT_MILLIS;
-        }
-    }
-
-    /**
-     * @param context from which properties are being read.
-     * @return value of private key path if value is present, Optional.absent otherwise
-     */
-    public static Optional<String> getPrivateKeyPath(final BundleContext context) {
-        return getProperty(context, getPrivateKeyKey());
-    }
-
-    public static String getPrivateKeyKey() {
-        return PREFIX_PROP + InfixProp.ssh + PRIVATE_KEY_PATH_PROP;
-    }
-
-    public static String getNetconfServerAddressKey(final InfixProp infixProp) {
-        return PREFIX_PROP + infixProp + ADDRESS_SUFFIX_PROP;
-    }
-
-    /**
-     * @param context   from which properties are being read.
-     * @param infixProp either tcp or ssh
-     * @return value if address and port are present and valid, Optional.absent otherwise.
-     */
-    public static Optional<InetSocketAddress> extractNetconfServerAddress(final BundleContext context,
-                                                                           final InfixProp infixProp) {
-
-        final Optional<String> address = getProperty(context, getNetconfServerAddressKey(infixProp));
-        final Optional<String> port = getProperty(context, PREFIX_PROP + infixProp + PORT_SUFFIX_PROP);
-
-        if (address.isPresent() && port.isPresent()) {
-            try {
-                return Optional.of(parseAddress(address, port));
-            } catch (final IllegalArgumentException | SecurityException e) {
-                LOG.warn("Unable to parse {} netconf address from {}:{}, fallback to default",
-                        infixProp, address, port, e);
-            }
-        }
-        return Optional.absent();
-    }
-
-    private static InetSocketAddress parseAddress(final Optional<String> address, final Optional<String> port) {
-        final int portNumber = Integer.valueOf(port.get());
-        return new InetSocketAddress(address.get(), portNumber);
-    }
-
-    private static Optional<String> getProperty(final BundleContext context, final String propKey) {
-        String value = context.getProperty(propKey);
-        if (value != null && value.isEmpty()) {
-            value = null;
-        }
-        return Optional.fromNullable(value);
-    }
-
-    public static java.util.Optional<NetconfConfiguration> getNetconfConfigurationService(BundleContext bundleContext) {
+    public static Optional<NetconfConfiguration> getNetconfConfigurationService(BundleContext bundleContext) {
         final Collection<ServiceReference<ManagedService>> serviceReferences;
         try {
             serviceReferences = bundleContext.getServiceReferences(ManagedService.class, null);
             for (final ServiceReference<ManagedService> serviceReference : serviceReferences) {
                 ManagedService service = bundleContext.getService(serviceReference);
                 if (service instanceof NetconfConfiguration){
-                    return java.util.Optional.of((NetconfConfiguration) service);
+                    return Optional.of((NetconfConfiguration) service);
                 }
             }
         } catch (InvalidSyntaxException e) {
             LOG.error("Unable to retrieve references for ManagedService: {}", e);
         }
-        LOG.error("Unable to retrieve NetconfConfiguration service. Not found. Bundle netconf-util probably failed.");
-        return java.util.Optional.empty();
+        LOG.error("Unable to retrieve NetconfConfiguration service. Not found. Bundle netconf-util probably failed to load.");
+        return Optional.empty();
     }
 }
index e33f7e2e71fa55c0f0a10515a9c54bea4d610f97..bf935dee867906e0889997a0f7bdea142321d9a2 100644 (file)
@@ -8,8 +8,10 @@
 
 package org.opendaylight.netconf.util.osgi;
 
+import io.netty.channel.local.LocalAddress;
 import java.net.InetSocketAddress;
 import java.util.Dictionary;
+import java.util.concurrent.TimeUnit;
 import org.osgi.service.cm.ManagedService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -17,39 +19,61 @@ import org.slf4j.LoggerFactory;
 public class NetconfConfiguration implements ManagedService {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfConfiguration.class);
 
-    private static final NetconfConfiguration instance = new NetconfConfiguration();
-    private NetconfConfigurationHolder netconfConfiguration;
+    /**
+     * Props to access information within the dictionary.
+     */
+
+    private static final String SSH_ADDRESS_PROP = "ssh-address";
+    private static final String SSH_PORT_PROP = "ssh-port";
+    private static final String TCP_ADDRESS_PROP = "tcp-address";
+    private static final String TCP_PORT_PROP = "tcp-port";
+    private static final String SSH_PK_PATH_PROP = "ssh-pk-path";
+
+    /**
+     * Default values used if no dictionary is provided.
+     */
+
+    public static final LocalAddress NETCONF_LOCAL_ADDRESS = new LocalAddress("netconf");
+    public static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(30);
 
-    public static final String KEY_SSH_ADDRESS = "ssh-address";
-    public static final String KEY_SSH_PORT = "ssh-port";
-    public static final String KEY_TCP_ADDRESS = "tcp-address";
-    public static final String KEY_TCP_PORT = "tcp-port";
-    public static final String KEY_SSH_PK_PATH = "ssh-pk-path";
+    private static final String LOCAL_HOST = "127.0.0.1";
+    private static final String INADDR_ANY = "0.0.0.0";
+    private static final String DEFAULT_PRIVATE_KEY_PATH = "./configuration/RSA.pk";
+    private static final InetSocketAddress DEFAULT_TCP_SERVER_ADRESS = new InetSocketAddress(LOCAL_HOST, 8383);
+    private static final InetSocketAddress DEFAULT_SSH_SERVER_ADRESS = new InetSocketAddress(INADDR_ANY, 1830);
+
+    /**
+     * Singleton instance of this class, registered as a service in the OSGi registry.
+     */
+    private static final NetconfConfiguration INSTANCE = new NetconfConfiguration();
+
+    private NetconfConfigurationHolder netconfConfiguration;
 
     public static NetconfConfiguration getInstance() {
-        return instance;
+        return INSTANCE;
     }
 
     private NetconfConfiguration() {
-        netconfConfiguration = new NetconfConfigurationHolder(NetconfConfigUtil.DEFAULT_TCP_SERVER_ADRESS,
-                NetconfConfigUtil.DEFAULT_SSH_SERVER_ADRESS, NetconfConfigUtil.DEFAULT_PRIVATE_KEY_PATH);
+        netconfConfiguration = new NetconfConfigurationHolder(DEFAULT_TCP_SERVER_ADRESS,
+                DEFAULT_SSH_SERVER_ADRESS, DEFAULT_PRIVATE_KEY_PATH);
     }
 
     @Override
     public void updated(final Dictionary<String, ?> dictionaryConfig) {
         if (dictionaryConfig == null) {
-            LOG.warn("Netconf configuration cannot be updated.");
+            LOG.trace("CSS netconf server configuration cannot be updated as passed dictionary is null");
             return;
         }
-        final InetSocketAddress sshServerAddress = new InetSocketAddress((String) dictionaryConfig.get(KEY_SSH_ADDRESS),
-                Integer.parseInt((String) dictionaryConfig.get(KEY_SSH_PORT)));
-        final InetSocketAddress tcpServerAddress = new InetSocketAddress((String) dictionaryConfig.get(KEY_TCP_ADDRESS),
-                Integer.parseInt((String) dictionaryConfig.get(KEY_TCP_PORT)));
+        final InetSocketAddress sshServerAddress = new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP),
+                Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP)));
+        final InetSocketAddress tcpServerAddress = new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP),
+                Integer.parseInt((String) dictionaryConfig.get(TCP_PORT_PROP)));
 
-        netconfConfiguration = new NetconfConfigurationHolder(tcpServerAddress, sshServerAddress,
-                (String) dictionaryConfig.get(KEY_SSH_PK_PATH));
+        netconfConfiguration = new NetconfConfigurationHolder(tcpServerAddress,
+                sshServerAddress,
+                (String) dictionaryConfig.get(SSH_PK_PATH_PROP));
 
-        LOG.info("Netconf configuration was updated: {}", dictionaryConfig.toString());
+        LOG.debug("CSS netconf server configuration was updated: {}", dictionaryConfig.toString());
     }
 
     public InetSocketAddress getSshServerAddress(){
index a752322d5042131834b3f06cade1ad630c7c9f98..99371503b589b53e4394d4bd71bab3f898f9e58a 100644 (file)
@@ -28,12 +28,12 @@ public class NetconfConfigurationActivator implements BundleActivator {
     @Override
     public void stop(BundleContext bundleContext) {
         if (configService != null) {
-          configService.unregister();
-          configService = null;
+            configService.unregister();
+            configService = null;
         }
     }
 
-    private Hashtable<String, String> getNetconfConfigProperties(){
+    private Hashtable<String, String> getNetconfConfigProperties() {
         Hashtable<String, String> properties = new Hashtable<>();
         properties.put(Constants.SERVICE_PID, CONFIG_PID);
         return properties;
index 74b3a089fa7aa506dc7a3bb49cce314a9f1f9a05..9eb88c4cb2b1fe088bf7ac87352ba939fb5500ca 100644 (file)
@@ -16,7 +16,9 @@ final class NetconfConfigurationHolder {
     private final InetSocketAddress sshServerAddress;
     private final String privateKeyPath;
 
-    NetconfConfigurationHolder(InetSocketAddress tcpServerAddress, InetSocketAddress sshServerAddress, String privateKeyPath){
+    NetconfConfigurationHolder(final InetSocketAddress tcpServerAddress,
+                               final InetSocketAddress sshServerAddress,
+                               final String privateKeyPath) {
         this.tcpServerAddress = tcpServerAddress;
         this.sshServerAddress = sshServerAddress;
         this.privateKeyPath = privateKeyPath;
@@ -33,5 +35,4 @@ final class NetconfConfigurationHolder {
     InetSocketAddress getTcpServerAddress() {
         return tcpServerAddress;
     }
-
 }
index 4e363b14b27200ef9a672d4b214d05175e9b0f82..72106403225d806818188ba9677ec77235794a85 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -8,76 +8,73 @@
 
 package org.opendaylight.netconf.util.osgi;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
 
-import com.google.common.base.Optional;
-import io.netty.channel.local.LocalAddress;
-import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Collection;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.cm.ManagedService;
 
 public class NetconfConfigUtilTest {
 
-    private BundleContext bundleContext;
+    @Mock
+    private ServiceReference<ManagedService> serviceRef;
 
-    @Before
-    public void setUp() throws Exception {
-        bundleContext = mock(BundleContext.class);
-    }
-
-    @Test
-    public void testNetconfConfigUtil() throws Exception {
-        assertEquals(NetconfConfigUtil.getNetconfLocalAddress(), new LocalAddress("netconf"));
-
-        doReturn("").when(bundleContext).getProperty("netconf.connectionTimeoutMillis");
-        assertEquals(NetconfConfigUtil.extractTimeoutMillis(bundleContext), NetconfConfigUtil.DEFAULT_TIMEOUT_MILLIS);
-
-        doReturn("a").when(bundleContext).getProperty("netconf.connectionTimeoutMillis");
-        assertEquals(NetconfConfigUtil.extractTimeoutMillis(bundleContext), NetconfConfigUtil.DEFAULT_TIMEOUT_MILLIS);
-    }
+    @Mock
+    private ServiceReference<ManagedService> netconfConfigurationRef;
 
-    @Test
-    public void testgetPrivateKeyKey() throws Exception {
-        assertEquals(NetconfConfigUtil.getPrivateKeyKey(), "netconf.ssh.pk.path");
-    }
-
-    @Test
-    public void testgetNetconfServerAddressKey() throws Exception {
-        NetconfConfigUtil.InfixProp prop = NetconfConfigUtil.InfixProp.tcp;
-        assertEquals(NetconfConfigUtil.getNetconfServerAddressKey(prop), "netconf.tcp.address");
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
     }
 
     @Test
-    public void testExtractNetconfServerAddress() throws Exception {
-        NetconfConfigUtil.InfixProp prop = NetconfConfigUtil.InfixProp.tcp;
-        doReturn("").when(bundleContext).getProperty(anyString());
-        assertEquals(NetconfConfigUtil.extractNetconfServerAddress(bundleContext, prop), Optional.absent());
-    }
+    public void testGetNetconfConfigurationService() throws Exception {
+        final Collection<ServiceReference<ManagedService>> services = new ArrayList<>();
+        services.add(serviceRef);
+        services.add(netconfConfigurationRef);
+        final BundleContext context = mock(BundleContext.class);
+        doReturn(services).when(context).getServiceReferences(ManagedService.class, null);
+        final ManagedService service = mock(ManagedService.class);
+        doReturn(service).when(context).getService(serviceRef);
+        doReturn(NetconfConfiguration.getInstance()).when(context).getService(netconfConfigurationRef);
+        final java.util.Optional<NetconfConfiguration> netconfConfigurationOptional =
+                NetconfConfigUtil.getNetconfConfigurationService(context);
+        Assert.assertTrue(netconfConfigurationOptional.isPresent());
+        Assert.assertEquals(NetconfConfiguration.getInstance(), netconfConfigurationOptional.get());
 
-    @Test
-    public void testExtractNetconfServerAddress2() throws Exception {
-        NetconfConfigUtil.InfixProp prop = NetconfConfigUtil.InfixProp.tcp;
-        doReturn("1.1.1.1").when(bundleContext).getProperty("netconf.tcp.address");
-        doReturn("20").when(bundleContext).getProperty("netconf.tcp.port");
-        Optional<InetSocketAddress> inetSocketAddressOptional = NetconfConfigUtil.extractNetconfServerAddress(bundleContext, prop);
-        assertTrue(inetSocketAddressOptional.isPresent());
-        assertEquals(inetSocketAddressOptional.get(), new InetSocketAddress("1.1.1.1", 20));
     }
 
     @Test
-    public void testGetPrivateKeyPath() throws Exception {
-        doReturn("path").when(bundleContext).getProperty("netconf.ssh.pk.path");
-        assertEquals(NetconfConfigUtil.getPrivateKeyPath(bundleContext).get(), "path");
+    public void testGetNetconfConfigurationServiceAbsent() throws Exception {
+        final Collection<ServiceReference<ManagedService>> services = new ArrayList<>();
+        services.add(serviceRef);
+        final BundleContext context = mock(BundleContext.class);
+        doReturn(services).when(context).getServiceReferences(ManagedService.class, null);
+        final ManagedService service = mock(ManagedService.class);
+        doReturn(service).when(context).getService(serviceRef);
+        final java.util.Optional<NetconfConfiguration> netconfConfigurationOptional =
+                NetconfConfigUtil.getNetconfConfigurationService(context);
+        Assert.assertFalse(netconfConfigurationOptional.isPresent());
     }
 
     @Test
-    public void testGetPrivateKeyPathNotPresent() throws Exception {
-        doReturn(null).when(bundleContext).getProperty("netconf.ssh.pk.path");
-        assertEquals(NetconfConfigUtil.getPrivateKeyPath(bundleContext), Optional.absent());
+    public void testGetNetconfConfigurationServiceInvalidSyntax() throws Exception {
+        final BundleContext context = mock(BundleContext.class);
+        final InvalidSyntaxException exception = new InvalidSyntaxException("Invalid syntax", "filter");
+        doThrow(exception).when(context).getServiceReferences(ManagedService.class, null);
+        final java.util.Optional<NetconfConfiguration> netconfConfigurationOptional =
+                NetconfConfigUtil.getNetconfConfigurationService(context);
+        Assert.assertFalse(netconfConfigurationOptional.isPresent());
     }
 }
diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationActivatorTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationActivatorTest.java
new file mode 100644 (file)
index 0000000..7ace84b
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.util.osgi;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.cm.ManagedService;
+
+public class NetconfConfigurationActivatorTest {
+
+    @Mock
+    private BundleContext context;
+    @Mock
+    private ServiceRegistration registration;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        doReturn(registration).when(context)
+                .registerService(eq(ManagedService.class), any(NetconfConfiguration.class), any());
+        doNothing().when(registration).unregister();
+    }
+
+    @Test
+    public void testStartStop() throws Exception {
+        final NetconfConfigurationActivator activator = new NetconfConfigurationActivator();
+        activator.start(context);
+        final Dictionary<String, String> props = new Hashtable<>();
+        props.put(Constants.SERVICE_PID, "netconf");
+        verify(context).registerService(eq(ManagedService.class), eq(NetconfConfiguration.getInstance()), eq(props));
+        activator.stop(context);
+        verify(registration).unregister();
+    }
+
+}
\ No newline at end of file
diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigurationTest.java
new file mode 100644 (file)
index 0000000..c80f388
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.util.osgi;
+
+import io.netty.channel.local.LocalAddress;
+import java.net.InetSocketAddress;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class NetconfConfigurationTest {
+
+    @Test
+    public void testUpdated() throws Exception {
+        final NetconfConfiguration config = NetconfConfiguration.getInstance();
+        Assert.assertEquals(new InetSocketAddress("0.0.0.0", 1830), config.getSshServerAddress());
+        Assert.assertEquals(new InetSocketAddress("127.0.0.1", 8383), config.getTcpServerAddress());
+        Assert.assertEquals("./configuration/RSA.pk", config.getPrivateKeyPath());
+        final Dictionary<String, String> newValues = new Hashtable<>();
+        final String newSshIp = "192.168.1.1";
+        final String newTcpIp = "192.168.1.2";
+        final int newSshPort = 1234;
+        final int newTcpPort = 4567;
+        final String newSshKeyPath = "./new_folder/configuration/RSA.pk";
+        newValues.put("ssh-address", newSshIp);
+        newValues.put("ssh-port", Integer.toString(newSshPort));
+        newValues.put("tcp-address", newTcpIp);
+        newValues.put("tcp-port", Integer.toString(newTcpPort));
+        newValues.put("ssh-pk-path", newSshKeyPath);
+        config.updated(newValues);
+        Assert.assertEquals(new InetSocketAddress(newSshIp, newSshPort), config.getSshServerAddress());
+        Assert.assertEquals(new InetSocketAddress(newTcpIp, newTcpPort), config.getTcpServerAddress());
+        Assert.assertEquals(newSshKeyPath, config.getPrivateKeyPath());
+    }
+
+    @Test
+    public void testUpdatedNull() throws Exception {
+        final NetconfConfiguration config = NetconfConfiguration.getInstance();
+        Assert.assertEquals(new InetSocketAddress("0.0.0.0", 1830), config.getSshServerAddress());
+        Assert.assertEquals(new InetSocketAddress("127.0.0.1", 8383), config.getTcpServerAddress());
+        Assert.assertEquals("./configuration/RSA.pk", config.getPrivateKeyPath());
+        final Dictionary<String, String> nullDictionary = null;
+        config.updated(nullDictionary);
+        Assert.assertEquals(new InetSocketAddress("0.0.0.0", 1830), config.getSshServerAddress());
+        Assert.assertEquals(new InetSocketAddress("127.0.0.1", 8383), config.getTcpServerAddress());
+        Assert.assertEquals("./configuration/RSA.pk", config.getPrivateKeyPath());
+    }
+}
\ No newline at end of file