Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / time / WallClockTimestamp.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.time;
17
18 import com.google.common.collect.ComparisonChain;
19 import io.atomix.utils.misc.TimestampPrinter;
20
21 import java.util.Objects;
22
23 import static com.google.common.base.Preconditions.checkArgument;
24
25 /**
26  * A Timestamp that derives its value from the prevailing
27  * wallclock time on the controller where it is generated.
28  */
29 public class WallClockTimestamp implements Timestamp {
30
31   /**
32    * Returns a new wall clock timestamp for the given unix timestamp.
33    *
34    * @param unixTimestamp the unix timestamp for which to create a new wall clock timestamp
35    * @return the wall clock timestamp
36    */
37   public static WallClockTimestamp from(long unixTimestamp) {
38     return new WallClockTimestamp(unixTimestamp);
39   }
40
41   private final long unixTimestamp;
42
43   public WallClockTimestamp() {
44     unixTimestamp = System.currentTimeMillis();
45   }
46
47   public WallClockTimestamp(long timestamp) {
48     unixTimestamp = timestamp;
49   }
50
51   @Override
52   public int compareTo(Timestamp o) {
53     checkArgument(o instanceof WallClockTimestamp,
54         "Must be WallClockTimestamp", o);
55     WallClockTimestamp that = (WallClockTimestamp) o;
56
57     return ComparisonChain.start()
58         .compare(this.unixTimestamp, that.unixTimestamp)
59         .result();
60   }
61
62   @Override
63   public int hashCode() {
64     return Long.hashCode(unixTimestamp);
65   }
66
67   @Override
68   public boolean equals(Object obj) {
69     if (this == obj) {
70       return true;
71     }
72     if (!(obj instanceof WallClockTimestamp)) {
73       return false;
74     }
75     WallClockTimestamp that = (WallClockTimestamp) obj;
76     return Objects.equals(this.unixTimestamp, that.unixTimestamp);
77   }
78
79   @Override
80   public String toString() {
81     return new TimestampPrinter(unixTimestamp).toString();
82   }
83
84   /**
85    * Returns the unixTimestamp.
86    *
87    * @return unix timestamp
88    */
89   public long unixTimestamp() {
90     return unixTimestamp;
91   }
92 }