1 /*
2  * Copyright 2011-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */

15 package com.amazonaws.auth;
16
17 import com.amazonaws.annotation.SdkProtectedApi;
18 import com.amazonaws.annotation.SdkTestInternalApi;
19 import java.util.Date;
20
21 /**
22  * Clock interface to prevent static coupling to {@link System#currentTimeMillis()}.
23  */

24 @SdkProtectedApi
25 public interface SdkClock {
26
27     /**
28      * Standard implementation that calls out to {@link System#currentTimeMillis()}. Used in production code.
29      */

30     SdkClock STANDARD = new SdkClock() {
31         @Override
32         public long currentTimeMillis() {
33             return System.currentTimeMillis();
34         }
35     };
36
37     long currentTimeMillis();
38
39     /**
40      * Mock implementation used in tests.
41      */

42     final class MockClock implements SdkClock {
43         private final long mockedTime;
44
45         public MockClock(Date mockedTime) {
46             this(mockedTime.getTime());
47         }
48
49         public MockClock(long mockedTime) {
50             this.mockedTime = mockedTime;
51         }
52
53         @Override
54         public long currentTimeMillis() {
55             return mockedTime;
56         }
57     }
58
59     /**
60      * Container for Singleton instance of the {@link SdkClock}.
61      */

62     final class Instance {
63
64         private static SdkClock clock = STANDARD;
65
66         public static SdkClock get() {
67             return clock;
68         }
69
70         /**
71          * Should only be used by tests to mock the clock.
72          *
73          * @param newClock New clock to use.
74          */

75         @SdkTestInternalApi
76         public static void set(SdkClock newClock) {
77             clock = newClock;
78         }
79
80         /**
81          * Reset the clock to {@link #STANDARD}. Should only be used by SDK tests.
82          */

83         @SdkTestInternalApi
84         public static void reset() {
85             clock = STANDARD;
86         }
87
88     }
89 }
90