View Javadoc
1   /*
2    * Copyright 2020-2023 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.software.os;
6   
7   import java.time.Instant;
8   import java.time.LocalDateTime;
9   import java.time.ZoneId;
10  import java.time.format.DateTimeFormatter;
11  import java.util.Locale;
12  
13  import oshi.annotation.concurrent.Immutable;
14  
15  /**
16   * This class encapsulates information about users who are currently logged in to an operating system.
17   */
18  @Immutable
19  public class OSSession {
20      private static final DateTimeFormatter LOGIN_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ROOT);
21  
22      private final String userName;
23      private final String terminalDevice;
24      private final long loginTime;
25      private final String host;
26  
27      public OSSession(String userName, String terminalDevice, long loginTime, String host) {
28          this.userName = userName;
29          this.terminalDevice = terminalDevice;
30          this.loginTime = loginTime;
31          this.host = host;
32      }
33  
34      /**
35       * Gets the login name of the user
36       *
37       * @return the userName
38       */
39      public String getUserName() {
40          return userName;
41      }
42  
43      /**
44       * Gets the terminal device (such as tty, pts, etc.) the user used to log in
45       *
46       * @return the terminalDevice
47       */
48      public String getTerminalDevice() {
49          return terminalDevice;
50      }
51  
52      /**
53       * Gets the time the user logged in
54       *
55       * @return the loginTime, in milliseconds since the 1970 epoch
56       */
57      public long getLoginTime() {
58          return loginTime;
59      }
60  
61      /**
62       * Gets the remote host from which the user logged in
63       *
64       * @return the host as either an IPv4 or IPv6 representation. If the host is unspecified, may also be an empty
65       *         string, depending on the platform.
66       */
67      public String getHost() {
68          return host;
69      }
70  
71      @Override
72      public String toString() {
73          String loginStr = loginTime == 0 ? "No login"
74                  : LocalDateTime.ofInstant(Instant.ofEpochMilli(loginTime), ZoneId.systemDefault()).format(LOGIN_FORMAT);
75          String hostStr = "";
76          if (!host.isEmpty() && !host.equals("::") && !host.equals("0.0.0.0")) {
77              hostStr = ", (" + host + ")";
78          }
79          return String.format(Locale.ROOT, "%s, %s, %s%s", userName, terminalDevice, loginStr, hostStr);
80      }
81  }