Skip to content

Commit c921a87

Browse files
authored
Refactor ZonedDateTime.now in millis resolution (#38577)
In different places across the code base the ZonedDateTime in milliseconds resolution has to be used for testing. Refactoring this to a single place to avoid code duplication closes #38511 closes #38581
1 parent 5988b44 commit c921a87

File tree

6 files changed

+33
-43
lines changed

6 files changed

+33
-43
lines changed

server/src/main/java/org/elasticsearch/common/time/DateUtils.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,12 @@
2323
import org.elasticsearch.common.logging.DeprecationLogger;
2424
import org.joda.time.DateTimeZone;
2525

26+
import java.time.Clock;
27+
import java.time.Duration;
2628
import java.time.Instant;
2729
import java.time.ZoneId;
2830
import java.time.ZoneOffset;
31+
import java.time.ZonedDateTime;
2932
import java.util.Collections;
3033
import java.util.HashMap;
3134
import java.util.Map;
@@ -139,4 +142,18 @@ public static long toMilliSeconds(long nanoSecondsSinceEpoch) {
139142

140143
return nanoSecondsSinceEpoch / 1_000_000;
141144
}
145+
146+
/**
147+
* Returns the current UTC date-time with milliseconds precision.
148+
* In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean
149+
* that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8
150+
* {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock}
151+
* which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision.
152+
*
153+
* @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC
154+
*/
155+
public static ZonedDateTime nowWithMillisResolution() {
156+
Clock millisResolutionClock = Clock.tick(Clock.systemUTC(), Duration.ofMillis(1));
157+
return ZonedDateTime.now(millisResolutionClock);
158+
}
142159
}

x-pack/plugin/core/src/test/java/org/elasticsearch/protocol/xpack/watcher/GetWatchResponseTests.java

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package org.elasticsearch.protocol.xpack.watcher;
77

88
import org.elasticsearch.common.bytes.BytesReference;
9+
import org.elasticsearch.common.time.DateUtils;
910
import org.elasticsearch.common.xcontent.DeprecationHandler;
1011
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
1112
import org.elasticsearch.common.xcontent.ToXContent;
@@ -23,9 +24,6 @@
2324

2425
import java.io.IOException;
2526
import java.io.InputStream;
26-
import java.time.Clock;
27-
import java.time.Instant;
28-
import java.time.ZoneOffset;
2927
import java.time.ZonedDateTime;
3028
import java.util.Collections;
3129
import java.util.HashMap;
@@ -126,15 +124,15 @@ private static BytesReference simpleWatch() {
126124

127125
private static WatchStatus randomWatchStatus() {
128126
long version = randomLongBetween(-1, Long.MAX_VALUE);
129-
WatchStatus.State state = new WatchStatus.State(randomBoolean(), nowWithMillisResolution());
127+
WatchStatus.State state = new WatchStatus.State(randomBoolean(), DateUtils.nowWithMillisResolution());
130128
ExecutionState executionState = randomFrom(ExecutionState.values());
131-
ZonedDateTime lastChecked = rarely() ? null : nowWithMillisResolution();
132-
ZonedDateTime lastMetCondition = rarely() ? null : nowWithMillisResolution();
129+
ZonedDateTime lastChecked = rarely() ? null : DateUtils.nowWithMillisResolution();
130+
ZonedDateTime lastMetCondition = rarely() ? null : DateUtils.nowWithMillisResolution();
133131
int size = randomIntBetween(0, 5);
134132
Map<String, ActionStatus> actionMap = new HashMap<>();
135133
for (int i = 0; i < size; i++) {
136134
ActionStatus.AckStatus ack = new ActionStatus.AckStatus(
137-
nowWithMillisResolution(),
135+
DateUtils.nowWithMillisResolution(),
138136
randomFrom(ActionStatus.AckStatus.State.values())
139137
);
140138
ActionStatus actionStatus = new ActionStatus(
@@ -154,16 +152,16 @@ private static WatchStatus randomWatchStatus() {
154152
}
155153

156154
private static ActionStatus.Throttle randomThrottle() {
157-
return new ActionStatus.Throttle(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
155+
return new ActionStatus.Throttle(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
158156
}
159157

160158
private static ActionStatus.Execution randomExecution() {
161159
if (randomBoolean()) {
162160
return null;
163161
} else if (randomBoolean()) {
164-
return ActionStatus.Execution.failure(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
162+
return ActionStatus.Execution.failure(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
165163
} else {
166-
return ActionStatus.Execution.successful(nowWithMillisResolution());
164+
return ActionStatus.Execution.successful(DateUtils.nowWithMillisResolution());
167165
}
168166
}
169167

@@ -229,8 +227,4 @@ private static ActionStatus.Execution convertHlrcToInternal(org.elasticsearch.cl
229227
private static ActionStatus.Throttle convertHlrcToInternal(org.elasticsearch.client.watcher.ActionStatus.Throttle throttle) {
230228
return new ActionStatus.Throttle(throttle.timestamp(), throttle.reason());
231229
}
232-
233-
private static ZonedDateTime nowWithMillisResolution() {
234-
return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC);
235-
}
236230
}

x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/calendars/ScheduledEventTests.java

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import org.elasticsearch.ElasticsearchStatusException;
99
import org.elasticsearch.common.io.stream.Writeable;
10+
import org.elasticsearch.common.time.DateUtils;
1011
import org.elasticsearch.common.unit.TimeValue;
1112
import org.elasticsearch.common.xcontent.XContentParser;
1213
import org.elasticsearch.common.xcontent.json.JsonXContent;
@@ -17,9 +18,6 @@
1718
import org.elasticsearch.xpack.core.ml.job.config.RuleCondition;
1819

1920
import java.io.IOException;
20-
import java.time.Clock;
21-
import java.time.Instant;
22-
import java.time.ZoneOffset;
2321
import java.time.ZonedDateTime;
2422
import java.util.EnumSet;
2523
import java.util.List;
@@ -29,7 +27,7 @@
2927
public class ScheduledEventTests extends AbstractSerializingTestCase<ScheduledEvent> {
3028

3129
public static ScheduledEvent createScheduledEvent(String calendarId) {
32-
ZonedDateTime start = nowWithMillisResolution();
30+
ZonedDateTime start = DateUtils.nowWithMillisResolution();
3331
return new ScheduledEvent(randomAlphaOfLength(10), start, start.plusSeconds(randomIntBetween(1, 10000)),
3432
calendarId, null);
3533
}
@@ -120,8 +118,4 @@ public void testLenientParser() throws IOException {
120118
ScheduledEvent.LENIENT_PARSER.apply(parser, null);
121119
}
122120
}
123-
124-
private static ZonedDateTime nowWithMillisResolution() {
125-
return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC);
126-
}
127121
}

x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@
1111
import org.elasticsearch.xpack.sql.session.Configuration;
1212
import org.elasticsearch.xpack.sql.util.DateUtils;
1313

14-
import java.time.Clock;
15-
import java.time.Duration;
16-
import java.time.ZonedDateTime;
17-
1814
public class TestUtils {
1915

2016
private TestUtils() {}
@@ -23,16 +19,4 @@ private TestUtils() {}
2319
Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, Mode.PLAIN,
2420
null, null, null);
2521

26-
/**
27-
* Returns the current UTC date-time with milliseconds precision.
28-
* In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean
29-
* that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8
30-
* {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock}
31-
* which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision.
32-
*
33-
* @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC
34-
*/
35-
public static final ZonedDateTime now() {
36-
return ZonedDateTime.now(Clock.tick(Clock.system(DateUtils.UTC), Duration.ofMillis(1)));
37-
}
3822
}

x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
import org.elasticsearch.test.ESTestCase;
99
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
10-
import org.elasticsearch.xpack.sql.TestUtils;
1110
import org.elasticsearch.xpack.sql.expression.Literal;
1211
import org.elasticsearch.xpack.sql.tree.Location;
1312
import org.elasticsearch.xpack.sql.tree.Source;
@@ -157,7 +156,8 @@ public void testConversionToDate() {
157156
assertEquals(date(18000000L), conversion.convert("1970-01-01T03:10:20-05:00"));
158157

159158
// double check back and forth conversion
160-
ZonedDateTime zdt = TestUtils.now();
159+
160+
ZonedDateTime zdt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution();
161161
Conversion forward = conversionFor(DATE, KEYWORD);
162162
Conversion back = conversionFor(KEYWORD, DATE);
163163
assertEquals(DateUtils.asDateOnly(zdt), back.convert(forward.convert(zdt)));
@@ -205,7 +205,8 @@ public void testConversionToDateTime() {
205205
assertEquals(dateTime(18000000L), conversion.convert("1970-01-01T00:00:00-05:00"));
206206

207207
// double check back and forth conversion
208-
ZonedDateTime dt = TestUtils.now();
208+
209+
ZonedDateTime dt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution();
209210
Conversion forward = conversionFor(DATETIME, KEYWORD);
210211
Conversion back = conversionFor(KEYWORD, DATETIME);
211212
assertEquals(dt, back.convert(forward.convert(dt)));

x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import org.elasticsearch.client.Client;
1818
import org.elasticsearch.common.collect.MapBuilder;
1919
import org.elasticsearch.common.settings.Settings;
20+
import org.elasticsearch.common.time.DateUtils;
2021
import org.elasticsearch.common.unit.TimeValue;
2122
import org.elasticsearch.common.util.concurrent.ThreadContext;
2223
import org.elasticsearch.common.xcontent.XContentBuilder;
@@ -276,7 +277,6 @@ public void testConfigureIndexInMapAndAction() {
276277
fieldName + "] or [ctx.payload._doc." + fieldName + "]"));
277278
}
278279

279-
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/38581")
280280
public void testIndexActionExecuteSingleDoc() throws Exception {
281281
boolean customId = randomBoolean();
282282
boolean docIdAsParam = customId && randomBoolean();
@@ -287,7 +287,7 @@ public void testIndexActionExecuteSingleDoc() throws Exception {
287287
refreshPolicy);
288288
ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, client, TimeValue.timeValueSeconds(30),
289289
TimeValue.timeValueSeconds(30));
290-
ZonedDateTime executionTime = ZonedDateTime.now(ZoneOffset.UTC);
290+
ZonedDateTime executionTime = DateUtils.nowWithMillisResolution();
291291
Payload payload;
292292

293293
if (customId && docIdAsParam == false) {

0 commit comments

Comments
 (0)