Refactored primitive builders to consolidate methods into the base DistributedPrimitiveBuilder

Change-Id: I9a24117b41d1feeb5cf460c6adfa484aabcbb8c1
diff --git a/core/store/dist/src/main/java/org/onosproject/store/device/impl/ECDeviceStore.java b/core/store/dist/src/main/java/org/onosproject/store/device/impl/ECDeviceStore.java
index 129fbbe..e1e1d2e 100644
--- a/core/store/dist/src/main/java/org/onosproject/store/device/impl/ECDeviceStore.java
+++ b/core/store/dist/src/main/java/org/onosproject/store/device/impl/ECDeviceStore.java
@@ -237,7 +237,8 @@
                 .withSerializer(Serializer.using(KryoNamespaces.API))
                 .withPartitionsDisabled()
                 .withRelaxedReadConsistency()
-                .build();
+                .build()
+                .asDistributedSet();
 
         deviceDescriptions.addListener(deviceUpdateListener);
         portDescriptions.addListener(portUpdateListener);
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultConsistentMapBuilder.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultConsistentMapBuilder.java
index 6f3fadd..5a81ca6 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultConsistentMapBuilder.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultConsistentMapBuilder.java
@@ -15,13 +15,10 @@
  */
 package org.onosproject.store.primitives.impl;
 
-import org.onosproject.core.ApplicationId;
 import org.onosproject.store.service.AsyncConsistentMap;
 import org.onosproject.store.service.ConsistentMap;
 import org.onosproject.store.service.ConsistentMapBuilder;
-import org.onosproject.store.service.Serializer;
 
-import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
 
 /**
@@ -30,85 +27,25 @@
  * @param <K> type for map key
  * @param <V> type for map value
  */
-public class DefaultConsistentMapBuilder<K, V> implements ConsistentMapBuilder<K, V> {
+public class DefaultConsistentMapBuilder<K, V> extends ConsistentMapBuilder<K, V> {
 
-    private Serializer serializer;
-    private String name;
-    private ApplicationId applicationId;
-    private boolean purgeOnUninstall = false;
-    private boolean partitionsEnabled = true;
-    private boolean readOnly = false;
-    private boolean metering = true;
-    private boolean relaxedReadConsistency = false;
     private final DatabaseManager manager;
-    private static final long DEFAULT_OPERATION_TIMEOUT_MILLIS = 5000L;
 
     public DefaultConsistentMapBuilder(DatabaseManager manager) {
         this.manager = manager;
     }
 
-    @Override
-    public ConsistentMapBuilder<K, V> withName(String name) {
-        checkArgument(name != null && !name.isEmpty());
-        this.name = name;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withApplicationId(ApplicationId id) {
-        checkArgument(id != null);
-        this.applicationId = id;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withPurgeOnUninstall() {
-        purgeOnUninstall = true;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withMeteringDisabled() {
-        metering = false;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withSerializer(Serializer serializer) {
-        checkArgument(serializer != null);
-        this.serializer = serializer;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withPartitionsDisabled() {
-        partitionsEnabled = false;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withUpdatesDisabled() {
-        readOnly = true;
-        return this;
-    }
-
-    @Override
-    public ConsistentMapBuilder<K, V> withRelaxedReadConsistency() {
-        relaxedReadConsistency = true;
-        return this;
-    }
-
     private void validateInputs() {
-        checkState(name != null, "name must be specified");
-        checkState(serializer != null, "serializer must be specified");
-        if (purgeOnUninstall) {
-            checkState(applicationId != null, "ApplicationId must be specified when purgeOnUninstall is enabled");
+        checkState(name() != null, "name must be specified");
+        checkState(serializer() != null, "serializer must be specified");
+        if (purgeOnUninstall()) {
+            checkState(applicationId() != null, "ApplicationId must be specified when purgeOnUninstall is enabled");
         }
     }
 
     @Override
     public ConsistentMap<K, V> build() {
-        return buildAndRegisterMap().asConsistentMap(DEFAULT_OPERATION_TIMEOUT_MILLIS);
+        return buildAndRegisterMap().asConsistentMap();
     }
 
     @Override
@@ -118,25 +55,25 @@
 
     private DefaultAsyncConsistentMap<K, V> buildAndRegisterMap() {
         validateInputs();
-        Database database = partitionsEnabled ? manager.partitionedDatabase : manager.inMemoryDatabase;
-        if (relaxedReadConsistency) {
+        Database database = partitionsDisabled() ? manager.inMemoryDatabase : manager.partitionedDatabase;
+        if (relaxedReadConsistency()) {
             return manager.registerMap(
-                    new AsyncCachingConsistentMap<>(name,
-                        applicationId,
+                    new AsyncCachingConsistentMap<>(name(),
+                        applicationId(),
                         database,
-                        serializer,
-                        readOnly,
-                        purgeOnUninstall,
-                        metering));
+                        serializer(),
+                        readOnly(),
+                        purgeOnUninstall(),
+                        meteringEnabled()));
         } else {
             return manager.registerMap(
-                    new DefaultAsyncConsistentMap<>(name,
-                        applicationId,
+                    new DefaultAsyncConsistentMap<>(name(),
+                        applicationId(),
                         database,
-                        serializer,
-                        readOnly,
-                        purgeOnUninstall,
-                        metering));
+                        serializer(),
+                        readOnly(),
+                        purgeOnUninstall(),
+                        meteringEnabled()));
         }
     }
 }
\ No newline at end of file
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSet.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSet.java
deleted file mode 100644
index 01a341d..0000000
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSet.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2015 Open Networking Laboratory
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.onosproject.store.primitives.impl;
-
-import java.lang.reflect.Array;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.onosproject.store.service.AsyncDistributedSet;
-import org.onosproject.store.service.DistributedSet;
-import org.onosproject.store.service.SetEventListener;
-import org.onosproject.store.service.StorageException;
-import org.onosproject.store.service.Synchronous;
-
-/**
- * Implementation of {@link DistributedSet} that merely delegates to a {@link AsyncDistributedSet}
- * and waits for the operation to complete.
-
- * @param <E> set element type
- */
-public class DefaultDistributedSet<E> extends Synchronous<AsyncDistributedSet<E>> implements DistributedSet<E> {
-
-    private static final long OPERATION_TIMEOUT_MILLIS = 5000;
-
-    private final AsyncDistributedSet<E> asyncSet;
-
-    public DefaultDistributedSet(AsyncDistributedSet<E> asyncSet) {
-        super(asyncSet);
-        this.asyncSet = asyncSet;
-    }
-
-    private static <T> T complete(CompletableFuture<T> future) {
-        try {
-            return future.get(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new StorageException.Interrupted();
-        } catch (TimeoutException e) {
-            throw new StorageException.Timeout();
-        } catch (ExecutionException e) {
-            if (e.getCause() instanceof StorageException) {
-                throw (StorageException) e.getCause();
-            } else {
-                throw new StorageException(e.getCause());
-            }
-        }
-    }
-
-    @Override
-    public int size() {
-        return complete(asyncSet.size());
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return complete(asyncSet.isEmpty());
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean contains(Object o) {
-        return complete(asyncSet.contains((E) o));
-    }
-
-    @Override
-    public Iterator<E> iterator() {
-        return complete(asyncSet.getAsImmutableSet()).iterator();
-    }
-
-    @Override
-    public Object[] toArray() {
-        return complete(asyncSet.getAsImmutableSet()).stream().toArray();
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public <T> T[] toArray(T[] a) {
-        // TODO: Optimize this to only allocate a new array if the set size
-        // is larger than the array.length. If the set size is smaller than
-        // the array.length then copy the data into the array and set the
-        // last element in the array to be null.
-        final T[] resizedArray =
-                (T[]) Array.newInstance(a.getClass().getComponentType(), complete(asyncSet.getAsImmutableSet()).size());
-        return complete(asyncSet.getAsImmutableSet()).toArray(resizedArray);
-    }
-
-    @Override
-    public boolean add(E e) {
-        return complete(asyncSet.add(e));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean remove(Object o) {
-        return complete(asyncSet.remove((E) o));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean containsAll(Collection<?> c) {
-        return complete(asyncSet.containsAll((Collection<? extends E>) c));
-    }
-
-    @Override
-    public boolean addAll(Collection<? extends E> c) {
-        return complete(asyncSet.addAll(c));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean retainAll(Collection<?> c) {
-        return complete(asyncSet.retainAll((Collection<? extends E>) c));
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean removeAll(Collection<?> c) {
-        return complete(asyncSet.removeAll((Collection<? extends E>) c));
-    }
-
-    @Override
-    public void clear() {
-        complete(asyncSet.clear());
-    }
-
-    @Override
-    public void addListener(SetEventListener<E> listener) {
-        complete(asyncSet.addListener(listener));
-    }
-
-    @Override
-    public void removeListener(SetEventListener<E> listener) {
-        complete(asyncSet.removeListener(listener));
-    }
-}
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSetBuilder.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSetBuilder.java
index 6621b4c..8c3e5f3 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSetBuilder.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedSetBuilder.java
@@ -20,7 +20,6 @@
 import org.onosproject.core.ApplicationId;
 import org.onosproject.store.service.AsyncDistributedSet;
 import org.onosproject.store.service.ConsistentMapBuilder;
-import org.onosproject.store.service.DistributedSet;
 import org.onosproject.store.service.Serializer;
 import org.onosproject.store.service.DistributedSetBuilder;
 
@@ -29,7 +28,7 @@
  *
  * @param <E> type for set elements
  */
-public class DefaultDistributedSetBuilder<E> implements DistributedSetBuilder<E> {
+public class DefaultDistributedSetBuilder<E> extends DistributedSetBuilder<E> {
 
     private String name;
     private ConsistentMapBuilder<E, Boolean>  mapBuilder;
@@ -90,12 +89,7 @@
     }
 
     @Override
-    public DistributedSet<E> build() {
-        return new DefaultDistributedSet<E>(buildAsyncSet());
-    }
-
-    @Override
-    public AsyncDistributedSet<E> buildAsyncSet() {
+    public AsyncDistributedSet<E> build() {
         return new DefaultAsyncDistributedSet<E>(mapBuilder.buildAsyncMap(), name, metering);
     }
 }
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContext.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContext.java
index b71902b..43cacb3 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContext.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContext.java
@@ -82,14 +82,16 @@
         checkState(isOpen, TX_NOT_OPEN_ERROR);
         checkNotNull(mapName);
         checkNotNull(serializer);
-        return txMaps.computeIfAbsent(mapName, name -> new DefaultTransactionalMap<>(
+        return txMaps.computeIfAbsent(mapName, name -> {
+            ConsistentMapBuilder mapBuilder =  (ConsistentMapBuilder) mapBuilderSupplier.get()
+                                                                                        .withName(name)
+                                                                                        .withSerializer(serializer);
+            return new DefaultTransactionalMap<>(
                                 name,
-                                mapBuilderSupplier.get()
-                                                  .withName(name)
-                                                  .withSerializer(serializer)
-                                                  .buildAsyncMap(),
+                                mapBuilder.buildAsyncMap(),
                                 this,
-                                serializer));
+                                serializer);
+        });
     }
 
     @SuppressWarnings("unchecked")
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContextBuilder.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContextBuilder.java
index 99d62ca..91f4bf6 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContextBuilder.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultTransactionContextBuilder.java
@@ -48,7 +48,7 @@
         return new DefaultTransactionContext(transactionId, transactionCommitter, () -> {
             ConsistentMapBuilder mapBuilder = mapBuilderSupplier.get();
             if (partitionsDisabled()) {
-                mapBuilder = mapBuilder.withPartitionsDisabled();
+                mapBuilder = (ConsistentMapBuilder) mapBuilder.withPartitionsDisabled();
             }
             return mapBuilder;
         });