Merge branch 'master' of https://github.uci.edu/rtrimana/smart_home_traffic
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / comparison / ComparisonFunctions.java
1 package edu.uci.iotproject.comparison;
2
3 import edu.uci.iotproject.Conversation;
4 import edu.uci.iotproject.FlowPattern;
5 import org.pcap4j.core.PcapPacket;
6 import org.pcap4j.packet.TcpPacket;
7
8 import java.util.List;
9 import java.util.function.BiFunction;
10
11 /**
12  * Contains concrete implementations of comparison functions that compare a {@link Conversation} and a {@link FlowPattern}.
13  * These functions are supplied to {@link PatternComparisonTask} which in turn facilitates comparison on a background thread.
14  * This design provides plugability: currently, we only support complete match comparison, but further down the road we
15  * can simply introduce more sophisticated comparison functions here (e.g. Least Common Substring) simply replace the
16  * argument passed to the {@link PatternComparisonTask} constructor to switch between the different implementations.
17  *
18  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
19  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
20  */
21 public class ComparisonFunctions {
22
23     /**
24      * Comparison function that checks for a <em>complete</em> match, i.e. a match in which every packet in the
25      * {@link Conversation} has the same length as the corresponding packet in the {@link FlowPattern}.
26      */
27     public static final BiFunction<Conversation, FlowPattern, CompleteMatchPatternComparisonResult> COMPLETE_MATCH = (conversation, flowPattern) -> {
28         List<PcapPacket> convPackets = conversation.getPackets();
29         if (convPackets.size() != flowPattern.getLength()) {
30             return new CompleteMatchPatternComparisonResult(conversation, flowPattern, false);
31         }
32         for (int i = 0; i < convPackets.size(); i++) {
33             TcpPacket tcpPacket = convPackets.get(i).get(TcpPacket.class);
34             if (tcpPacket.getPayload().length() != flowPattern.getPacketOrder().get(i)) {
35                 return new CompleteMatchPatternComparisonResult(conversation, flowPattern, false);
36             }
37         }
38         return new CompleteMatchPatternComparisonResult(conversation, flowPattern, true);
39     };
40
41 }