View Javadoc
1   /*
2    * Copyright 2020-2023 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.unix.aix;
6   
7   import java.time.LocalDateTime;
8   import java.time.ZoneId;
9   import java.time.format.DateTimeFormatter;
10  import java.time.format.DateTimeParseException;
11  import java.util.Locale;
12  import java.util.regex.Matcher;
13  import java.util.regex.Pattern;
14  
15  import oshi.annotation.concurrent.ThreadSafe;
16  import oshi.util.ExecutingCommand;
17  
18  /**
19   * Utility to query logged in users.
20   */
21  @ThreadSafe
22  public final class Who {
23  
24      // sample format:
25      // system boot 2020-06-16 09:12
26      private static final Pattern BOOT_FORMAT_AIX = Pattern.compile("\\D+(\\d{4}-\\d{2}-\\d{2})\\s+(\\d{2}:\\d{2}).*");
27      private static final DateTimeFormatter BOOT_DATE_FORMAT_AIX = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm",
28              Locale.ROOT);
29  
30      private Who() {
31      }
32  
33      /**
34       * Query {@code who -b} to get boot time
35       *
36       * @return Boot time in milliseconds since the epoch
37       */
38      public static long queryBootTime() {
39          String s = ExecutingCommand.getFirstAnswer("who -b");
40          if (s.isEmpty()) {
41              s = ExecutingCommand.getFirstAnswer("/usr/bin/who -b");
42          }
43          Matcher m = BOOT_FORMAT_AIX.matcher(s);
44          if (m.matches()) {
45              try {
46                  return LocalDateTime.parse(m.group(1) + " " + m.group(2), BOOT_DATE_FORMAT_AIX)
47                          .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
48              } catch (DateTimeParseException | NullPointerException e) {
49                  // Shouldn't happen with regex matching
50              }
51          }
52          return 0L;
53      }
54  }