Add utility for analyzing the success of a detection run
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / analysis / UserAction.java
index 807ea788cbd623bd6e662b1255b9d0a11f204331..408d66a3fbdfdb09c8021d4f66dbcabb5eaf6bbf 100644 (file)
@@ -1,6 +1,8 @@
 package edu.uci.iotproject.analysis;
 
 import java.time.Instant;
 package edu.uci.iotproject.analysis;
 
 import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
 
 /**
  * Models a user's action, such as toggling the smart plug on/off at a given time.
 
 /**
  * Models a user's action, such as toggling the smart plug on/off at a given time.
@@ -9,6 +11,35 @@ import java.time.Instant;
  */
 public class UserAction {
 
  */
 public class UserAction {
 
+    private static volatile DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ISO_ZONED_DATE_TIME.
+            withZone(ZoneId.of("America/Los_Angeles"));
+
+    /**
+     * Sets the {@link DateTimeFormatter} used when outputting a user action as a string and parsing a user action from
+     * a string.
+     * @param formatter The formatter to use for outputting and parsing.
+     */
+    public static void setTimestampFormatter(DateTimeFormatter formatter) {
+        TIMESTAMP_FORMATTER = formatter;
+    }
+
+    /**
+     * Instantiates a {@code UserAction} from a string that obeys the format used in {@link UserAction#toString()}.
+     * @param string The string that represents a {@code UserAction}
+     * @return A {@code UserAction} resulting from deserializing the string.
+     */
+    public static UserAction fromString(String string) {
+        String[] parts = string.split("@");
+        if (parts.length != 2) {
+            throw new IllegalArgumentException("Invalid string format");
+        }
+        // If any of these two parses fail, an exception is thrown -- no need to check return values.
+        UserAction.Type actionType = UserAction.Type.valueOf(parts[0].trim());
+        Instant timestamp = TIMESTAMP_FORMATTER.parse(parts[1].trim(), Instant::from);
+        return new UserAction(actionType, timestamp);
+    }
+
+
     /**
      * The specific type of action the user performed.
      */
     /**
      * The specific type of action the user performed.
      */
@@ -72,6 +103,6 @@ public class UserAction {
 
     @Override
     public String toString() {
 
     @Override
     public String toString() {
-       return String.format("[ %s @ %s ]", mType.name(), mTimestamp.toString());
+       return String.format("%s @ %s", mType.name(), TIMESTAMP_FORMATTER.format(mTimestamp));
     }
 }
     }
 }