Moving NetconfDeviceConfig to API bundle

- Move the class to API bundle to allow config manipulation via API
- Avoid sweeping whole device tree on every Device event.
- code clean up

Change-Id: I58ebdc89688c6c9250bb546585c227d486b30df2
diff --git a/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java b/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java
index 933899f..c756013 100644
--- a/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java
+++ b/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java
@@ -16,8 +16,11 @@
 package org.onosproject.net;
 
 import com.google.common.testing.EqualsTester;
+
+import org.junit.Assert;
 import org.junit.Test;
 
+import static org.junit.Assert.assertEquals;
 import static org.onosproject.net.DeviceId.deviceId;
 
 /**
@@ -34,4 +37,14 @@
                 .testEquals();
     }
 
+
+    @Test
+    public void ipAndPort() {
+        DeviceId ipp = deviceId("netconf:127.0.0.1:830");
+        assertEquals("127.0.0.1:830", ipp.uri().getSchemeSpecificPart());
+
+        DeviceId ipp6 = deviceId("netconf:[2001:db8:85a3:8d3:1319:8a2e:370:7348]:830");
+        Assert.assertEquals("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:830", ipp6.uri().getSchemeSpecificPart());
+    }
+
 }
diff --git a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceConfig.java b/protocols/netconf/api/src/main/java/org/onosproject/netconf/config/NetconfDeviceConfig.java
similarity index 84%
rename from providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceConfig.java
rename to protocols/netconf/api/src/main/java/org/onosproject/netconf/config/NetconfDeviceConfig.java
index ea17015..0af9885 100644
--- a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceConfig.java
+++ b/protocols/netconf/api/src/main/java/org/onosproject/netconf/config/NetconfDeviceConfig.java
@@ -14,14 +14,13 @@
  * limitations under the License.
  */
 
-package org.onosproject.provider.netconf.device.impl;
+package org.onosproject.netconf.config;
 
 import com.google.common.annotations.Beta;
 import org.apache.commons.lang3.tuple.Pair;
 import org.onlab.packet.IpAddress;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.config.Config;
-
 import static com.google.common.base.Preconditions.checkNotNull;
 
 /**
@@ -30,6 +29,11 @@
 @Beta
 public class NetconfDeviceConfig extends Config<DeviceId> {
 
+    /**
+     * netcfg ConfigKey.
+     */
+    public static final String CONFIG_KEY = "netconf";
+
     private static final String IP = "ip";
     private static final String PORT = "port";
     private static final String USERNAME = "username";
@@ -138,13 +142,19 @@
     }
 
     private Pair<String, Integer> extractIpPort() {
-        String info = subject.toString();
-        if (info.startsWith(NetconfDeviceProvider.SCHEME_NAME)) {
-            //+1 is due to length of colon separator
-            String ip = info.substring(info.indexOf(":") + 1, info.lastIndexOf(":"));
-            int port = Integer.parseInt(info.substring(info.lastIndexOf(":") + 1));
-            return Pair.of(ip, port);
+        // Assuming one of
+        //  - netconf:ip:port
+        //  - netconf:ip
+
+        // foo:schemespecifcpart
+        String info = subject.uri().getSchemeSpecificPart();
+        int portSeparator = info.lastIndexOf(':');
+        if (portSeparator == -1) {
+            // assume default port
+            return Pair.of(info, 830);
         }
-        return null;
+        String ip = info.substring(0, portSeparator);
+        int port = Integer.parseInt(info.substring(portSeparator + 1));
+        return Pair.of(ip, port);
     }
 }
diff --git a/protocols/netconf/api/src/main/java/org/onosproject/netconf/config/package-info.java b/protocols/netconf/api/src/main/java/org/onosproject/netconf/config/package-info.java
new file mode 100644
index 0000000..43b0832
--- /dev/null
+++ b/protocols/netconf/api/src/main/java/org/onosproject/netconf/config/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2017-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Netconf configuration package.
+ */
+package org.onosproject.netconf.config;
diff --git a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java b/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
index 41a6ed1..b30c6a0 100644
--- a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
+++ b/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
@@ -67,6 +67,7 @@
 import org.onosproject.netconf.NetconfController;
 import org.onosproject.netconf.NetconfDeviceListener;
 import org.onosproject.netconf.NetconfException;
+import org.onosproject.netconf.config.NetconfDeviceConfig;
 import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
 
@@ -154,9 +155,10 @@
     protected ScheduledFuture<?> scheduledTask;
 
     protected final List<ConfigFactory> factories = ImmutableList.of(
+            // TODO consider moving Config registration to NETCONF ctl bundle
             new ConfigFactory<DeviceId, NetconfDeviceConfig>(
                     SubjectFactories.DEVICE_SUBJECT_FACTORY,
-                    NetconfDeviceConfig.class, SCHEME_NAME) {
+                    NetconfDeviceConfig.class, NetconfDeviceConfig.CONFIG_KEY) {
                 @Override
                 public NetconfDeviceConfig createConfig() {
                     return new NetconfDeviceConfig();
@@ -351,23 +353,35 @@
         Set<DeviceId> deviceSubjects =
                 cfgService.getSubjects(DeviceId.class, NetconfDeviceConfig.class);
         deviceSubjects.forEach(deviceId -> {
-            NetconfDeviceConfig config =
-                    cfgService.getConfig(deviceId, NetconfDeviceConfig.class);
-            DeviceDescription deviceDescription = createDeviceRepresentation(deviceId, config);
-            log.debug("Connecting NETCONF device {}, on {}:{} with username {}",
-                      deviceId, config.ip(), config.port(), config.username());
-            storeDeviceKey(config.sshKey(), config.username(), config.password(), deviceId);
-            if (deviceService.getDevice(deviceId) == null) {
-                providerService.deviceConnected(deviceId, deviceDescription);
-            }
-            try {
-                checkAndUpdateDevice(deviceId, deviceDescription);
-            } catch (Exception e) {
-                log.error("Unhandled exception checking {}", deviceId, e);
-            }
+            connectDevice(cfgService.getConfig(deviceId, NetconfDeviceConfig.class));
         });
     }
 
+
+    private void connectDevice(NetconfDeviceConfig config) {
+        if (config == null) {
+            return;
+        }
+        DeviceId deviceId = config.subject();
+        if (!deviceId.uri().getScheme().equals(SCHEME_NAME)) {
+            // not under my scheme, skipping
+            log.trace("{} not my scheme, skipping", deviceId);
+            return;
+        }
+        DeviceDescription deviceDescription = createDeviceRepresentation(deviceId, config);
+        log.debug("Connecting NETCONF device {}, on {}:{} with username {}",
+                  deviceId, config.ip(), config.port(), config.username());
+        storeDeviceKey(config.sshKey(), config.username(), config.password(), deviceId);
+        if (deviceService.getDevice(deviceId) == null) {
+            providerService.deviceConnected(deviceId, deviceDescription);
+        }
+        try {
+            checkAndUpdateDevice(deviceId, deviceDescription);
+        } catch (Exception e) {
+            log.error("Unhandled exception checking {}", deviceId, e);
+        }
+    }
+
     private void checkAndUpdateDevice(DeviceId deviceId, DeviceDescription deviceDescription) {
         Device device = deviceService.getDevice(deviceId);
         if (device == null) {
@@ -580,7 +594,7 @@
         @Override
         public void event(NetworkConfigEvent event) {
             if (event.configClass().equals(NetconfDeviceConfig.class)) {
-                executor.execute(NetconfDeviceProvider.this::connectDevices);
+                executor.execute(() -> connectDevice((NetconfDeviceConfig) event.config().get()));
             } else {
                 log.warn("Injecting device via this Json is deprecated, " +
                                  "please put configuration under devices/ as shown in the wiki");
diff --git a/providers/netconf/device/src/test/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProviderTest.java b/providers/netconf/device/src/test/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProviderTest.java
index f2f4007..d146e0f 100644
--- a/providers/netconf/device/src/test/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProviderTest.java
+++ b/providers/netconf/device/src/test/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProviderTest.java
@@ -70,6 +70,7 @@
 import org.onosproject.net.provider.ProviderId;
 import org.onosproject.netconf.NetconfController;
 import org.onosproject.netconf.NetconfDeviceListener;
+import org.onosproject.netconf.config.NetconfDeviceConfig;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -106,13 +107,16 @@
     private final DeviceStore deviceStore = new MockDeviceStore();
 
     //Class for testing
-    private final NetworkConfigEvent deviceAddedEvent =
-            new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED,
-                                   DeviceId.deviceId(NETCONF_DEVICE_ID_STRING), NetconfDeviceConfig.class);
     private final NetconfDeviceConfig netconfDeviceConfig = new NetconfDeviceConfig();
     private final NetconfDeviceConfig netconfDeviceConfigSshKey = new NetconfDeviceConfig();
     private final NetconfDeviceConfig netconfDeviceConfigEmptyIpv4 = new NetconfDeviceConfig();
     private final NetconfDeviceConfig netconfDeviceConfigEmptyIpv6 = new NetconfDeviceConfig();
+    private final NetworkConfigEvent deviceAddedEvent =
+            new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED,
+                                   DeviceId.deviceId(NETCONF_DEVICE_ID_STRING),
+                                   netconfDeviceConfig, null,
+                                   NetconfDeviceConfig.class);
+
     private final NetworkConfigEvent deviceAddedEventOld =
             new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED,
                                    null, NetconfProviderConfig.class);
@@ -436,7 +440,7 @@
 
         @Override
         public <S, C extends Config<S>> Set<S> getSubjects(Class<S> subjectClass, Class<C> configClass) {
-            Set<S> subjects = new HashSet<S>();
+            Set<S> subjects = new HashSet<>();
             if (available) {
                 if (cfg != null) {
                     subjects.add((S) DeviceId.deviceId(NETCONF_DEVICE_ID_STRING_OLD));