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.
*/
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.
*/
@Override
public String toString() {
- return String.format("[ %s @ %s ]", mType.name(), mTimestamp.toString());
+ return String.format("%s @ %s", mType.name(), TIMESTAMP_FORMATTER.format(mTimestamp));
}
}