Enhance StatisticService to allow filtering by Application ID and Group ID

Resolve ONOS-205

Change-Id: Ie9318a5ade943bd8e47fb92ee856b7ebead5022e
diff --git a/core/net/src/main/java/org/onlab/onos/net/statistic/impl/StatisticManager.java b/core/net/src/main/java/org/onlab/onos/net/statistic/impl/StatisticManager.java
index 3bff3c5..fd4b741 100644
--- a/core/net/src/main/java/org/onlab/onos/net/statistic/impl/StatisticManager.java
+++ b/core/net/src/main/java/org/onlab/onos/net/statistic/impl/StatisticManager.java
@@ -15,12 +15,18 @@
  */
 package org.onlab.onos.net.statistic.impl;
 
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.Service;
+import org.onlab.onos.core.ApplicationId;
+import org.onlab.onos.core.GroupId;
 import org.onlab.onos.net.ConnectPoint;
 import org.onlab.onos.net.Link;
 import org.onlab.onos.net.Path;
@@ -35,8 +41,13 @@
 import org.onlab.onos.net.statistic.StatisticService;
 import org.onlab.onos.net.statistic.StatisticStore;
 import org.slf4j.Logger;
+
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
 
+import static com.google.common.base.Preconditions.checkNotNull;
 import static org.slf4j.LoggerFactory.getLogger;
 
 /**
@@ -76,6 +87,25 @@
     }
 
     @Override
+    public Load load(Link link, ApplicationId appId, Optional<GroupId> groupId) {
+        Statistics stats = getStatistics(link.src());
+        if (!stats.isValid()) {
+            return new DefaultLoad();
+        }
+
+        ImmutableSet<FlowEntry> current = FluentIterable.from(stats.current())
+                .filter(hasApplicationId(appId))
+                .filter(hasGroupId(groupId))
+                .toSet();
+        ImmutableSet<FlowEntry> previous = FluentIterable.from(stats.previous())
+                .filter(hasApplicationId(appId))
+                .filter(hasGroupId(groupId))
+                .toSet();
+
+        return new DefaultLoad(aggregate(current), aggregate(previous));
+    }
+
+    @Override
     public Load load(ConnectPoint connectPoint) {
         return loadInternal(connectPoint);
     }
@@ -131,22 +161,64 @@
     }
 
     private Load loadInternal(ConnectPoint connectPoint) {
+        Statistics stats = getStatistics(connectPoint);
+        if (!stats.isValid()) {
+            return new DefaultLoad();
+        }
+
+        return new DefaultLoad(aggregate(stats.current), aggregate(stats.previous));
+    }
+
+    /**
+     * Returns statistics of the specified port.
+     *
+     * @param connectPoint port to query
+     * @return statistics
+     */
+    private Statistics getStatistics(ConnectPoint connectPoint) {
         Set<FlowEntry> current;
         Set<FlowEntry> previous;
         synchronized (statisticStore) {
-            current = statisticStore.getCurrentStatistic(connectPoint);
-            previous = statisticStore.getPreviousStatistic(connectPoint);
+            current = getCurrentStatistic(connectPoint);
+            previous = getPreviousStatistic(connectPoint);
         }
-        if (current == null || previous == null) {
-            return new DefaultLoad();
-        }
-        long currentAggregate = aggregate(current);
-        long previousAggregate = aggregate(previous);
 
-        return new DefaultLoad(currentAggregate, previousAggregate);
+        return new Statistics(current, previous);
     }
 
     /**
+     * Returns the current statistic of the specified port.
+
+     * @param connectPoint port to query
+     * @return set of flow entries
+     */
+    private Set<FlowEntry> getCurrentStatistic(ConnectPoint connectPoint) {
+        Set<FlowEntry> stats = statisticStore.getCurrentStatistic(connectPoint);
+        if (stats == null) {
+            return Collections.emptySet();
+        } else {
+            return stats;
+        }
+    }
+
+    /**
+     * Returns the previous statistic of the specified port.
+     *
+     * @param connectPoint port to query
+     * @return set of flow entries
+     */
+    private Set<FlowEntry> getPreviousStatistic(ConnectPoint connectPoint) {
+        Set<FlowEntry> stats = statisticStore.getCurrentStatistic(connectPoint);
+        if (stats == null) {
+            return Collections.emptySet();
+        } else {
+            return stats;
+        }
+    }
+
+    // TODO: make aggregation function generic by passing a function
+    // (applying Java 8 Stream API?)
+    /**
      * Aggregates a set of values.
      * @param values the values to aggregate
      * @return a long value
@@ -188,5 +260,105 @@
         }
     }
 
+    /**
+     * Internal data class holding two set of flow entries.
+     */
+    private static class Statistics {
+        private final ImmutableSet<FlowEntry> current;
+        private final ImmutableSet<FlowEntry> previous;
 
+        public Statistics(Set<FlowEntry> current, Set<FlowEntry> previous) {
+            this.current = ImmutableSet.copyOf(checkNotNull(current));
+            this.previous = ImmutableSet.copyOf(checkNotNull(previous));
+        }
+
+        /**
+         * Returns flow entries as the current value.
+         *
+         * @return flow entries as the current value
+         */
+        public ImmutableSet<FlowEntry> current() {
+            return current;
+        }
+
+        /**
+         * Returns flow entries as the previous value.
+         *
+         * @return flow entries as the previous value
+         */
+        public ImmutableSet<FlowEntry> previous() {
+            return previous;
+        }
+
+        /**
+         * Validates values are not empty.
+         *
+         * @return false if either of the sets is empty. Otherwise, true.
+         */
+        public boolean isValid() {
+            return !(current.isEmpty() || previous.isEmpty());
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(current, previous);
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof Statistics)) {
+                return false;
+            }
+            final Statistics other = (Statistics) obj;
+            return Objects.equals(this.current, other.current) && Objects.equals(this.previous, other.previous);
+        }
+
+        @Override
+        public String toString() {
+            return MoreObjects.toStringHelper(this)
+                    .add("current", current)
+                    .add("previous", previous)
+                    .toString();
+        }
+    }
+
+    /**
+     * Creates a predicate that checks the application ID of a flow entry is the same as
+     * the specified application ID.
+     *
+     * @param appId application ID to be checked
+     * @return predicate
+     */
+    private static Predicate<FlowEntry> hasApplicationId(ApplicationId appId) {
+        return new Predicate<FlowEntry>() {
+            @Override
+            public boolean apply(FlowEntry flowEntry) {
+                return flowEntry.appId() == appId.id();
+            }
+        };
+    }
+
+    /**
+     * Create a predicate that checks the group ID of a flow entry is the same as
+     * the specified group ID.
+     *
+     * @param groupId group ID to be checked
+     * @return predicate
+     */
+    private static Predicate<FlowEntry> hasGroupId(Optional<GroupId> groupId) {
+        return new Predicate<FlowEntry>() {
+            @Override
+            public boolean apply(FlowEntry flowEntry) {
+                if (!groupId.isPresent()) {
+                    return false;
+                }
+                // FIXME: The left hand type and right hand type don't match
+                // FlowEntry.groupId() still returns a short value, not int.
+                return flowEntry.groupId() == groupId.get().id();
+            }
+        };
+    }
 }