Adding additional TreeMap resources

Change-Id: I103a8c5e6fb1c5e7a6ae0942e0b746367da18736
diff --git a/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentMap.java b/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentMap.java
index 9a432e0..f25fadc 100644
--- a/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentMap.java
+++ b/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentMap.java
@@ -243,8 +243,9 @@
     CompletableFuture<Set<Entry<K, Versioned<V>>>> entrySet();
 
     /**
-     * If the specified key is not already associated with a value
-     * associates it with the given value and returns null, else returns the current value.
+     * If the specified key is not already associated with a value associates
+     * it with the given value and returns null, else behaves as a get
+     * returning the existing mapping without making any changes.
      *
      * @param key key with which the specified value is to be associated
      * @param value value to be associated with the specified key
diff --git a/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentTreeMap.java b/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentTreeMap.java
index b4a1b40..5c60b19 100644
--- a/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentTreeMap.java
+++ b/core/api/src/main/java/org/onosproject/store/service/AsyncConsistentTreeMap.java
@@ -19,6 +19,7 @@
 import org.onosproject.store.primitives.DefaultConsistentTreeMap;
 
 import java.util.Map;
+import java.util.NavigableMap;
 import java.util.NavigableSet;
 import java.util.concurrent.CompletableFuture;
 
@@ -42,26 +43,28 @@
     CompletableFuture<K> lastKey();
 
     /**
-     * Returns the entry associated with the least key greater than or equal to the key.
+     * Returns the entry associated with the least key greater than or equal to
+     * the key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> ceilingEntry(K key);
 
     /**
-     * Returns the entry associated with the greatest key less than or equal to key.
+     * Returns the entry associated with the greatest key less than or equal
+     * to key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> floorEntry(K key);
 
     /**
-     * Returns the entry associated with the lest key greater than key.
+     * Returns the entry associated with the least key greater than key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> higherEntry(K key);
 
@@ -69,35 +72,35 @@
      * Returns the entry associated with the largest key less than key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> lowerEntry(K key);
 
     /**
      * Return the entry associated with the lowest key in the map.
      *
-     * @return the entry or null
+     * @return the entry or null if none exist
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> firstEntry();
 
     /**
-     * Return the entry assocaited with the highest key in the map.
+     * Return the entry associated with the highest key in the map.
      *
-     * @return the entry or null
+     * @return the entry or null if none exist
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> lastEntry();
 
     /**
      * Return and remove the entry associated with the lowest key.
      *
-     * @return the entry or null
+     * @return the entry or null if none exist
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> pollFirstEntry();
 
     /**
      * Return and remove the entry associated with the highest key.
      *
-     * @return the entry or null
+     * @return the entry or null if none exist
      */
     CompletableFuture<Map.Entry<K, Versioned<V>>> pollLastEntry();
 
@@ -105,15 +108,15 @@
      * Return the entry associated with the greatest key less than key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<K> lowerKey(K key);
 
     /**
-     * Return the entry associated with the highest key less than or equal to key.
+     * Return the highest key less than or equal to key.
      *
      * @param key the key
-     * @return the entry or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<K> floorKey(K key);
 
@@ -121,7 +124,7 @@
      * Return the lowest key greater than or equal to key.
      *
      * @param key the key
-     * @return the key or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<K> ceilingKey(K key);
 
@@ -129,17 +132,35 @@
      * Return the lowest key greater than key.
      *
      * @param key the key
-     * @return the key or null
+     * @return the entry or null if no suitable key exists
      */
     CompletableFuture<K> higherKey(K key);
 
     /**
      * Returns a navigable set of the keys in this map.
      *
-     * @return a navigable key set
+     * @return a navigable key set (this may be empty)
      */
     CompletableFuture<NavigableSet<K>> navigableKeySet();
 
+    /**
+     * Returns a navigable map containing the entries from the original map
+     * which are larger than (or if specified equal to) {@code lowerKey} AND
+     * less than (or if specified equal to) {@code upperKey}.
+     *
+     * @param upperKey the upper bound for the keys in this map
+     * @param lowerKey the lower bound for the keys in this map
+     * @param inclusiveUpper whether keys equal to the upperKey should be
+     *                       included
+     * @param inclusiveLower whether keys equal to the lowerKey should be
+     *                       included
+     * @return a navigable map containing entries in the specified range (this
+     * may be empty)
+     */
+    CompletableFuture<NavigableMap<K, V>> subMap(K upperKey, K lowerKey,
+                                                 boolean inclusiveUpper,
+                                                 boolean inclusiveLower);
+
     default ConsistentTreeMap<K, V> asTreeMap() {
         return asTreeMap(DistributedPrimitive.DEFAULT_OPERTATION_TIMEOUT_MILLIS);
     }
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java
index 8bab853..df567d2 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java
@@ -266,7 +266,7 @@
     public synchronized CompletableFuture<Void> addListener(MapEventListener<String, byte[]> listener,
                                                             Executor executor) {
         if (mapEventListeners.isEmpty()) {
-            return client.submit(new Listen()).thenRun(() -> mapEventListeners.putIfAbsent(listener, executor));
+            return client.submit(new Listen()).thenRun(() -> mapEventListeners.put(listener, executor));
         } else {
             mapEventListeners.put(listener, executor);
             return CompletableFuture.completedFuture(null);
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMap.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMap.java
new file mode 100644
index 0000000..3baadde
--- /dev/null
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMap.java
@@ -0,0 +1,401 @@
+/*
+ * 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.primitives.resources.impl;
+
+import com.google.common.collect.Maps;
+import io.atomix.copycat.client.CopycatClient;
+import io.atomix.resource.AbstractResource;
+import io.atomix.resource.ResourceTypeInfo;
+import org.onlab.util.Match;
+import org.onosproject.store.primitives.TransactionId;
+import org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstKey;
+import org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorEntry;
+import org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherEntry;
+import org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastEntry;
+import org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerEntry;
+import org.onosproject.store.service.AsyncConsistentTreeMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+import org.onosproject.store.service.MapTransaction;
+import org.onosproject.store.service.Versioned;
+
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NavigableSet;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiFunction;
+import java.util.function.Predicate;
+
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Clear;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsValue;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.EntrySet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Get;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.IsEmpty;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.KeySet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Listen;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollFirstEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollLastEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Size;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Unlisten;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.UpdateAndGet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Values;
+
+/**
+ * Implementation of {@link AsyncConsistentTreeMap}.
+ */
+@ResourceTypeInfo(id = -155, factory = AtomixConsistentTreeMapFactory.class)
+public class AtomixConsistentTreeMap extends AbstractResource<AtomixConsistentTreeMap>
+        implements AsyncConsistentTreeMap<String, byte[]> {
+
+    private final Map<MapEventListener<String, byte[]>, Executor>
+            mapEventListeners = Maps.newConcurrentMap();
+
+    public static final String CHANGE_SUBJECT = "changeEvents";
+
+    public AtomixConsistentTreeMap(CopycatClient client, Properties options) {
+        super(client, options);
+    }
+
+    @Override
+    public String name() {
+        return null;
+    }
+
+    @Override
+    public CompletableFuture<AtomixConsistentTreeMap> open() {
+        return super.open().thenApply(result -> {
+            client.onEvent(CHANGE_SUBJECT, this::handleEvent);
+            return result;
+        });
+    }
+
+    private void handleEvent(List<MapEvent<String, byte[]>> events) {
+        events.forEach(event -> mapEventListeners.
+                forEach((listener, executor) ->
+                                executor.execute(() ->
+                                                     listener.event(event))));
+    }
+
+    @Override
+    public CompletableFuture<Boolean> isEmpty() {
+        return client.submit(new IsEmpty());
+    }
+
+    @Override
+    public CompletableFuture<Integer> size() {
+        return client.submit(new Size());
+    }
+
+    @Override
+    public CompletableFuture<Boolean> containsKey(String key) {
+        return client.submit(new ContainsKey(key));
+    }
+
+    @Override
+    public CompletableFuture<Boolean> containsValue(byte[] value) {
+        return client.submit(new ContainsValue(value));
+    }
+
+    @Override
+    public CompletableFuture<Versioned<byte[]>> get(String key) {
+        return client.submit(new Get(key));
+    }
+
+    @Override
+    public CompletableFuture<Set<String>> keySet() {
+        return client.submit(new KeySet());
+    }
+
+    @Override
+    public CompletableFuture<Collection<Versioned<byte[]>>> values() {
+        return client.submit(new Values());
+    }
+
+    @Override
+    public CompletableFuture<Set<Map.Entry<String, Versioned<byte[]>>>> entrySet() {
+        return client.submit(new EntrySet());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> put(String key, byte[] value) {
+        return client.submit(new UpdateAndGet(key, value, Match.ANY, Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.oldValue());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> putAndGet(String key, byte[] value) {
+        return client.submit(new UpdateAndGet(key, value, Match.ANY, Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.newValue());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> putIfAbsent(String key, byte[] value) {
+        return client.submit(new UpdateAndGet(key, value, Match.NULL, Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.oldValue());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> remove(String key) {
+        return client.submit(new UpdateAndGet(key, null, Match.ANY, Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.oldValue());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Boolean> remove(String key, byte[] value) {
+        return client.submit(new UpdateAndGet(key, null, Match.ifValue(value), Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.updated());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Boolean> remove(String key, long version) {
+        return client.submit(new UpdateAndGet(key, null, Match.ANY, Match.ifValue(version)))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.updated());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> replace(String key, byte[] value) {
+        return client.submit(new UpdateAndGet(key, value, Match.NOT_NULL, Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.oldValue());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Boolean> replace(String key, byte[] oldValue, byte[] newValue) {
+        return client.submit(new UpdateAndGet(key, newValue, Match.ifValue(oldValue), Match.ANY))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.updated());
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Boolean> replace(String key, long oldVersion, byte[] newValue) {
+        return client.submit(new UpdateAndGet(key, newValue, Match.ANY, Match.ifValue(oldVersion)))
+                .whenComplete((r, e) -> throwIfLocked(r.status()))
+                .thenApply(v -> v.updated());
+    }
+
+    @Override
+    public CompletableFuture<Void> clear() {
+        return client.submit(new Clear())
+                .whenComplete((r, e) -> throwIfLocked(r))
+                .thenApply(v -> null);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public CompletableFuture<Versioned<byte[]>> computeIf(String key,
+                                                          Predicate<? super byte[]> condition,
+                                                          BiFunction<? super String,
+                                                                  ? super byte[],
+                                                                  ? extends byte[]> remappingFunction) {
+        return get(key).thenCompose(r1 -> {
+            byte[] existingValue = r1 == null ? null : r1.value();
+
+            if (!condition.test(existingValue)) {
+                return CompletableFuture.completedFuture(r1);
+            }
+
+            AtomicReference<byte[]> computedValue = new AtomicReference<byte[]>();
+            try {
+                computedValue.set(remappingFunction.apply(key, existingValue));
+            } catch (Exception e) {
+                CompletableFuture<Versioned<byte[]>> future = new CompletableFuture<>();
+                future.completeExceptionally(e);
+                return future;
+            }
+            if (computedValue.get() == null && r1 == null) {
+                return CompletableFuture.completedFuture(null);
+            }
+            Match<byte[]> valueMatch = r1 == null ? Match.NULL : Match.ANY;
+            Match<Long> versionMatch = r1 == null ? Match.ANY : Match.ifValue(r1.version());
+            return client.submit(new UpdateAndGet(key, computedValue.get(),
+                                                                      valueMatch, versionMatch))
+                    .whenComplete((r, e) -> throwIfLocked(r.status()))
+                    .thenApply(v -> v.newValue());
+        });
+    }
+
+    @Override
+    public CompletableFuture<Void> addListener(
+            MapEventListener<String, byte[]> listener, Executor executor) {
+        if (mapEventListeners.isEmpty()) {
+            return client.submit(new Listen()).thenRun(() ->
+                                   mapEventListeners.put(listener,
+                                           executor));
+        } else {
+            mapEventListeners.put(listener, executor);
+            return CompletableFuture.completedFuture(null);
+        }
+    }
+
+    @Override
+    public synchronized CompletableFuture<Void> removeListener(MapEventListener<String, byte[]> listener) {
+        if (mapEventListeners.remove(listener) != null &&
+                mapEventListeners.isEmpty()) {
+            return client.submit(new Unlisten())
+                    .thenApply(v -> null);
+        }
+        return CompletableFuture.completedFuture(null);
+    }
+
+
+    private void throwIfLocked(MapEntryUpdateResult.Status status) {
+        if (status == MapEntryUpdateResult.Status.WRITE_LOCK) {
+            throw new ConcurrentModificationException("Cannot update TreeMap: another update is in progress.");
+        }
+    }
+
+    @Override
+    public CompletableFuture<String> firstKey() {
+        return client.submit(new FirstKey<String>());
+    }
+
+    @Override
+    public CompletableFuture<String> lastKey() {
+        return client.submit(new LastKey<String>());
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> ceilingEntry(String key) {
+        return client.submit(new CeilingEntry(key));
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> floorEntry(String key) {
+        return client.submit(new FloorEntry<String, Versioned<byte[]>>(key));
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> higherEntry(
+            String key) {
+        return client.submit(new HigherEntry<String, Versioned<byte[]>>(key));
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> lowerEntry(
+            String key) {
+        return client.submit(new LowerEntry<>(key));
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> firstEntry() {
+        return client.submit(new FirstEntry());
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> lastEntry() {
+        return client.submit(new LastEntry<String, Versioned<byte[]>>());
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> pollFirstEntry() {
+        return client.submit(new PollFirstEntry());
+    }
+
+    @Override
+    public CompletableFuture<Map.Entry<String, Versioned<byte[]>>> pollLastEntry() {
+        return client.submit(new PollLastEntry());
+    }
+
+    @Override
+    public CompletableFuture<String> lowerKey(String key) {
+        return client.submit(new LowerKey(key));
+    }
+
+    @Override
+    public CompletableFuture<String> floorKey(String key) {
+        return client.submit(new FloorKey(key));
+    }
+
+    @Override
+    public CompletableFuture<String> ceilingKey(String key) {
+        return client.submit(new CeilingKey(key));
+    }
+
+    @Override
+    public CompletableFuture<String> higherKey(String key) {
+        return client.submit(new HigherKey(key));
+    }
+
+    @Override
+    public CompletableFuture<NavigableSet<String>> navigableKeySet() {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");
+    }
+
+    @Override
+    public CompletableFuture<NavigableMap<String, byte[]>> subMap(
+            String upperKey, String lowerKey, boolean inclusiveUpper,
+            boolean inclusiveLower) {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");    }
+
+    @Override
+    public CompletableFuture<Boolean> prepareAndCommit(MapTransaction<String,
+            byte[]> transaction) {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");
+    }
+
+    @Override
+    public CompletableFuture<Boolean> prepare(MapTransaction<String, byte[]>
+                                                          transaction) {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");
+    }
+
+    @Override
+    public CompletableFuture<Void> commit(TransactionId transactionId) {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");
+    }
+
+    @Override
+    public CompletableFuture<Void> rollback(TransactionId transactionId) {
+        throw new UnsupportedOperationException("This operation is not yet " +
+                                                        "supported.");
+    }
+}
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapFactory.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapFactory.java
new file mode 100644
index 0000000..4d0ec89
--- /dev/null
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapFactory.java
@@ -0,0 +1,44 @@
+/*
+ * 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.primitives.resources.impl;
+
+import io.atomix.catalyst.serializer.SerializableTypeResolver;
+import io.atomix.copycat.client.CopycatClient;
+import io.atomix.resource.ResourceFactory;
+import io.atomix.resource.ResourceStateMachine;
+
+import java.util.Properties;
+
+/**
+ * Factory for {@link AtomixConsistentTreeMap}.
+ */
+public class AtomixConsistentTreeMapFactory implements ResourceFactory<AtomixConsistentTreeMap> {
+    @Override
+    public SerializableTypeResolver createSerializableTypeResolver() {
+        return new AtomixConsistentTreeMapCommands.TypeResolver();
+    }
+
+    @Override
+    public ResourceStateMachine createStateMachine(Properties config) {
+        return new AtomixConsistentTreeMapState(config);
+    }
+
+    @Override
+    public AtomixConsistentTreeMap createInstance(CopycatClient client, Properties options) {
+        return new AtomixConsistentTreeMap(client, options);
+    }
+}
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java
new file mode 100644
index 0000000..2f8f5a8
--- /dev/null
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapState.java
@@ -0,0 +1,579 @@
+/*
+ * 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.primitives.resources.impl;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import io.atomix.copycat.server.Commit;
+import io.atomix.copycat.server.Snapshottable;
+import io.atomix.copycat.server.StateMachineExecutor;
+import io.atomix.copycat.server.session.ServerSession;
+import io.atomix.copycat.server.session.SessionListener;
+import io.atomix.copycat.server.storage.snapshot.SnapshotReader;
+import io.atomix.copycat.server.storage.snapshot.SnapshotWriter;
+import io.atomix.resource.ResourceStateMachine;
+import org.onlab.util.Match;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.Versioned;
+
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.CeilingKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Clear;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.ContainsValue;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.EntrySet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FirstKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.FloorKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Get;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.HigherKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.IsEmpty;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.KeySet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LastKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Listen;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.LowerKey;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollFirstEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.PollLastEntry;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Size;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.SubMap;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Unlisten;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.UpdateAndGet;
+import static org.onosproject.store.primitives.resources.impl.AtomixConsistentTreeMapCommands.Values;
+import static org.onosproject.store.primitives.resources.impl.MapEntryUpdateResult.*;
+
+/**
+ * State machine corresponding to {@link AtomixConsistentTreeMap} backed by a
+ * {@link TreeMap}.
+ */
+public class AtomixConsistentTreeMapState extends ResourceStateMachine implements SessionListener, Snapshottable {
+
+    private final Map<Long, Commit<? extends Listen>> listeners =
+            Maps.newHashMap();
+    private TreeMap<String, TreeMapEntryValue> tree = Maps.newTreeMap();
+    private final Set<String> preparedKeys = Sets.newHashSet();
+    private AtomicLong versionCounter = new AtomicLong(0);
+
+    private Function<Commit<SubMap>, NavigableMap<String, TreeMapEntryValue>> subMapFunction = this::subMap;
+    private Function<Commit<FirstKey>, String> firstKeyFunction = this::firstKey;
+    private Function<Commit<LastKey>, String> lastKeyFunction = this::lastKey;
+    private Function<Commit<HigherEntry>, Map.Entry<String, Versioned<byte[]>>> higherEntryFunction =
+            this::higherEntry;
+    private Function<Commit<FirstEntry>, Map.Entry<String, Versioned<byte[]>>> firstEntryFunction =
+            this::firstEntry;
+    private Function<Commit<LastEntry>, Map.Entry<String, Versioned<byte[]>>> lastEntryFunction =
+            this::lastEntry;
+    private Function<Commit<PollFirstEntry>, Map.Entry<String, Versioned<byte[]>>> pollFirstEntryFunction =
+            this::pollFirstEntry;
+    private Function<Commit<PollLastEntry>, Map.Entry<String, Versioned<byte[]>>> pollLastEntryFunction =
+            this::pollLastEntry;
+    private Function<Commit<LowerEntry>, Map.Entry<String, Versioned<byte[]>>> lowerEntryFunction =
+            this::lowerEntry;
+    private Function<Commit<LowerKey>, String> lowerKeyFunction = this::lowerKey;
+    private Function<Commit<FloorEntry>, Map.Entry<String, Versioned<byte[]>>> floorEntryFunction =
+            this::floorEntry;
+    private Function<Commit<CeilingEntry>, Map.Entry<String, Versioned<byte[]>>> ceilingEntryFunction =
+            this::ceilingEntry;
+    private Function<Commit<FloorKey>, String> floorKeyFunction = this::floorKey;
+    private Function<Commit<CeilingKey>, String> ceilingKeyFunction = this::ceilingKey;
+    private Function<Commit<HigherKey>, String> higherKeyFunction = this::higherKey;
+
+    public AtomixConsistentTreeMapState(Properties properties) {
+        super(properties);
+    }
+
+    @Override
+    public void snapshot(SnapshotWriter writer) {
+        writer.writeLong(versionCounter.get());
+    }
+
+    @Override
+    public void install(SnapshotReader reader) {
+        versionCounter = new AtomicLong(reader.readLong());
+    }
+
+    @Override
+    public void configure(StateMachineExecutor executor) {
+        // Listeners
+        executor.register(Listen.class, this::listen);
+        executor.register(Unlisten.class, this::unlisten);
+        // Queries
+        executor.register(ContainsKey.class, this::containsKey);
+        executor.register(ContainsValue.class, this::containsValue);
+        executor.register(EntrySet.class, this::entrySet);
+        executor.register(Get.class, this::get);
+        executor.register(IsEmpty.class, this::isEmpty);
+        executor.register(KeySet.class, this::keySet);
+        executor.register(Size.class, this::size);
+        executor.register(Values.class, this::values);
+        executor.register(SubMap.class, subMapFunction);
+        executor.register(FirstKey.class, firstKeyFunction);
+        executor.register(LastKey.class, lastKeyFunction);
+        executor.register(FirstEntry.class, firstEntryFunction);
+        executor.register(LastEntry.class, lastEntryFunction);
+        executor.register(PollFirstEntry.class, pollFirstEntryFunction);
+        executor.register(PollLastEntry.class, pollLastEntryFunction);
+        executor.register(LowerEntry.class, lowerEntryFunction);
+        executor.register(LowerKey.class, lowerKeyFunction);
+        executor.register(FloorEntry.class, floorEntryFunction);
+        executor.register(FloorKey.class, floorKeyFunction);
+        executor.register(CeilingEntry.class, ceilingEntryFunction);
+        executor.register(CeilingKey.class, ceilingKeyFunction);
+        executor.register(HigherEntry.class, higherEntryFunction);
+        executor.register(HigherKey.class, higherKeyFunction);
+
+        // Commands
+        executor.register(UpdateAndGet.class, this::updateAndGet);
+        executor.register(Clear.class, this::clear);
+    }
+
+    @Override
+    public void delete() {
+        listeners.values().forEach(Commit::close);
+        listeners.clear();
+        tree.values().forEach(TreeMapEntryValue::discard);
+        tree.clear();
+    }
+
+    protected boolean containsKey(Commit<? extends ContainsKey> commit) {
+        try {
+            return toVersioned(tree.get((commit.operation().key()))) != null;
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected boolean containsValue(Commit<? extends ContainsValue> commit) {
+        try {
+            Match<byte[]> valueMatch = Match
+                    .ifValue(commit.operation().value());
+            return tree.values().stream().anyMatch(
+                    value -> valueMatch.matches(value.value()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Versioned<byte[]> get(Commit<? extends Get> commit) {
+        try {
+            return toVersioned(tree.get(commit.operation().key()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected int size(Commit<? extends Size> commit) {
+        try {
+            return tree.size();
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected boolean isEmpty(Commit<? extends IsEmpty> commit) {
+        try {
+            return tree.isEmpty();
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Set<String> keySet(Commit<? extends KeySet> commit) {
+        try {
+            return tree.keySet().stream().collect(Collectors.toSet());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Collection<Versioned<byte[]>> values(
+            Commit<? extends Values> commit) {
+        try {
+            return tree.values().stream().map(this::toVersioned)
+                    .collect(Collectors.toList());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Set<Map.Entry<String, Versioned<byte[]>>> entrySet(
+            Commit<? extends EntrySet> commit) {
+        try {
+            return tree
+                    .entrySet()
+                    .stream()
+                    .map(e -> Maps.immutableEntry(e.getKey(),
+                                                  toVersioned(e.getValue())))
+                    .collect(Collectors.toSet());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected MapEntryUpdateResult<String, byte[]> updateAndGet(
+            Commit<? extends UpdateAndGet> commit) {
+        Status updateStatus = validate(commit.operation());
+        String key = commit.operation().key();
+        TreeMapEntryValue oldCommitValue = tree.get(commit.operation().key());
+        Versioned<byte[]> oldTreeValue = toVersioned(oldCommitValue);
+
+        if (updateStatus != Status.OK) {
+            commit.close();
+            return new MapEntryUpdateResult<>(updateStatus, "", key,
+                                                  oldTreeValue, oldTreeValue);
+        }
+
+        byte[] newValue = commit.operation().value();
+        long newVersion = versionCounter.incrementAndGet();
+        Versioned<byte[]> newTreeValue = newValue == null ? null
+                : new Versioned<byte[]>(newValue, newVersion);
+
+        MapEvent.Type updateType = newValue == null ? MapEvent.Type.REMOVE
+                : oldCommitValue == null ? MapEvent.Type.INSERT :
+                MapEvent.Type.UPDATE;
+        if (updateType == MapEvent.Type.REMOVE ||
+                updateType == MapEvent.Type.UPDATE) {
+            tree.remove(key);
+            oldCommitValue.discard();
+        }
+        if (updateType == MapEvent.Type.INSERT ||
+                updateType == MapEvent.Type.UPDATE) {
+            tree.put(key, new NonTransactionalCommit(newVersion, commit));
+        } else {
+            commit.close();
+        }
+        publish(Lists.newArrayList(new MapEvent<>("", key, newTreeValue,
+                                                  oldTreeValue)));
+        return new MapEntryUpdateResult<>(updateStatus, "", key, oldTreeValue,
+                                          newTreeValue);
+    }
+
+    protected Status clear(
+            Commit<? extends Clear> commit) {
+        try {
+            Iterator<Map.Entry<String, TreeMapEntryValue>> iterator = tree
+                    .entrySet()
+                    .iterator();
+            while (iterator.hasNext()) {
+                Map.Entry<String, TreeMapEntryValue> entry = iterator.next();
+                String key = entry.getKey();
+                TreeMapEntryValue value = entry.getValue();
+                Versioned<byte[]> removedValue =
+                        new Versioned<byte[]>(value.value(),
+                                              value.version());
+                publish(Lists.newArrayList(new MapEvent<>("", key, null,
+                                                          removedValue)));
+                value.discard();
+                iterator.remove();
+            }
+            return Status.OK;
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected void listen(
+            Commit<? extends Listen> commit) {
+        Long sessionId = commit.session().id();
+        listeners.put(sessionId, commit);
+        commit.session()
+                .onStateChange(
+                        state -> {
+                            if (state == ServerSession.State.CLOSED
+                                    || state == ServerSession.State.EXPIRED) {
+                                Commit<? extends Listen> listener =
+                                        listeners.remove(sessionId);
+                                if (listener != null) {
+                                    listener.close();
+                                }
+                            }
+                        });
+    }
+
+    protected void unlisten(
+            Commit<? extends Unlisten> commit) {
+        try {
+            Commit<? extends AtomixConsistentTreeMapCommands.Listen> listener =
+                    listeners.remove(commit.session());
+            if (listener != null) {
+                listener.close();
+            }
+        } finally {
+            commit.close();
+        }
+    }
+
+    private Status validate(UpdateAndGet update) {
+        TreeMapEntryValue existingValue = tree.get(update.key());
+        if (existingValue == null && update.value() == null) {
+            return Status.NOOP;
+        }
+        if (preparedKeys.contains(update.key())) {
+            return Status.WRITE_LOCK;
+        }
+        byte[] existingRawValue = existingValue == null ? null :
+                existingValue.value();
+        Long existingVersion = existingValue == null ? null :
+                existingValue.version();
+        return update.valueMatch().matches(existingRawValue)
+                && update.versionMatch().matches(existingVersion) ?
+                Status.OK
+                : Status.PRECONDITION_FAILED;
+    }
+
+    protected NavigableMap<String, TreeMapEntryValue> subMap(
+            Commit<? extends SubMap> commit) {
+        //Do not support this until lazy communication is possible.  At present
+        // it transmits up to the entire map.
+        try {
+            SubMap<String, TreeMapEntryValue> subMap = commit.operation();
+            return tree.subMap(subMap.fromKey(), subMap.isInclusiveFrom(),
+                               subMap.toKey(), subMap.isInclusiveTo());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String firstKey(Commit<? extends FirstKey> commit) {
+        try {
+            if (tree.isEmpty()) {
+                return null;
+            }
+            return tree.firstKey();
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String lastKey(Commit<? extends LastKey> commit) {
+        try {
+            return tree.isEmpty() ? null : tree.lastKey();
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> higherEntry(
+            Commit<? extends HigherEntry> commit) {
+        try {
+            if (tree.isEmpty()) {
+                return null;
+            }
+            return toVersionedEntry(
+                    tree.higherEntry(commit.operation().key()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> firstEntry(
+            Commit<? extends FirstEntry> commit) {
+        try {
+            if (tree.isEmpty()) {
+                return null;
+            }
+            return toVersionedEntry(tree.firstEntry());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> lastEntry(
+            Commit<? extends LastEntry> commit) {
+        try {
+            if (tree.isEmpty()) {
+                return null;
+            }
+            return toVersionedEntry(tree.lastEntry());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> pollFirstEntry(
+            Commit<? extends PollFirstEntry> commit) {
+        try {
+            return toVersionedEntry(tree.pollFirstEntry());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> pollLastEntry(
+            Commit<? extends PollLastEntry> commit) {
+        try {
+            return toVersionedEntry(tree.pollLastEntry());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> lowerEntry(
+            Commit<? extends LowerEntry> commit) {
+        try {
+            return toVersionedEntry(tree.lowerEntry(commit.operation().key()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String lowerKey(Commit<? extends LowerKey> commit) {
+        try {
+            return tree.lowerKey(commit.operation().key());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> floorEntry(
+            Commit<? extends FloorEntry> commit) {
+        try {
+            return toVersionedEntry(tree.floorEntry(commit.operation().key()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String floorKey(Commit<? extends FloorKey> commit) {
+        try {
+            return tree.floorKey(commit.operation().key());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected Map.Entry<String, Versioned<byte[]>> ceilingEntry(
+            Commit<CeilingEntry> commit) {
+        try {
+            return toVersionedEntry(
+                    tree.ceilingEntry(commit.operation().key()));
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String ceilingKey(Commit<CeilingKey> commit) {
+        try {
+            return tree.ceilingKey(commit.operation().key());
+        } finally {
+            commit.close();
+        }
+    }
+
+    protected String higherKey(Commit<HigherKey> commit) {
+        try {
+            return tree.higherKey(commit.operation().key());
+        } finally {
+            commit.close();
+        }
+    }
+
+    private Versioned<byte[]> toVersioned(TreeMapEntryValue value) {
+        return value == null ? null :
+                new Versioned<byte[]>(value.value(), value.version());
+    }
+
+    private Map.Entry<String, Versioned<byte[]>> toVersionedEntry(
+            Map.Entry<String, TreeMapEntryValue> entry) {
+        //FIXME is this the best type of entry to return?
+        return entry == null ? null : new SimpleImmutableEntry<>(
+                entry.getKey(), toVersioned(entry.getValue()));
+    }
+
+    private void publish(List<MapEvent<String, byte[]>> events) {
+        listeners.values().forEach(commit -> commit.session()
+                .publish(AtomixConsistentTreeMap.CHANGE_SUBJECT, events));
+    }
+
+    @Override
+    public void register(ServerSession session) {
+    }
+
+    @Override
+    public void unregister(ServerSession session) {
+        closeListener(session.id());
+    }
+
+    @Override
+    public void expire(ServerSession session) {
+        closeListener(session.id());
+    }
+
+    @Override
+    public void close(ServerSession session) {
+        closeListener(session.id());
+    }
+
+    private void closeListener(Long sessionId) {
+        Commit<? extends Listen> commit = listeners.remove(sessionId);
+        if (commit != null) {
+            commit.close();
+        }
+    }
+
+    private interface TreeMapEntryValue {
+
+        byte[] value();
+
+        long version();
+
+        void discard();
+    }
+
+    private class NonTransactionalCommit implements TreeMapEntryValue {
+        private final long version;
+        private final Commit<? extends UpdateAndGet> commit;
+
+        public NonTransactionalCommit(long version,
+                                      Commit<? extends UpdateAndGet> commit) {
+            this.version = version;
+            this.commit = commit;
+        }
+
+        @Override
+        public byte[] value() {
+            return commit.operation().value();
+        }
+
+        @Override
+        public long version() {
+            return version;
+        }
+
+        @Override
+        public void discard() {
+            commit.close();
+        }
+    }
+}
diff --git a/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentSetMultimapTest.java b/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentSetMultimapTest.java
index 194cc19..314342a 100644
--- a/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentSetMultimapTest.java
+++ b/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentSetMultimapTest.java
@@ -404,7 +404,7 @@
     private AtomixConsistentSetMultimap createResource(String mapName) {
         try {
             AtomixConsistentSetMultimap map = createAtomixClient().
-                    getResource("mapName", AtomixConsistentSetMultimap.class)
+                    getResource(mapName, AtomixConsistentSetMultimap.class)
                     .join();
             return map;
         } catch (Throwable e) {
diff --git a/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapTest.java b/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapTest.java
new file mode 100644
index 0000000..5df6092
--- /dev/null
+++ b/core/store/primitives/src/test/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentTreeMapTest.java
@@ -0,0 +1,660 @@
+/*
+ * 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.primitives.resources.impl;
+
+import com.google.common.base.Throwables;
+import com.google.common.collect.Lists;
+import io.atomix.resource.ResourceType;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onlab.util.Tools;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Unit tests for {@link AtomixConsistentTreeMap}.
+ */
+public class AtomixConsistentTreeMapTest extends AtomixTestBase {
+    private final String keyFour = "hello";
+    private final String keyThree = "goodbye";
+    private final String keyTwo = "foo";
+    private final String keyOne = "bar";
+    private final byte[] valueOne = Tools.getBytesUtf8(keyOne);
+    private final byte[] valueTwo = Tools.getBytesUtf8(keyTwo);
+    private final byte[] valueThree = Tools.getBytesUtf8(keyThree);
+    private final byte[] valueFour = Tools.getBytesUtf8(keyFour);
+    private final byte[] spareValue = Tools.getBytesUtf8("spareValue");
+    private final List<String> allKeys = Lists.newArrayList(keyOne, keyTwo,
+                                                            keyThree, keyFour);
+    private final List<byte[]> allValues = Lists.newArrayList(valueOne,
+                                                              valueTwo,
+                                                              valueThree,
+                                                              valueFour);
+    @BeforeClass
+    public static void preTestSetup() throws Throwable {
+        createCopycatServers(3);
+    }
+
+    @AfterClass
+    public static void postTestCleanup() throws Throwable {
+        clearTests();
+    }
+
+    @Override
+    protected ResourceType resourceType() {
+        return new ResourceType(AtomixConsistentTreeMap.class);
+    }
+
+    /**
+     * Tests of the functionality associated with the
+     * {@link org.onosproject.store.service.AsyncConsistentMap} interface
+     * except transactions and listeners.
+     */
+    @Test
+    public void testBasicMapOperations() throws Throwable {
+        //Throughout the test there are isEmpty queries, these are intended to
+        //make sure that the previous section has been cleaned up, they serve
+        //the secondary purpose of testing isEmpty but that is not their
+        //primary purpose.
+        AtomixConsistentTreeMap map = createResource("basicTestMap");
+        //test size
+        map.size().thenAccept(result -> assertEquals(0, (int) result)).join();
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+        //test contains key
+        allKeys.forEach(key -> map.containsKey(key).
+                thenAccept(result -> assertFalse(result)).join());
+        //test contains value
+        allValues.forEach(value -> map.containsValue(value)
+                .thenAccept(result -> assertFalse(result)).join());
+        //test get
+        allKeys.forEach(key -> map.get(key).
+                thenAccept(result -> assertNull(result)).join());
+
+        //populate and redo prior three tests
+        allKeys.forEach(key -> map.put(key, allValues
+                .get(allKeys.indexOf(key))).thenAccept(
+                result -> assertNull(result)).join());
+        //test contains key
+        allKeys.forEach(key -> map.containsKey(key).
+                thenAccept(result -> assertTrue(result)).join());
+        //test contains value
+        allValues.forEach(value -> map.containsValue(value)
+                .thenAccept(result -> assertTrue(result)).join());
+        //test get
+        allKeys.forEach(key -> map.get(key).
+                thenAccept(
+                        result -> assertArrayEquals(
+                                allValues.get(allKeys.indexOf(key)),
+                                result.value())).join());
+        //test all compute methods in this section
+        allKeys.forEach(key -> map.computeIfAbsent(
+                key, v ->allValues.get(allKeys.indexOf(key)
+                )).thenAccept(result ->
+                                assertArrayEquals(
+                                        allValues.get(allKeys.indexOf(key)),
+                                        result.value())).join());
+        map.size().thenAccept(result -> assertEquals(4, (int) result)).join();
+        map.isEmpty().thenAccept(result -> assertFalse(result)).join();
+        allKeys.forEach(key -> map.computeIfPresent(key, (k, v) -> null).
+                thenAccept(result -> assertNull(result)).join());
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+        allKeys.forEach(key -> map.compute(key, (k, v) ->
+                            allValues.get(allKeys.indexOf(key))).
+                            thenAccept(result -> assertArrayEquals(
+                                    allValues.get(allKeys.indexOf(key)),
+                                    result.value())).join());
+        map.size().thenAccept(result -> assertEquals(4, (int) result)).join();
+        map.isEmpty().thenAccept(result -> assertFalse(result)).join();
+        allKeys.forEach(key -> map.computeIf(key,
+                                         (k) -> allKeys.indexOf(key) < 2,
+                                         (k, v) -> null).thenAccept(result -> {
+            if (allKeys.indexOf(key) < 2) {
+                assertNull(result);
+            } else {
+                assertArrayEquals(allValues.get(allKeys.indexOf(key)),
+                                  result.value());
+            }
+        }).join());
+        map.size().thenAccept(result -> assertEquals(2, (int) result)).join();
+        map.isEmpty().thenAccept(result -> assertFalse(result)).join();
+        //test simple put
+        allKeys.forEach(
+                key -> map.put(key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> {
+                    if (allKeys.indexOf(key) < 2) {
+                        assertNull(result);
+                    } else {
+                        assertArrayEquals(
+                                allValues.get(allKeys.indexOf(key)),
+                                result.value());
+                    }
+                }).join());
+        map.size().thenAccept(result -> assertEquals(4, (int) result)).join();
+        map.isEmpty().thenAccept(result -> assertFalse(result)).join();
+        //test put and get for version retrieval
+        allKeys.forEach(
+                key -> map.putAndGet(key, allValues.get(allKeys.indexOf(key))).
+            thenAccept(firstResult -> {
+                map.putAndGet(key, allValues.get(allKeys.indexOf(key))).
+                    thenAccept(secondResult -> {
+                    assertArrayEquals(allValues.get(allKeys.indexOf(key)),
+                                      firstResult.value());
+                    assertArrayEquals(allValues.get(allKeys.indexOf(key)),
+                                      secondResult.value());
+                    assertTrue((firstResult.version() + 1) ==
+                                       secondResult.version());
+                });
+            }).join());
+        //test removal
+        allKeys.forEach(key -> map.remove(key).thenAccept(
+                result -> assertArrayEquals(
+                        allValues.get(allKeys.indexOf(key)), result.value()))
+                .join());
+        map.isEmpty().thenAccept(result -> assertTrue(result));
+        //repopulating, this is not mainly for testing
+        allKeys.forEach(key -> map.put(
+                key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> {
+                        assertNull(result);
+                }).join());
+
+        //Test various collections of keys, values and entries
+        map.keySet().thenAccept(
+                keys -> assertTrue(
+                        stringArrayCollectionIsEqual(keys, allKeys)))
+                .join();
+        map.values().thenAccept(
+                values -> assertTrue(
+                        byteArrayCollectionIsEqual(values.stream().map(
+                                v -> v.value()).collect(
+                                Collectors.toSet()), allValues)))
+                .join();
+        map.entrySet().thenAccept(entrySet -> {
+            entrySet.forEach(entry -> {
+                assertTrue(allKeys.contains(entry.getKey()));
+                assertTrue(Arrays.equals(entry.getValue().value(),
+                             allValues.get(allKeys.indexOf(entry.getKey()))));
+            });
+        }).join();
+        map.clear().join();
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+
+        //test conditional put
+        allKeys.forEach(
+                key -> map.putIfAbsent(
+                        key, allValues.get(allKeys.indexOf(key))).
+                        thenAccept(result -> assertNull(result)).join());
+        allKeys.forEach(
+                key -> map.putIfAbsent(
+                        key, null).
+                        thenAccept(result ->
+                                   assertArrayEquals(result.value(),
+                                        allValues.get(allKeys.indexOf(key))))
+                        .join());
+        // test alternate removes that specify value or version
+        allKeys.forEach(
+                key -> map.remove(key, spareValue).thenAccept(
+                        result -> assertFalse(result)).join());
+        allKeys.forEach(
+                key -> map.remove(key, allValues.get(allKeys.indexOf(key)))
+                        .thenAccept(result -> assertTrue(result)).join());
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+        List<Long> versions = Lists.newArrayList();
+
+        //repopulating set for version based removal
+        allKeys.forEach(
+                key -> map.putAndGet(key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> versions.add(result.version())).join());
+        allKeys.forEach(
+                key -> map.remove(key, versions.get(0)).thenAccept(
+                        result -> {
+                            assertTrue(result);
+                            versions.remove(0);
+                        }).join());
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+        //Testing all replace both simple (k, v), and complex that consider
+        // previous mapping or version.
+        allKeys.forEach(
+                key -> map.put(key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> assertNull(result)).join());
+        allKeys.forEach(key -> map.replace(
+                key, allValues.get(3 - allKeys.indexOf(key)))
+                .thenAccept(result -> assertArrayEquals(
+                        allValues.get(allKeys.indexOf(key)), result.value()))
+                .join());
+        allKeys.forEach(key -> map.replace(key,
+                                           spareValue,
+                                           allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> assertFalse(result))
+                .join());
+        allKeys.forEach(key -> map.replace(
+                key, allValues.get(3 - allKeys.indexOf(key)),
+                allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> assertTrue(result)).join());
+        map.clear().join();
+        map.isEmpty().thenAccept(result -> assertTrue(result)).join();
+        versions.clear();
+        //populate for version based replacement
+        allKeys.forEach(
+                key -> map.putAndGet(
+                        key, allValues.get(3 - allKeys.indexOf(key)))
+                        .thenAccept(result ->
+                            versions.add(result.version())).join());
+        allKeys.forEach(key -> map.replace(
+                key, 0, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> assertFalse(result))
+                .join());
+        allKeys.forEach(key -> map.replace(
+                key, versions.get(0), allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> {
+                    assertTrue(result);
+                    versions.remove(0);
+                }).join());
+    }
+
+    @Test
+    public void mapListenerTests() throws Throwable {
+        final byte[] value1 = Tools.getBytesUtf8("value1");
+        final byte[] value2 = Tools.getBytesUtf8("value2");
+        final byte[] value3 = Tools.getBytesUtf8("value3");
+
+        AtomixConsistentTreeMap map = createResource("treeMapListenerTestMap");
+        TestMapEventListener listener = new TestMapEventListener();
+
+        // add listener; insert new value into map and verify an INSERT event
+        // is received.
+        map.addListener(listener).thenCompose(v -> map.put("foo", value1))
+                .join();
+        MapEvent<String, byte[]> event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.INSERT, event.type());
+        assertTrue(Arrays.equals(value1, event.newValue().value()));
+
+        // remove listener and verify listener is not notified.
+        map.removeListener(listener).thenCompose(v -> map.put("foo", value2))
+                .join();
+        assertFalse(listener.eventReceived());
+
+        // add the listener back and verify UPDATE events are received
+        // correctly
+        map.addListener(listener).thenCompose(v -> map.put("foo", value3))
+                .join();
+        event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.UPDATE, event.type());
+        assertTrue(Arrays.equals(value3, event.newValue().value()));
+
+        // perform a non-state changing operation and verify no events are
+        // received.
+        map.putIfAbsent("foo", value1).join();
+        assertFalse(listener.eventReceived());
+
+        // verify REMOVE events are received correctly.
+        map.remove("foo").join();
+        event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.REMOVE, event.type());
+        assertTrue(Arrays.equals(value3, event.oldValue().value()));
+
+        // verify compute methods also generate events.
+        map.computeIf("foo", v -> v == null, (k, v) -> value1).join();
+        event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.INSERT, event.type());
+        assertTrue(Arrays.equals(value1, event.newValue().value()));
+
+        map.compute("foo", (k, v) -> value2).join();
+        event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.UPDATE, event.type());
+        assertTrue(Arrays.equals(value2, event.newValue().value()));
+
+        map.computeIf(
+                "foo", v -> Arrays.equals(v, value2), (k, v) -> null).join();
+        event = listener.event();
+        assertNotNull(event);
+        assertEquals(MapEvent.Type.REMOVE, event.type());
+        assertTrue(Arrays.equals(value2, event.oldValue().value()));
+
+        map.removeListener(listener).join();
+    }
+
+    /**
+     * Tests functionality specified in the {@link AtomixConsistentTreeMap}
+     * interface, beyond the functionality provided in
+     * {@link org.onosproject.store.service.AsyncConsistentMap}.
+     */
+    @Test
+    public void treeMapFunctionsTest() {
+        AtomixConsistentTreeMap map = createResource("treeMapFunctionTestMap");
+        //Tests on empty map
+        map.firstKey().thenAccept(result -> assertNull(result)).join();
+        map.lastKey().thenAccept(result -> assertNull(result)).join();
+        map.ceilingEntry(keyOne).thenAccept(result -> assertNull(result))
+                .join();
+        map.floorEntry(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.higherEntry(keyOne).thenAccept(result -> assertNull(result))
+                .join();
+        map.lowerEntry(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.firstEntry().thenAccept(result -> assertNull(result)).join();
+        map.lastEntry().thenAccept(result -> assertNull(result)).join();
+        map.pollFirstEntry().thenAccept(result -> assertNull(result)).join();
+        map.pollLastEntry().thenAccept(result -> assertNull(result)).join();
+        map.lowerKey(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.floorKey(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.ceilingKey(keyOne).thenAccept(result -> assertNull(result))
+                .join();
+        map.higherKey(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.delete().join();
+
+        allKeys.forEach(key -> map.put(
+                key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> assertNull(result)).join());
+        //Note ordering keys are in their proper ordering in ascending order
+        //both in naming and in the allKeys list.
+
+        map.firstKey().thenAccept(result -> assertEquals(keyOne, result))
+                .join();
+        map.lastKey().thenAccept(result -> assertEquals(keyFour, result))
+                .join();
+        map.ceilingEntry(keyOne)
+                .thenAccept(result -> {
+                    assertEquals(keyOne, result.getKey());
+                    assertArrayEquals(valueOne, result.getValue().value());
+                })
+                .join();
+        //adding an additional letter to make keyOne an unacceptable response
+        map.ceilingEntry(keyOne + "a")
+                .thenAccept(result -> {
+                    assertEquals(keyTwo, result.getKey());
+                    assertArrayEquals(valueTwo, result.getValue().value());
+                })
+                .join();
+        map.ceilingEntry(keyFour + "a")
+                .thenAccept(result -> {
+                    assertNull(result);
+                })
+                .join();
+        map.floorEntry(keyTwo).thenAccept(result -> {
+            assertEquals(keyTwo, result.getKey());
+            assertArrayEquals(valueTwo, result.getValue().value());
+        })
+                .join();
+        //shorten the key so it itself is not an acceptable reply
+        map.floorEntry(keyTwo.substring(0, 2)).thenAccept(result -> {
+            assertEquals(keyOne, result.getKey());
+            assertArrayEquals(valueOne, result.getValue().value());
+        })
+                .join();
+        // shorten least key so no acceptable response exists
+        map.floorEntry(keyOne.substring(0, 1)).thenAccept(
+                result -> assertNull(result))
+                .join();
+
+        map.higherEntry(keyTwo).thenAccept(result -> {
+            assertEquals(keyThree, result.getKey());
+            assertArrayEquals(valueThree, result.getValue().value());
+        })
+                .join();
+        map.higherEntry(keyFour).thenAccept(result -> assertNull(result))
+                .join();
+
+        map.lowerEntry(keyFour).thenAccept(result -> {
+            assertEquals(keyThree, result.getKey());
+            assertArrayEquals(valueThree, result.getValue().value());
+        })
+                .join();
+        map.lowerEntry(keyOne).thenAccept(result -> assertNull(result))
+                .join();
+        map.firstEntry().thenAccept(result -> {
+            assertEquals(keyOne, result.getKey());
+            assertArrayEquals(valueOne, result.getValue().value());
+        })
+                .join();
+        map.lastEntry().thenAccept(result -> {
+            assertEquals(keyFour, result.getKey());
+            assertArrayEquals(valueFour, result.getValue().value());
+        })
+                .join();
+        map.pollFirstEntry().thenAccept(result -> {
+            assertEquals(keyOne, result.getKey());
+            assertArrayEquals(valueOne, result.getValue().value());
+        });
+        map.containsKey(keyOne).thenAccept(result -> assertFalse(result))
+                .join();
+        map.size().thenAccept(result -> assertEquals(3, (int) result)).join();
+        map.pollLastEntry().thenAccept(result -> {
+            assertEquals(keyFour, result.getKey());
+            assertArrayEquals(valueFour, result.getValue().value());
+        });
+        map.containsKey(keyFour).thenAccept(result -> assertFalse(result))
+                .join();
+        map.size().thenAccept(result -> assertEquals(2, (int) result)).join();
+
+        //repopulate the missing entries
+        allKeys.forEach(key -> map.put(
+                key, allValues.get(allKeys.indexOf(key)))
+                .thenAccept(result -> {
+                    if (key.equals(keyOne) || key.equals(keyFour)) {
+                        assertNull(result);
+                    } else {
+                        assertArrayEquals(allValues.get(allKeys.indexOf(key)),
+                                          result.value());
+                    }
+                })
+                .join());
+        map.lowerKey(keyOne).thenAccept(result -> assertNull(result)).join();
+        map.lowerKey(keyThree).thenAccept(
+                result -> assertEquals(keyTwo, result))
+                .join();
+        map.floorKey(keyThree).thenAccept(
+                result -> assertEquals(keyThree, result))
+                .join();
+        //shortening the key so there is no acceptable response
+        map.floorKey(keyOne.substring(0, 1)).thenAccept(
+                result -> assertNull(result))
+                .join();
+        map.ceilingKey(keyTwo).thenAccept(
+                result -> assertEquals(keyTwo, result))
+                .join();
+        //adding to highest key so there is no acceptable response
+        map.ceilingKey(keyFour + "a")
+                .thenAccept(reslt -> assertNull(reslt))
+                .join();
+        map.higherKey(keyThree).thenAccept(
+                result -> assertEquals(keyFour, result))
+                .join();
+        map.higherKey(keyFour).thenAccept(
+                result -> assertNull(result))
+                .join();
+        map.delete().join();
+
+    }
+
+    private AtomixConsistentTreeMap createResource(String mapName) {
+        try {
+            AtomixConsistentTreeMap map = createAtomixClient().
+                    getResource(mapName, AtomixConsistentTreeMap.class)
+                    .join();
+            return map;
+        } catch (Throwable e) {
+            throw new RuntimeException(e.toString());
+        }
+    }
+    private static class TestMapEventListener
+            implements MapEventListener<String, byte[]> {
+
+        private final BlockingQueue<MapEvent<String, byte[]>> queue =
+                new ArrayBlockingQueue<>(1);
+
+        @Override
+        public void event(MapEvent<String, byte[]> event) {
+            try {
+                queue.put(event);
+            } catch (InterruptedException e) {
+                Throwables.propagate(e);
+            }
+        }
+
+        public boolean eventReceived() {
+            return !queue.isEmpty();
+        }
+
+        public MapEvent<String, byte[]> event() throws InterruptedException {
+            return queue.take();
+        }
+    }
+
+    /**
+     * Returns two arrays contain the same set of elements,
+     * regardless of order.
+     * @param o1 first collection
+     * @param o2 second collection
+     * @return true if they contain the same elements
+     */
+    private boolean byteArrayCollectionIsEqual(
+            Collection<? extends byte[]> o1, Collection<? extends byte[]> o2) {
+        if (o1 == null || o2 == null || o1.size() != o2.size()) {
+            return false;
+        }
+        for (byte[] array1 : o1) {
+            boolean matched = false;
+            for (byte[] array2 : o2) {
+                if (Arrays.equals(array1, array2)) {
+                    matched = true;
+                    break;
+                }
+            }
+            if (!matched) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Compares two collections of strings returns true if they contain the
+     * same strings, false otherwise.
+     * @param s1 string collection one
+     * @param s2 string collection two
+     * @return true if the two sets contain the same strings
+     */
+    private boolean stringArrayCollectionIsEqual(
+            Collection<? extends String> s1, Collection<? extends String> s2) {
+        if (s1 == null || s2 == null || s1.size() != s2.size()) {
+            return false;
+        }
+        for (String string1 : s1) {
+            boolean matched = false;
+            for (String string2 : s2) {
+                if (string1.equals(string2)) {
+                    matched = true;
+                    break;
+                }
+            }
+            if (!matched) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Inner entry type for testing.
+     * @param <K>
+     * @param <V>
+     */
+    private class InnerEntry<K, V> implements Map.Entry<K, V> {
+        private K key;
+        private V value;
+        public InnerEntry(K key, V value) {
+            this.key = key;
+            this.value = value;
+        }
+
+        @Override
+        public K getKey() {
+            return key;
+        }
+
+        @Override
+        public V getValue() {
+            return value;
+        }
+
+        @Override
+        public V setValue(V value) {
+            V temp = this.value;
+            this.value = value;
+            return temp;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (!(o instanceof InnerEntry)) {
+                return false;
+            }
+            InnerEntry other = (InnerEntry) o;
+            boolean keysEqual = false;
+            boolean valuesEqual = false;
+            if (this.key instanceof byte[]) {
+                if (other.getKey() instanceof byte[]) {
+                    keysEqual =  Arrays.equals((byte[]) this.key,
+                                               (byte[]) other.getKey());
+                } else {
+                    return false;
+                }
+            } else {
+                keysEqual = this.getKey().equals(other.getKey());
+            }
+
+            if (keysEqual) {
+                if (this.value instanceof byte[]) {
+                    if (other.getValue() instanceof byte[]) {
+                        return Arrays.equals((byte[]) this.value,
+                                             (byte[]) other.getValue());
+                    } else {
+                        return false;
+                    }
+                } else {
+                    return this.key.equals(other.getKey());
+                }
+            }
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return 0;
+        }
+    }
+}
\ No newline at end of file