bda6493cb04978f2eafc178ff27d15b27821871e
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / AbstractClusterMatcher.java
1 package edu.uci.iotproject.detection;
2
3 import org.pcap4j.core.PcapPacket;
4
5 import java.util.List;
6 import java.util.Objects;
7
8 /**
9  * Base class for classes that search a traffic trace for sequences of packets that "belong to" a given cluster (in
10  * other words, classes that attempt to classify traffic as pertaining to a given cluster).
11  *
12  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
13  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
14  */
15 abstract public class AbstractClusterMatcher {
16
17     /**
18      * The cluster that describes the sequence of packets that this {@link AbstractClusterMatcher} is trying to detect
19      * in the observed traffic.
20      */
21     protected final List<List<PcapPacket>> mCluster;
22
23     protected AbstractClusterMatcher(List<List<PcapPacket>> cluster) {
24         // ===================== PRECONDITION SECTION =====================
25         cluster = Objects.requireNonNull(cluster, "cluster cannot be null");
26         if (cluster.isEmpty() || cluster.stream().anyMatch(inner -> inner.isEmpty())) {
27             throw new IllegalArgumentException("cluster is empty (or contains an empty inner List)");
28         }
29         for (List<PcapPacket> clusterMember : cluster) {
30             if (clusterMember.size() != cluster.get(0).size()) {
31                 throw new IllegalArgumentException("All sequences in cluster must contain the same number of packets");
32             }
33         }
34         // ================================================================
35         // Let the subclass prune the provided cluster
36         mCluster = pruneCluster(cluster);
37     }
38
39     /**
40      * Allows subclasses to specify how to prune the input cluster provided to the constructor.
41      * @param cluster The input cluster provided to the constructor.
42      * @return The pruned cluster to use in place of the input cluster.
43      */
44     abstract protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster);
45
46     // TODO: move Direction outside Conversation so that this is less confusing.
47 //    abstract protected Conversation.Direction[] getPacketDirections(List<PcapPacket> packets);
48
49 }