cleaning up more cord apps

Change-Id: Ie48245b61926232ca9b2fa583492cb6e88f10990
diff --git a/apps/cordmcast/features.xml b/apps/cordmcast/features.xml
new file mode 100644
index 0000000..59c92c5
--- /dev/null
+++ b/apps/cordmcast/features.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+  ~ Copyright 2016 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.
+  -->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
+    <feature name="${project.artifactId}" version="${project.version}"
+             description="${project.description}">
+        <feature>onos-api</feature>
+        <bundle>mvn:${project.groupId}/onos-app-olt-api/${project.version}</bundle>
+        <bundle>mvn:${project.groupId}/onos-app-cord-mcast/${project.version}</bundle>
+    </feature>
+</features>
diff --git a/apps/cordmcast/pom.xml b/apps/cordmcast/pom.xml
index b977c51..32a5c72 100644
--- a/apps/cordmcast/pom.xml
+++ b/apps/cordmcast/pom.xml
@@ -68,5 +68,10 @@
             <artifactId>jersey-client</artifactId>
             <version>1.19</version>
         </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-app-olt-api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
     </dependencies>
 </project>
diff --git a/apps/cordmcast/src/main/java/org/onosproject/cordmcast/CordMcast.java b/apps/cordmcast/src/main/java/org/onosproject/cordmcast/CordMcast.java
index 76c6fd2..0981879 100644
--- a/apps/cordmcast/src/main/java/org/onosproject/cordmcast/CordMcast.java
+++ b/apps/cordmcast/src/main/java/org/onosproject/cordmcast/CordMcast.java
@@ -24,6 +24,7 @@
 import com.sun.jersey.api.client.ClientHandlerException;
 import com.sun.jersey.api.client.WebResource;
 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
+import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
@@ -40,6 +41,12 @@
 import org.onosproject.core.ApplicationId;
 import org.onosproject.core.CoreService;
 import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.config.basics.SubjectFactories;
 import org.onosproject.net.flow.DefaultTrafficSelector;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
 import org.onosproject.net.flow.TrafficSelector;
@@ -56,6 +63,8 @@
 import org.onosproject.net.mcast.McastRoute;
 import org.onosproject.net.mcast.McastRouteInfo;
 import org.onosproject.net.mcast.MulticastRouteService;
+import org.onosproject.olt.AccessDeviceConfig;
+import org.onosproject.olt.AccessDeviceData;
 import org.onosproject.rest.AbstractWebResource;
 import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
@@ -66,7 +75,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
-import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -84,12 +93,14 @@
 @Component(immediate = true)
 public class CordMcast {
 
+
     private static final int DEFAULT_REST_TIMEOUT_MS = 2000;
-    private static final int DEFAULT_PRIORITY = 1000;
+    private static final int DEFAULT_PRIORITY = 500;
     private static final short DEFAULT_MCAST_VLAN = 4000;
     private static final String DEFAULT_SYNC_HOST = "10.90.0.8:8181";
     private static final String DEFAULT_USER = "karaf";
     private static final String DEFAULT_PASSWORD = "karaf";
+    private static final boolean DEFAULT_VLAN_ENABLED = true;
 
     private final Logger log = getLogger(getClass());
 
@@ -108,7 +119,12 @@
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected ComponentConfigService componentConfigService;
 
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected NetworkConfigRegistry networkConfig;
+
     protected McastListener listener = new InternalMulticastListener();
+    private InternalNetworkConfigListener configListener =
+            new InternalNetworkConfigListener();
 
     //TODO: move this to a ec map
     private Map<IpAddress, Integer> groups = Maps.newConcurrentMap();
@@ -122,9 +138,9 @@
             label = "VLAN for multicast traffic")
     private int mcastVlan = DEFAULT_MCAST_VLAN;
 
-    @Property(name = "vlanEnabled", boolValue = false,
-            label = "Use vlan for multicast traffic")
-    private boolean vlanEnabled = false;
+    @Property(name = "vlanEnabled", boolValue = DEFAULT_VLAN_ENABLED,
+            label = "Use vlan for multicast traffic?")
+    private boolean vlanEnabled = DEFAULT_VLAN_ENABLED;
 
     @Property(name = "priority", intValue = DEFAULT_PRIORITY,
             label = "Priority for multicast rules")
@@ -144,6 +160,20 @@
 
     private String fabricOnosUrl;
 
+    private Map<DeviceId, AccessDeviceData> oltData = new ConcurrentHashMap<>();
+
+    private static final Class<AccessDeviceConfig> CONFIG_CLASS =
+            AccessDeviceConfig.class;
+
+    private ConfigFactory<DeviceId, AccessDeviceConfig> configFactory =
+            new ConfigFactory<DeviceId, AccessDeviceConfig>(
+                    SubjectFactories.DEVICE_SUBJECT_FACTORY, CONFIG_CLASS, "accessDevice") {
+                @Override
+                public AccessDeviceConfig createConfig() {
+                    return new AccessDeviceConfig();
+                }
+            };
+
     @Activate
     public void activate(ComponentContext context) {
         componentConfigService.registerProperties(getClass());
@@ -151,16 +181,30 @@
 
         appId = coreService.registerApplication("org.onosproject.cordmcast");
 
+
         clearRemoteRoutes();
 
+        networkConfig.registerConfigFactory(configFactory);
+        networkConfig.addListener(configListener);
+
+        networkConfig.getSubjects(DeviceId.class, AccessDeviceConfig.class).forEach(
+                subject -> {
+                    AccessDeviceConfig config = networkConfig.getConfig(subject, AccessDeviceConfig.class);
+                    if (config != null) {
+                        AccessDeviceData data = config.getOlt();
+                        oltData.put(data.deviceId(), data);
+                    }
+                }
+        );
+
+
         mcastService.addListener(listener);
 
-        for (McastRoute route : mcastService.getRoutes()) {
-            Set<ConnectPoint> sinks = mcastService.fetchSinks(route);
-            if (!sinks.isEmpty()) {
-                sinks.forEach(s -> provisionGroup(route, s));
-            }
-        }
+        mcastService.getRoutes().stream()
+                .map(r -> new ImmutablePair<>(r, mcastService.fetchSinks(r)))
+                .filter(pair -> pair.getRight() != null && !pair.getRight().isEmpty())
+                .forEach(pair -> pair.getRight().forEach(sink -> provisionGroup(pair.getLeft(),
+                                                                                sink)));
 
         log.info("Started");
     }
@@ -169,6 +213,8 @@
     public void deactivate() {
         componentConfigService.unregisterProperties(getClass(), false);
         mcastService.removeListener(listener);
+        networkConfig.unregisterConfigFactory(configFactory);
+        networkConfig.removeListener(configListener);
         log.info("Stopped");
     }
 
@@ -187,7 +233,7 @@
             mcastVlan = isNullOrEmpty(s) ? DEFAULT_MCAST_VLAN : Short.parseShort(s.trim());
 
             s = get(properties, "vlanEnabled");
-            vlanEnabled = isNullOrEmpty(s) || Boolean.parseBoolean(s.trim());
+            vlanEnabled = isNullOrEmpty(s) ? DEFAULT_VLAN_ENABLED : Boolean.parseBoolean(s.trim());
 
             s = get(properties, "priority");
             priority = isNullOrEmpty(s) ? DEFAULT_PRIORITY : Integer.parseInt(s.trim());
@@ -275,6 +321,13 @@
         checkNotNull(route, "Route cannot be null");
         checkNotNull(sink, "Sink cannot be null");
 
+        AccessDeviceData oltInfo = oltData.get(sink.deviceId());
+
+        if (oltInfo == null) {
+            log.warn("Unknown OLT device : {}", sink.deviceId());
+            return;
+        }
+
         final AtomicBoolean sync = new AtomicBoolean(false);
 
         Integer nextId = groups.computeIfAbsent(route.group(), (g) -> {
@@ -304,6 +357,7 @@
             flowObjectiveService.next(sink.deviceId(), next);
 
             TrafficSelector.Builder mcast = DefaultTrafficSelector.builder()
+                    .matchInPort(oltInfo.uplink())
                     .matchEthType(Ethernet.TYPE_IPV4)
                     .matchIPDst(g.toIpPrefix());
 
@@ -336,7 +390,7 @@
 
             sync.set(true);
 
-           return id;
+            return id;
         });
 
         if (!sync.get()) {
@@ -364,6 +418,7 @@
             flowObjectiveService.next(sink.deviceId(), next);
         }
 
+
         addRemoteRoute(route);
     }
 
@@ -456,4 +511,37 @@
                 .type(JSON_UTF_8.toString());
     }
 
+    private class InternalNetworkConfigListener implements NetworkConfigListener {
+        @Override
+        public void event(NetworkConfigEvent event) {
+            switch (event.type()) {
+
+                case CONFIG_ADDED:
+                case CONFIG_UPDATED:
+                    AccessDeviceConfig config =
+                            networkConfig.getConfig((DeviceId) event.subject(), CONFIG_CLASS);
+                    if (config != null) {
+                        oltData.put(config.getOlt().deviceId(), config.getOlt());
+                    }
+
+                    break;
+                case CONFIG_REGISTERED:
+                case CONFIG_UNREGISTERED:
+                    break;
+                case CONFIG_REMOVED:
+                    oltData.remove(event.subject());
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        @Override
+        public boolean isRelevant(NetworkConfigEvent event) {
+            return event.configClass().equals(CONFIG_CLASS);
+        }
+
+
+    }
+
 }
diff --git a/apps/igmp/src/main/java/org/onosproject/igmp/IgmpSnoop.java b/apps/igmp/src/main/java/org/onosproject/igmp/IgmpSnoop.java
index f0e11cc..58e5826 100644
--- a/apps/igmp/src/main/java/org/onosproject/igmp/IgmpSnoop.java
+++ b/apps/igmp/src/main/java/org/onosproject/igmp/IgmpSnoop.java
@@ -528,7 +528,10 @@
                 case CONFIG_REMOVED:
                     if (event.configClass().equals(SSM_TRANSLATE_CONFIG_CLASS)) {
                         ssmTranslateTable.clear();
+                    } else if (event.configClass().equals(CONFIG_CLASS)) {
+                        oltData.remove(event.subject());
                     }
+
                 default:
                     break;
             }
diff --git a/apps/olt/api/src/main/java/org/onosproject/olt/AccessDeviceService.java b/apps/olt/api/src/main/java/org/onosproject/olt/AccessDeviceService.java
index 831784c..74d8a28 100644
--- a/apps/olt/api/src/main/java/org/onosproject/olt/AccessDeviceService.java
+++ b/apps/olt/api/src/main/java/org/onosproject/olt/AccessDeviceService.java
@@ -19,6 +19,9 @@
 import org.onlab.packet.VlanId;
 import org.onosproject.event.ListenerService;
 import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+
+import java.util.Map;
 
 /**
  * Service for interacting with an access device (OLT).
@@ -41,4 +44,11 @@
      */
     void removeSubscriber(ConnectPoint port);
 
+    /**
+     * Returns the map of configured OLTs.
+     *
+     * @return a map
+     */
+    Map<DeviceId, AccessDeviceData> fetchOlts();
+
 }
diff --git a/apps/olt/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java b/apps/olt/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java
new file mode 100644
index 0000000..63b3af1
--- /dev/null
+++ b/apps/olt/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2015 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.
+ */
+
+package org.onosproject.olt.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.net.DeviceId;
+import org.onosproject.olt.AccessDeviceData;
+import org.onosproject.olt.AccessDeviceService;
+
+import java.util.Map;
+
+/**
+ * Adds a subscriber to an access device.
+ */
+@Command(scope = "onos", name = "show-olts",
+        description = "Shows configured OLTs")
+public class ShowOltCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "deviceId", description = "Access device ID",
+            required = false, multiValued = false)
+    private String strDeviceId = null;
+
+    @Override
+    protected void execute() {
+        AccessDeviceService service = AbstractShellCommand.get(AccessDeviceService.class);
+        Map<DeviceId, AccessDeviceData> data = service.fetchOlts();
+        if (strDeviceId != null) {
+            DeviceId deviceId = DeviceId.deviceId(strDeviceId);
+            print("OLT %s:", deviceId);
+            display(data.get(deviceId));
+        } else {
+            data.keySet().forEach(did -> {
+                print("OLT %s:", did);
+                display(data.get(did));
+            });
+        }
+    }
+
+    private void display(AccessDeviceData accessDeviceData) {
+        print("\tvlan : %s", accessDeviceData.vlan());
+        print("\tuplink : %s", accessDeviceData.uplink());
+    }
+}
diff --git a/apps/olt/app/src/main/java/org/onosproject/olt/impl/Olt.java b/apps/olt/app/src/main/java/org/onosproject/olt/impl/Olt.java
index fa9c2a4..ab03c0b 100644
--- a/apps/olt/app/src/main/java/org/onosproject/olt/impl/Olt.java
+++ b/apps/olt/app/src/main/java/org/onosproject/olt/impl/Olt.java
@@ -20,11 +20,14 @@
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Modified;
+import org.apache.felix.scr.annotations.Property;
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.Service;
 import org.onlab.packet.EthType;
 import org.onlab.packet.VlanId;
+import org.onosproject.cfg.ComponentConfigService;
 import org.onosproject.core.ApplicationId;
 import org.onosproject.core.CoreService;
 import org.onosproject.event.AbstractListenerManager;
@@ -58,17 +61,22 @@
 import org.onosproject.olt.AccessDeviceEvent;
 import org.onosproject.olt.AccessDeviceListener;
 import org.onosproject.olt.AccessDeviceService;
+import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
 
+import java.util.Dictionary;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.Properties;
 import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
+import static com.google.common.base.Strings.isNullOrEmpty;
+import static org.onlab.util.Tools.get;
 import static org.onlab.util.Tools.groupedThreads;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -80,6 +88,9 @@
 public class Olt
         extends AbstractListenerManager<AccessDeviceEvent, AccessDeviceListener>
         implements AccessDeviceService {
+
+    private static final short DEFAULT_VLAN = 0;
+
     private final Logger log = getLogger(getClass());
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
@@ -94,12 +105,18 @@
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected NetworkConfigRegistry networkConfig;
 
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ComponentConfigService componentConfigService;
+
+
+    @Property(name = "defaultVlan", intValue = DEFAULT_VLAN,
+            label = "Default VLAN RG<->ONU traffic")
+    private int defaultVlan = DEFAULT_VLAN;
+
     private final DeviceListener deviceListener = new InternalDeviceListener();
 
     private ApplicationId appId;
 
-    private static final VlanId DEFAULT_VLAN = VlanId.vlanId((short) 0);
-
     private ExecutorService oltInstallers = Executors.newFixedThreadPool(4,
                                                                          groupedThreads("onos/olt-service",
                                                                                         "olt-installer-%d"));
@@ -127,8 +144,10 @@
 
 
     @Activate
-    public void activate() {
+    public void activate(ComponentContext context) {
+        modified(context);
         appId = coreService.registerApplication("org.onosproject.olt");
+        componentConfigService.registerProperties(getClass());
 
         eventDispatcher.addSink(AccessDeviceEvent.class, listenerRegistry);
 
@@ -160,13 +179,26 @@
 
     @Deactivate
     public void deactivate() {
+        componentConfigService.unregisterProperties(getClass(), false);
         deviceService.removeListener(deviceListener);
         networkConfig.removeListener(configListener);
         networkConfig.unregisterConfigFactory(configFactory);
         log.info("Stopped");
     }
 
-    @Override
+    @Modified
+    public void modified(ComponentContext context) {
+        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
+
+        try {
+            String s = get(properties, "defaultVlan");
+            defaultVlan = isNullOrEmpty(s) ? DEFAULT_VLAN : Integer.parseInt(s.trim());
+        } catch (Exception e) {
+            defaultVlan = DEFAULT_VLAN;
+        }
+    }
+
+        @Override
     public void provisionSubscriber(ConnectPoint port, VlanId vlan) {
         AccessDeviceData olt = oltData.get(port.deviceId());
 
@@ -192,6 +224,11 @@
 
     }
 
+    @Override
+    public Map<DeviceId, AccessDeviceData> fetchOlts() {
+        return Maps.newHashMap(oltData);
+    }
+
     private void unprovisionSubscriber(DeviceId deviceId, PortNumber uplink,
                                        PortNumber subscriberPort, VlanId deviceVlan) {
 
@@ -255,7 +292,7 @@
         CompletableFuture<ObjectiveError> upFuture = new CompletableFuture();
 
         TrafficSelector upstream = DefaultTrafficSelector.builder()
-                .matchVlanId(defaultVlan.orElse(DEFAULT_VLAN))
+                .matchVlanId(defaultVlan.orElse(VlanId.vlanId((short) this.defaultVlan)))
                 .matchInPort(subscriberPort)
                 .build();
 
@@ -275,7 +312,7 @@
 
         TrafficTreatment downstreamTreatment = DefaultTrafficTreatment.builder()
                 .popVlan()
-                .setVlanId(defaultVlan.orElse(DEFAULT_VLAN))
+                .setVlanId(defaultVlan.orElse(VlanId.vlanId((short) this.defaultVlan)))
                 .setOutput(subscriberPort)
                 .build();
 
@@ -417,6 +454,7 @@
                     post(new AccessDeviceEvent(
                             AccessDeviceEvent.Type.DEVICE_CONNECTED, devId,
                             null, null));
+                    provisionDefaultFlows(devId);
                     break;
                 case DEVICE_REMOVED:
                     post(new AccessDeviceEvent(
@@ -450,21 +488,29 @@
 
                 case CONFIG_ADDED:
                 case CONFIG_UPDATED:
-                    if (event.configClass().equals(CONFIG_CLASS)) {
-                        AccessDeviceConfig config =
-                                networkConfig.getConfig((DeviceId) event.subject(), CONFIG_CLASS);
-                        if (config != null) {
-                            oltData.put(config.getOlt().deviceId(), config.getOlt());
-                            provisionDefaultFlows((DeviceId) event.subject());
-                        }
+
+                    AccessDeviceConfig config =
+                            networkConfig.getConfig((DeviceId) event.subject(), CONFIG_CLASS);
+                    if (config != null) {
+                        oltData.put(config.getOlt().deviceId(), config.getOlt());
+                        provisionDefaultFlows((DeviceId) event.subject());
                     }
+
                     break;
+                case CONFIG_REGISTERED:
                 case CONFIG_UNREGISTERED:
+                    break;
                 case CONFIG_REMOVED:
+                    oltData.remove(event.subject());
                 default:
                     break;
             }
         }
+
+        @Override
+        public boolean isRelevant(NetworkConfigEvent event) {
+            return event.configClass().equals(CONFIG_CLASS);
+        }
     }
 
     private void provisionDefaultFlows(DeviceId deviceId) {
diff --git a/apps/olt/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml b/apps/olt/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml
index 1818c02..5d114f9 100644
--- a/apps/olt/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml
+++ b/apps/olt/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml
@@ -30,6 +30,13 @@
                 <null/>
             </completers>
         </command>
+        <command>
+            <action class="org.onosproject.olt.cli.ShowOltCommand"/>
+            <completers>
+                <ref component-id="deviceIdCompleter"/>
+                <null/>
+            </completers>
+        </command>
     </command-bundle>
 
     <bean id="deviceIdCompleter" class="org.onosproject.cli.net.DeviceIdCompleter"/>