1 package edu.uci.iotproject.io;
3 import java.io.BufferedReader;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.time.Instant;
8 import java.time.LocalDateTime;
9 import java.time.ZoneId;
10 import java.time.ZonedDateTime;
11 import java.time.format.DateTimeFormatter;
15 * Parses a file to obtain the timestamps at which the smart plug was toggled on/off.
17 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
18 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
20 public class TriggerTimesFileReader {
22 public static final ZoneId ZONE_ID_LOS_ANGELES = ZoneId.of("America/Los_Angeles");
23 public static final ZoneId ZONE_ID_BUDAPEST = ZoneId.of("Europe/Budapest");
26 * Reads a file with trigger timestamps and parses the timestamps into {@link Instant}s using the rules specified
27 * by {@link #parseTriggerTimestamp(String, boolean)}.
28 * @param fileName The absolute path to the file with trigger timestamps.
29 * @param _24hFormat {@code true} if the timestamps in the file are in 24 hour format, {@code false} if they are in
31 * @return A containing the trigger timestamps represented as {@code Instant}s.
33 public List<Instant> readTriggerTimes(String fileName, boolean _24hFormat) {
34 List<Instant> listTriggerTimes = new ArrayList<>();
36 File file = new File(fileName);
37 BufferedReader br = new BufferedReader(new FileReader(file));
39 while ((s = br.readLine()) != null) {
40 listTriggerTimes.add(parseTriggerTimestamp(s, _24hFormat));
42 } catch (IOException e) {
45 System.out.println("List has: " + listTriggerTimes.size());
46 return listTriggerTimes;
50 * Parses a timestamp string to an {@link Instant} (UTC). Assumes timestamps are LA time.
51 * Format is expected to be either "MM/dd/uuuu HH:mm:ss" or "MM/dd/uuuu h:mm:ss a".
53 * @param timestampStr The string containing a date-time timestamp for LA's timezone.
54 * @param _24hFormat {@code true} if the time in {@code timestampStr} is given in 24 hour format, {@code false} if
55 * it is given in AM/PM format.
56 * @return An {@code Instant} representation of the parsed timestamp. Note that the {@code Instant} marks a point on
57 * the timeline in UTC. Use {@link Instant#atZone(ZoneId)} to convert to the corresponding time in a given
60 public Instant parseTriggerTimestamp(String timestampStr, boolean _24hFormat) {
61 // Note: only one 'h' when not prefixed with leading 0 for 1-9; and only one 'a' for AM/PM marker in Java 8 time
62 String format = _24hFormat ? "MM/dd/uuuu HH:mm:ss" : "MM/dd/uuuu h:mm:ss a";
63 LocalDateTime localDateTime = LocalDateTime.parse(timestampStr, DateTimeFormatter.ofPattern(format, Locale.US));
64 ZonedDateTime laZonedDateTime = localDateTime.atZone(ZONE_ID_LOS_ANGELES);
65 return laZonedDateTime.toInstant();