2ee419452fa033035030087112d18300f2b2dd06
[onosfw.git] /
1 /*
2  * Copyright 2015 Open Networking Laboratory
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 org.onosproject.store.trivial;
17
18 import com.google.common.base.MoreObjects;
19 import com.google.common.collect.ComparisonChain;
20 import org.onosproject.store.Timestamp;
21
22 import java.util.Objects;
23
24 import static com.google.common.base.Preconditions.checkArgument;
25
26 /**
27  * A Timestamp that derives its value from the system clock time (in ns)
28  * on the controller where it is generated.
29  */
30 public class SystemClockTimestamp implements Timestamp {
31
32     private final long nanoTimestamp;
33
34     public SystemClockTimestamp() {
35         nanoTimestamp = System.nanoTime();
36     }
37
38     public SystemClockTimestamp(long timestamp) {
39         nanoTimestamp = timestamp;
40     }
41
42     @Override
43     public int compareTo(Timestamp o) {
44         checkArgument(o instanceof SystemClockTimestamp,
45                 "Must be SystemClockTimestamp", o);
46         SystemClockTimestamp that = (SystemClockTimestamp) o;
47
48         return ComparisonChain.start()
49                 .compare(this.nanoTimestamp, that.nanoTimestamp)
50                 .result();
51     }
52     @Override
53     public int hashCode() {
54         return Objects.hash(nanoTimestamp);
55     }
56
57     @Override
58     public boolean equals(Object obj) {
59         if (this == obj) {
60             return true;
61         }
62         if (!(obj instanceof SystemClockTimestamp)) {
63             return false;
64         }
65         SystemClockTimestamp that = (SystemClockTimestamp) obj;
66         return Objects.equals(this.nanoTimestamp, that.nanoTimestamp);
67     }
68
69     @Override
70     public String toString() {
71         return MoreObjects.toStringHelper(getClass())
72                     .add("nanoTimestamp", nanoTimestamp)
73                     .toString();
74     }
75
76     public long nanoTimestamp() {
77         return nanoTimestamp;
78     }
79
80     public long systemTimestamp() {
81         return nanoTimestamp / 1_000_000; // convert ns to ms
82     }
83 }