X-Git-Url: http://plrg.eecs.uci.edu/git/?p=pingpong.git;a=blobdiff_plain;f=Code%2FProjects%2FSmartPlugDetector%2Fsrc%2Fmain%2Fjava%2Fedu%2Fuci%2Fiotproject%2Fanalysis%2FUserAction.java;fp=Code%2FProjects%2FSmartPlugDetector%2Fsrc%2Fmain%2Fjava%2Fedu%2Fuci%2Fiotproject%2Fanalysis%2FUserAction.java;h=408d66a3fbdfdb09c8021d4f66dbcabb5eaf6bbf;hp=807ea788cbd623bd6e662b1255b9d0a11f204331;hb=884d5e68edad0b94de1406ea6f4993606c066bff;hpb=4f918f195bbf5cd5211e15ed88c2a7a4094f6b6e diff --git a/Code/Projects/SmartPlugDetector/src/main/java/edu/uci/iotproject/analysis/UserAction.java b/Code/Projects/SmartPlugDetector/src/main/java/edu/uci/iotproject/analysis/UserAction.java index 807ea78..408d66a 100644 --- a/Code/Projects/SmartPlugDetector/src/main/java/edu/uci/iotproject/analysis/UserAction.java +++ b/Code/Projects/SmartPlugDetector/src/main/java/edu/uci/iotproject/analysis/UserAction.java @@ -1,6 +1,8 @@ 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. @@ -9,6 +11,35 @@ import java.time.Instant; */ 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. */ @@ -72,6 +103,6 @@ public class UserAction { @Override public String toString() { - return String.format("[ %s @ %s ]", mType.name(), mTimestamp.toString()); + return String.format("%s @ %s", mType.name(), TIMESTAMP_FORMATTER.format(mTimestamp)); } }