Implement SimpleMappingStore with augmented StoredMappingEntry

Change-Id: Iea1623757b95b322910fcf2506d61431e0da1693
diff --git a/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/DefaultMappingEntry.java b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/DefaultMappingEntry.java
index 626cee2..844bad0 100644
--- a/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/DefaultMappingEntry.java
+++ b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/DefaultMappingEntry.java
@@ -23,7 +23,7 @@
 /**
  * Default implementation of MappingEntry.
  */
-public class DefaultMappingEntry extends DefaultMapping implements MappingEntry {
+public class DefaultMappingEntry extends DefaultMapping implements StoredMappingEntry {
 
     private static final Logger log = getLogger(DefaultMappingEntry.class);
 
@@ -61,4 +61,9 @@
                 .add("state", state)
                 .toString();
     }
+
+    @Override
+    public void setState(MappingEntryState newState) {
+        this.state = newState;
+    }
 }
diff --git a/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/MappingStore.java b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/MappingStore.java
index b93a3a9..49d8169 100644
--- a/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/MappingStore.java
+++ b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/MappingStore.java
@@ -50,7 +50,7 @@
     /**
      * Obtains the stored mapping from the specified store.
      *
-     * @param type store type
+     * @param type    store type
      * @param mapping the mapping to look for
      * @return a mapping
      */
@@ -60,17 +60,25 @@
      * Obtains the mapping entries associated with a device from the
      * specified store.
      *
-     * @param type store type
+     * @param type     store type
      * @param deviceId device identifier
      * @return the mapping entries
      */
     Iterable<MappingEntry> getMappingEntries(Type type, DeviceId deviceId);
 
     /**
+     * Stores a new mapping.
+     *
+     * @param type    store type
+     * @param mapping the mapping to add
+     */
+    void storeMapping(Type type, Mapping mapping);
+
+    /**
      * Marks a mapping for deletion. Actual deletion will occur when the
      * provider indicates that the mapping has been removed.
      *
-     * @param type store type
+     * @param type    store type
      * @param mapping the mapping to delete
      */
     void deleteMapping(Type type, Mapping mapping);
@@ -79,7 +87,7 @@
      * Stores a new mapping or updates an existing entry from/to the
      * specified store.
      *
-     * @param type store type
+     * @param type  store type
      * @param entry the mapping to add or update
      * @return mapping_added event, or null if just an update
      */
@@ -88,7 +96,7 @@
     /**
      * Removes an existing mapping from the specified store.
      *
-     * @param type store type
+     * @param type  store type
      * @param entry the mapping to remove
      * @return mapping_removed event, or null if nothing removed
      */
@@ -96,10 +104,10 @@
 
     /**
      * Marks a mapping as PENDING_ADD during retry.
-     *
+     * <p>
      * Emits mapping_update event if the state is changed
      *
-     * @param type store type
+     * @param type  store type
      * @param entry the mapping that is retrying
      * @return mapping_updated event, or null if nothing updated
      */
@@ -108,10 +116,11 @@
     /**
      * Removes all mapping entries of given device from the specified store.
      *
-     * @param type store type
+     * @param type     store type
      * @param deviceId device identifier
      */
-    default void purgeMappingEntry(Type type, DeviceId deviceId) {}
+    default void purgeMappingEntry(Type type, DeviceId deviceId) {
+    }
 
     /**
      * Removes all mapping entries from the specified store.
diff --git a/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/StoredMappingEntry.java b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/StoredMappingEntry.java
new file mode 100644
index 0000000..02ddce6
--- /dev/null
+++ b/apps/mappingmanagement/api/src/main/java/org/onosproject/mapping/StoredMappingEntry.java
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+package org.onosproject.mapping;
+
+/**
+ * An augmented mapping entry interface which allows to set state.
+ */
+public interface StoredMappingEntry extends MappingEntry {
+
+    /**
+     * Sets the new state for this entry.
+     *
+     * @param newState new mapping entry state
+     */
+    void setState(MappingEntryState newState);
+}
diff --git a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
index 772337e..d0f085a 100644
--- a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
+++ b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
@@ -83,6 +83,11 @@
     }
 
     @Override
+    public void storeMapping(Type type, Mapping mapping) {
+
+    }
+
+    @Override
     public void deleteMapping(Type type, Mapping mapping) {
 
     }
diff --git a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/SimpleMappingStore.java b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/SimpleMappingStore.java
index d82ff94..17b403f 100644
--- a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/SimpleMappingStore.java
+++ b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/SimpleMappingStore.java
@@ -15,28 +15,36 @@
  */
 package org.onosproject.mapping.impl;
 
+import com.google.common.collect.FluentIterable;
 import com.google.common.collect.Maps;
-
 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.Service;
 import org.apache.felix.scr.annotations.Modified;
-import org.onosproject.mapping.MappingEvent;
+import org.apache.felix.scr.annotations.Service;
+import org.onosproject.mapping.DefaultMappingEntry;
 import org.onosproject.mapping.Mapping;
+import org.onosproject.mapping.MappingEntry;
+import org.onosproject.mapping.MappingEvent;
 import org.onosproject.mapping.MappingId;
 import org.onosproject.mapping.MappingStore;
-import org.onosproject.mapping.MappingEntry;
 import org.onosproject.mapping.MappingStoreDelegate;
+import org.onosproject.mapping.StoredMappingEntry;
 import org.onosproject.net.DeviceId;
 import org.onosproject.store.AbstractStore;
 import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
 
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.CopyOnWriteArrayList;
 
+import static org.onosproject.mapping.MappingEntry.MappingEntryState.PENDING_ADD;
+import static org.onosproject.mapping.MappingEntry.MappingEntryState.PENDING_REMOVE;
+import static org.onosproject.mapping.MappingEvent.Type.MAPPING_ADDED;
+import static org.onosproject.mapping.MappingEvent.Type.MAPPING_REMOVED;
+import static org.onosproject.mapping.MappingEvent.Type.MAPPING_UPDATED;
 import static org.slf4j.LoggerFactory.getLogger;
 
 /**
@@ -50,13 +58,13 @@
 
     private final Logger log = getLogger(getClass());
 
-    private final ConcurrentMap<DeviceId, ConcurrentMap<MappingId, List<MappingEntry>>>
-            mapDbStore = Maps.newConcurrentMap();
+    private static final String UNRECOGNIZED_STORE_MSG = "Unrecognized store type {}";
 
-    private final ConcurrentMap<DeviceId, ConcurrentMap<MappingId, List<MappingEntry>>>
-            mapCacheStore = Maps.newConcurrentMap();
+    private final ConcurrentMap<DeviceId, ConcurrentMap<MappingId,
+                  List<StoredMappingEntry>>> mapDbStore = Maps.newConcurrentMap();
 
-    private final AtomicInteger localBatchIdGen = new AtomicInteger();
+    private final ConcurrentMap<DeviceId, ConcurrentMap<MappingId,
+                  List<StoredMappingEntry>>> mapCacheStore = Maps.newConcurrentMap();
 
     @Activate
     public void activate() {
@@ -77,42 +85,222 @@
 
     @Override
     public int getMappingCount(Type type) {
-        return 0;
+        int sum = 0;
+
+        ConcurrentMap<DeviceId, ConcurrentMap<MappingId,
+                List<StoredMappingEntry>>> store = Maps.newConcurrentMap();
+
+        switch (type) {
+            case MAP_DATABASE:
+                store = mapDbStore;
+                break;
+            case MAP_CACHE:
+                store = mapCacheStore;
+                break;
+            default:
+                log.error(UNRECOGNIZED_STORE_MSG, type);
+                break;
+        }
+
+        for (ConcurrentMap<MappingId, List<StoredMappingEntry>> mapDb : store.values()) {
+            for (List<StoredMappingEntry> mes : mapDb.values()) {
+                sum += mes.size();
+            }
+        }
+
+        return sum;
+    }
+
+    /**
+     * Obtains the mapping store for specified device and store type.
+     *
+     * @param type     mapping store type
+     * @param deviceId device identifier
+     * @return Map representing Mapping Store of given device and store type
+     */
+    private ConcurrentMap<MappingId, List<StoredMappingEntry>>
+                                     getMappingStoreByDeviceId(Type type,
+                                                               DeviceId deviceId) {
+        switch (type) {
+            case MAP_DATABASE:
+                return mapDbStore.computeIfAbsent(deviceId,
+                                                    k -> Maps.newConcurrentMap());
+            case MAP_CACHE:
+                return mapCacheStore.computeIfAbsent(deviceId,
+                                                    k -> Maps.newConcurrentMap());
+            default:
+                log.error(UNRECOGNIZED_STORE_MSG, type);
+                return null;
+        }
+    }
+
+    /**
+     * Obtains the mapping store for specified store type.
+     *
+     * @param type mapping store type
+     * @return mapping store
+     */
+    private ConcurrentMap<DeviceId, ConcurrentMap<MappingId, List<StoredMappingEntry>>>
+                                    getMappingStore(Type type) {
+        switch (type) {
+            case MAP_DATABASE:
+                return mapDbStore;
+            case MAP_CACHE:
+                return mapCacheStore;
+            default:
+                log.error(UNRECOGNIZED_STORE_MSG, type);
+                return null;
+        }
+    }
+
+    /**
+     * Obtains mapping entries for specified device, store type and mapping ID.
+     *
+     * @param type      mapping store type
+     * @param deviceId  device identifier
+     * @param mappingId mapping identifier
+     * @return a collection of mapping entries
+     */
+    private List<StoredMappingEntry> getMappingEntriesInternal(Type type,
+                                                               DeviceId deviceId,
+                                                               MappingId mappingId) {
+        final ConcurrentMap<MappingId, List<StoredMappingEntry>>
+                            store = getMappingStoreByDeviceId(type, deviceId);
+        List<StoredMappingEntry> r = store.get(mappingId);
+        if (r == null) {
+            final List<StoredMappingEntry> concurrentlyAdded;
+            r = new CopyOnWriteArrayList<>();
+            concurrentlyAdded = store.putIfAbsent(mappingId, r);
+            if (concurrentlyAdded != null) {
+                return concurrentlyAdded;
+            }
+        }
+        return r;
+    }
+
+    /**
+     * Obtains a mapping entry for specified device, store type and mapping.
+     *
+     * @param type      mapping store type
+     * @param deviceId  device identifier
+     * @param mapping   mapping identifier
+     * @return a mapping entry
+     */
+    private MappingEntry getMappingEntryInternal(Type type, DeviceId deviceId,
+                                                 Mapping mapping) {
+        List<StoredMappingEntry> mes =
+                        getMappingEntriesInternal(type, deviceId, mapping.id());
+        for (StoredMappingEntry me : mes) {
+            if (me.equals(mapping)) {
+                return me;
+            }
+        }
+        return null;
     }
 
     @Override
     public MappingEntry getMappingEntry(Type type, Mapping mapping) {
-        return null;
+        return getMappingEntryInternal(type, mapping.deviceId(), mapping);
     }
 
     @Override
     public Iterable<MappingEntry> getMappingEntries(Type type, DeviceId deviceId) {
-        return null;
+        // FIXME: a better way is using Java 8 API to return immutable iterables
+        return FluentIterable.from(getMappingStoreByDeviceId(type, deviceId).values())
+                .transformAndConcat(Collections::unmodifiableList);
+    }
+
+    @Override
+    public void storeMapping(Type type, Mapping mapping) {
+
+        List<StoredMappingEntry> entries =
+                getMappingEntriesInternal(type, mapping.deviceId(), mapping.id());
+
+        synchronized (entries) {
+            if (!entries.contains(mapping)) {
+                StoredMappingEntry entry = new DefaultMappingEntry(mapping);
+                entries.add(entry);
+            }
+        }
     }
 
     @Override
     public void deleteMapping(Type type, Mapping mapping) {
 
+        List<StoredMappingEntry> entries =
+                getMappingEntriesInternal(type, mapping.deviceId(), mapping.id());
+
+        synchronized (entries) {
+            for (StoredMappingEntry entry : entries) {
+                if (entry.equals(mapping)) {
+                    synchronized (entry) {
+                        entry.setState(PENDING_REMOVE);
+                    }
+                }
+            }
+        }
     }
 
     @Override
     public MappingEvent addOrUpdateMappingEntry(Type type, MappingEntry entry) {
+
+        List<StoredMappingEntry> entries =
+                    getMappingEntriesInternal(type, entry.deviceId(), entry.id());
+        synchronized (entries) {
+            for (StoredMappingEntry stored : entries) {
+                if (stored.equals(entry)) {
+                    if (stored.state() == PENDING_ADD) {
+                        stored.setState(MappingEntry.MappingEntryState.ADDED);
+                        return new MappingEvent(MAPPING_ADDED, entry);
+                    }
+                    return new MappingEvent(MAPPING_UPDATED, entry);
+                }
+            }
+        }
+
+        log.error("Mapping was not found in store {} to update", entry);
+
         return null;
     }
 
     @Override
     public MappingEvent removeMappingEntry(Type type, MappingEntry entry) {
+
+        List<StoredMappingEntry> entries =
+                getMappingEntriesInternal(type, entry.deviceId(), entry.id());
+        synchronized (entries) {
+            if (entries.remove(entry)) {
+                return new MappingEvent(MAPPING_REMOVED, entry);
+            }
+        }
         return null;
     }
 
     @Override
     public MappingEvent pendingMappingEntry(Type type, MappingEntry entry) {
+        List<StoredMappingEntry> entries =
+                getMappingEntriesInternal(type, entry.deviceId(), entry.id());
+        synchronized (entries) {
+            for (StoredMappingEntry stored : entries) {
+                if (stored.equals(entry) && (stored.state() != PENDING_ADD)) {
+                    synchronized (stored) {
+                        stored.setState(PENDING_ADD);
+                        return new MappingEvent(MAPPING_UPDATED, entry);
+                    }
+                }
+            }
+        }
         return null;
     }
 
     @Override
-    public void purgeMappingEntries(Type type) {
+    public void purgeMappingEntry(Type type, DeviceId deviceId) {
+        getMappingStore(type).remove(deviceId);
+    }
 
+    @Override
+    public void purgeMappingEntries(Type type) {
+        getMappingStore(type).clear();
     }
 }