ONOS-3931: move DeviceKey manager and store implementations from incubator to core

Change-Id: I2c26d7a4106be5b8f631b010cc7a167de957c9d2
diff --git a/core/store/dist/src/main/java/org/onosproject/store/key/impl/DistributedDeviceKeyStore.java b/core/store/dist/src/main/java/org/onosproject/store/key/impl/DistributedDeviceKeyStore.java
new file mode 100644
index 0000000..003d919
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onosproject/store/key/impl/DistributedDeviceKeyStore.java
@@ -0,0 +1,146 @@
+/*
+ * 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.
+ */
+
+package org.onosproject.store.key.impl;
+
+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.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.Service;
+import org.onosproject.net.key.DeviceKey;
+import org.onosproject.net.key.DeviceKeyEvent;
+import org.onosproject.net.key.DeviceKeyId;
+import org.onosproject.net.key.DeviceKeyStore;
+import org.onosproject.net.key.DeviceKeyStoreDelegate;
+import org.onosproject.store.AbstractStore;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.slf4j.Logger;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * A distributed device key store implementation, device keys are stored consistently
+ * across the cluster.
+ */
+@Component(immediate = true)
+@Service
+public class DistributedDeviceKeyStore
+        extends AbstractStore<DeviceKeyEvent, DeviceKeyStoreDelegate>
+        implements DeviceKeyStore {
+
+    private final Logger log = getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected StorageService storageService;
+
+    private ConsistentMap<DeviceKeyId, DeviceKey> deviceKeys;
+    private Map<DeviceKeyId, DeviceKey> deviceKeysMap;
+
+    private final MapEventListener<DeviceKeyId, DeviceKey> listener = new InternalMapListener();
+
+    /**
+     * Activate the distributed device key store.
+     */
+    @Activate
+    public void activate() {
+        deviceKeys = storageService.<DeviceKeyId, DeviceKey>consistentMapBuilder()
+                .withSerializer(Serializer.using(Arrays.asList(KryoNamespaces.API),
+                                DeviceKey.class,
+                                DeviceKeyId.class,
+                                DeviceKey.Type.class))
+                .withName("onos-device-keys")
+                .withRelaxedReadConsistency()
+                .build();
+        deviceKeys.addListener(listener);
+        deviceKeysMap = deviceKeys.asJavaMap();
+
+        log.info("Started");
+    }
+
+    /**
+     * Deactivate the distributed device key store.
+     */
+    @Deactivate
+    public void deactivate() {
+        deviceKeys.removeListener(listener);
+        log.info("Stopped");
+    }
+
+    @Override
+    public void createOrUpdateDeviceKey(DeviceKey deviceKey) {
+
+        // Add the device key to the store, if the device key already exists
+        // then it will be replaced with the new one.
+        deviceKeys.put(deviceKey.deviceKeyId(), deviceKey);
+    }
+
+    @Override
+    public void deleteDeviceKey(DeviceKeyId deviceKeyId) {
+        // Remove the device key from the store if the device key identifier exists.
+        deviceKeys.remove(deviceKeyId);
+    }
+
+    @Override
+    public Collection<DeviceKey> getDeviceKeys() {
+        return deviceKeysMap.values();
+    }
+
+    @Override
+    public DeviceKey getDeviceKey(DeviceKeyId deviceKeyId) {
+        return deviceKeysMap.get(deviceKeyId);
+    }
+
+    /**
+     * Listener class to map listener events to the device key events.
+     */
+    private class InternalMapListener implements MapEventListener<DeviceKeyId, DeviceKey> {
+        @Override
+        public void event(MapEvent<DeviceKeyId, DeviceKey> event) {
+            DeviceKey deviceKey = null;
+
+            DeviceKeyEvent.Type type = null;
+            switch (event.type()) {
+                case INSERT:
+                    type = DeviceKeyEvent.Type.DEVICE_KEY_ADDED;
+                    deviceKey = checkNotNull(event.newValue().value());
+                    break;
+                case UPDATE:
+                    type = DeviceKeyEvent.Type.DEVICE_KEY_UPDATED;
+                    deviceKey = checkNotNull(event.newValue().value());
+                    break;
+                case REMOVE:
+                    type = DeviceKeyEvent.Type.DEVICE_KEY_REMOVED;
+                    deviceKey = checkNotNull(event.oldValue().value());
+                    break;
+                default:
+                    log.error("Unsupported event type: " + event.type());
+            }
+            notifyDelegate(new DeviceKeyEvent(type, deviceKey));
+        }
+    }
+}
diff --git a/core/store/dist/src/main/java/org/onosproject/store/key/impl/package-info.java b/core/store/dist/src/main/java/org/onosproject/store/key/impl/package-info.java
new file mode 100644
index 0000000..550e8ce
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onosproject/store/key/impl/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+/**
+ * A distributed device key store implementation that stores device key
+ * data consistently across the cluster.
+ */
+package org.onosproject.store.key.impl;
\ No newline at end of file
diff --git a/core/store/dist/src/test/java/org/onosproject/store/key/impl/DistributedDeviceKeyStoreTest.java b/core/store/dist/src/test/java/org/onosproject/store/key/impl/DistributedDeviceKeyStoreTest.java
new file mode 100644
index 0000000..077228a
--- /dev/null
+++ b/core/store/dist/src/test/java/org/onosproject/store/key/impl/DistributedDeviceKeyStoreTest.java
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+package org.onosproject.store.key.impl;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onosproject.net.key.DeviceKey;
+import org.onosproject.net.key.DeviceKeyId;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.Collection;
+
+import static org.junit.Assert.*;
+
+/**
+ * Test class for DistributedDeviceKeyStore.
+ */
+public class DistributedDeviceKeyStoreTest {
+    private DistributedDeviceKeyStore deviceKeyStore;
+
+    final String deviceKeyIdValue = "DeviceKeyId";
+    final String deviceKeyLabel = "DeviceKeyLabel";
+    final String deviceKeyLabel2 = "DeviceKeyLabel2";
+    final String deviceKeySnmpName = "DeviceKeySnmpName";
+
+    /**
+     * Sets up the device key store and the storage service test harness.
+     */
+    @Before
+    public void setUp() {
+        deviceKeyStore = new DistributedDeviceKeyStore();
+        deviceKeyStore.storageService = new TestStorageService();
+        deviceKeyStore.setDelegate(event -> {
+        });
+        deviceKeyStore.activate();
+    }
+
+    /**
+     * Tears down the device key store.
+     */
+    @After
+    public void tearDown() {
+        deviceKeyStore.deactivate();
+    }
+
+    /**
+     * Tests adding, query and removal of a device key.
+     */
+    @Test(expected = NullPointerException.class)
+    public void testAddNullKey() {
+        deviceKeyStore.createOrUpdateDeviceKey(null);
+    }
+
+    /**
+     * Tests adding a device key to the store. This also tests the device key store
+     * query methods.
+     */
+    @Test
+    public void testAddKey() {
+        DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue);
+
+        DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId,
+                                                                          deviceKeyLabel, deviceKeySnmpName);
+
+        // Test to make sure that the device key store is empty
+        Collection<DeviceKey> deviceKeys = deviceKeyStore.getDeviceKeys();
+        assertTrue("The device key set should be empty.", deviceKeys.isEmpty());
+
+        // Add the new device key to the store
+        deviceKeyStore.createOrUpdateDeviceKey(deviceKey);
+
+        // Test the getDeviceKeys method to make sure that the new device key exists
+        deviceKeys = deviceKeyStore.getDeviceKeys();
+        assertEquals("There should be one device key in the set.", deviceKeys.size(), 1);
+
+        // Test the getDeviceKey method using the device key unique identifier
+        deviceKey = deviceKeyStore.getDeviceKey(deviceKeyId);
+        assertEquals("There should be one device key in the set.", deviceKeys.size(), 1);
+    }
+
+    /**
+     * Tests re-adding the same device key to the store but with a different label.
+     */
+    @Test
+    public void testAddSameKey() {
+        DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue);
+
+        DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId,
+                                                                          deviceKeyLabel, deviceKeySnmpName);
+
+        // Add the first device key to the store
+        deviceKeyStore.createOrUpdateDeviceKey(deviceKey);
+
+        // Test the getDeviceKeys method
+        Collection<DeviceKey> deviceKeys = deviceKeyStore.getDeviceKeys();
+        assertEquals("There should be one device key in the set.", deviceKeys.size(), 1);
+
+        // Now let's create a new device key with the same device key identifier as exists in the store.
+        DeviceKey deviceKey2 = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId,
+                                                                           deviceKeyLabel2, deviceKeySnmpName);
+
+        // Replace the new device key in the store
+        deviceKeyStore.createOrUpdateDeviceKey(deviceKey2);
+
+        // Test the getDeviceKeys method to ensure that only 1 device key exists in the store.
+        deviceKeys = deviceKeyStore.getDeviceKeys();
+        assertEquals("There should be one device key in the set.", deviceKeys.size(), 1);
+
+        // Test the getDeviceKey method using the device key unique identifier
+        deviceKey = deviceKeyStore.getDeviceKey(deviceKeyId);
+        assertNotNull("The device key should not be null.", deviceKey);
+        assertEquals("The device key label should match.", deviceKeyLabel2, deviceKey.label());
+    }
+
+    /**
+     * Tests removal of a device key from the store using the device key identifier.
+     */
+    @Test
+    public void testRemoveKey() {
+        DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue);
+        DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId,
+                                                                          deviceKeyLabel, deviceKeySnmpName);
+        // Add the new device key to the store
+        deviceKeyStore.createOrUpdateDeviceKey(deviceKey);
+
+        // Remove the device key from the store
+        deviceKeyStore.deleteDeviceKey(deviceKeyId);
+
+        // Validate that the device key was removed from the store by querying it.
+        deviceKey = deviceKeyStore.getDeviceKey(deviceKeyId);
+        assertNull("The device key set should be empty.", deviceKey);
+    }
+}