Line data Source code
1 : // Copyright (C) 2013 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.util.time; 16 : 17 : import com.google.common.annotations.VisibleForTesting; 18 : import com.google.gerrit.server.util.git.DelegateSystemReader; 19 : import java.time.Instant; 20 : import java.util.concurrent.TimeUnit; 21 : import java.util.function.LongSupplier; 22 : import org.eclipse.jgit.util.SystemReader; 23 : 24 : /** Static utility methods for dealing with dates and times. */ 25 : public class TimeUtil { 26 157 : private static final LongSupplier SYSTEM_CURRENT_MILLIS_SUPPLIER = System::currentTimeMillis; 27 : 28 157 : private static volatile LongSupplier currentMillisSupplier = SYSTEM_CURRENT_MILLIS_SUPPLIER; 29 : 30 : public static long nowMs() { 31 : // We should rather use Instant.now(Clock).toEpochMilli() instead but this would require some 32 : // changes in our testing code as we wouldn't have clock steps anymore. 33 157 : return currentMillisSupplier.getAsLong(); 34 : } 35 : 36 : public static long nowNanos() { 37 104 : return TimeUnit.NANOSECONDS.convert(TimeUtil.nowMs(), TimeUnit.MILLISECONDS); 38 : } 39 : 40 : public static Instant now() { 41 156 : return Instant.ofEpochMilli(nowMs()); 42 : } 43 : 44 : public static Instant truncateToSecond(Instant t) { 45 152 : return Instant.ofEpochMilli(t.getEpochSecond() * 1000); 46 : } 47 : 48 : @VisibleForTesting 49 : public static void setCurrentMillisSupplier(LongSupplier customCurrentMillisSupplier) { 50 31 : currentMillisSupplier = customCurrentMillisSupplier; 51 : 52 31 : SystemReader oldSystemReader = SystemReader.getInstance(); 53 31 : if (!(oldSystemReader instanceof GerritSystemReader)) { 54 31 : SystemReader.setInstance(new GerritSystemReader(oldSystemReader)); 55 : } 56 31 : } 57 : 58 : @VisibleForTesting 59 : public static void resetCurrentMillisSupplier() { 60 138 : currentMillisSupplier = SYSTEM_CURRENT_MILLIS_SUPPLIER; 61 138 : SystemReader.setInstance(null); 62 138 : } 63 : 64 : static class GerritSystemReader extends DelegateSystemReader { 65 : GerritSystemReader(SystemReader reader) { 66 31 : super(reader); 67 31 : } 68 : 69 : @Override 70 : public long getCurrentTime() { 71 27 : return currentMillisSupplier.getAsLong(); 72 : } 73 : } 74 : 75 : private TimeUtil() {} 76 : }