From c921a87fc51c8fe57efdfcb2277c967886fce080 Mon Sep 17 00:00:00 2001 From: Przemyslaw Gomulka Date: Fri, 8 Feb 2019 14:24:11 +0100 Subject: [PATCH] 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 --- .../elasticsearch/common/time/DateUtils.java | 17 ++++++++++++++ .../xpack/watcher/GetWatchResponseTests.java | 22 +++++++------------ .../ml/calendars/ScheduledEventTests.java | 10 ++------- .../elasticsearch/xpack/sql/TestUtils.java | 16 -------------- .../sql/type/DataTypeConversionTests.java | 7 +++--- .../actions/index/IndexActionTests.java | 4 ++-- 6 files changed, 33 insertions(+), 43 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/common/time/DateUtils.java b/server/src/main/java/org/elasticsearch/common/time/DateUtils.java index 20646ae14599a..4235344bd8371 100644 --- a/server/src/main/java/org/elasticsearch/common/time/DateUtils.java +++ b/server/src/main/java/org/elasticsearch/common/time/DateUtils.java @@ -23,9 +23,12 @@ import org.elasticsearch.common.logging.DeprecationLogger; import org.joda.time.DateTimeZone; +import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -139,4 +142,18 @@ public static long toMilliSeconds(long nanoSecondsSinceEpoch) { return nanoSecondsSinceEpoch / 1_000_000; } + + /** + * Returns the current UTC date-time with milliseconds precision. + * In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean + * that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8 + * {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock} + * which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision. + * + * @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC + */ + public static ZonedDateTime nowWithMillisResolution() { + Clock millisResolutionClock = Clock.tick(Clock.systemUTC(), Duration.ofMillis(1)); + return ZonedDateTime.now(millisResolutionClock); + } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/protocol/xpack/watcher/GetWatchResponseTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/protocol/xpack/watcher/GetWatchResponseTests.java index 9b71079a6e5e7..4cc566adf31bb 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/protocol/xpack/watcher/GetWatchResponseTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/protocol/xpack/watcher/GetWatchResponseTests.java @@ -6,6 +6,7 @@ package org.elasticsearch.protocol.xpack.watcher; import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContent; @@ -23,9 +24,6 @@ import java.io.IOException; import java.io.InputStream; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; @@ -126,15 +124,15 @@ private static BytesReference simpleWatch() { private static WatchStatus randomWatchStatus() { long version = randomLongBetween(-1, Long.MAX_VALUE); - WatchStatus.State state = new WatchStatus.State(randomBoolean(), nowWithMillisResolution()); + WatchStatus.State state = new WatchStatus.State(randomBoolean(), DateUtils.nowWithMillisResolution()); ExecutionState executionState = randomFrom(ExecutionState.values()); - ZonedDateTime lastChecked = rarely() ? null : nowWithMillisResolution(); - ZonedDateTime lastMetCondition = rarely() ? null : nowWithMillisResolution(); + ZonedDateTime lastChecked = rarely() ? null : DateUtils.nowWithMillisResolution(); + ZonedDateTime lastMetCondition = rarely() ? null : DateUtils.nowWithMillisResolution(); int size = randomIntBetween(0, 5); Map actionMap = new HashMap<>(); for (int i = 0; i < size; i++) { ActionStatus.AckStatus ack = new ActionStatus.AckStatus( - nowWithMillisResolution(), + DateUtils.nowWithMillisResolution(), randomFrom(ActionStatus.AckStatus.State.values()) ); ActionStatus actionStatus = new ActionStatus( @@ -154,16 +152,16 @@ private static WatchStatus randomWatchStatus() { } private static ActionStatus.Throttle randomThrottle() { - return new ActionStatus.Throttle(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20)); + return new ActionStatus.Throttle(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20)); } private static ActionStatus.Execution randomExecution() { if (randomBoolean()) { return null; } else if (randomBoolean()) { - return ActionStatus.Execution.failure(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20)); + return ActionStatus.Execution.failure(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20)); } else { - return ActionStatus.Execution.successful(nowWithMillisResolution()); + return ActionStatus.Execution.successful(DateUtils.nowWithMillisResolution()); } } @@ -229,8 +227,4 @@ private static ActionStatus.Execution convertHlrcToInternal(org.elasticsearch.cl private static ActionStatus.Throttle convertHlrcToInternal(org.elasticsearch.client.watcher.ActionStatus.Throttle throttle) { return new ActionStatus.Throttle(throttle.timestamp(), throttle.reason()); } - - private static ZonedDateTime nowWithMillisResolution() { - return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC); - } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/calendars/ScheduledEventTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/calendars/ScheduledEventTests.java index 6508ee5cb2054..9555d364a7bb1 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/calendars/ScheduledEventTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/calendars/ScheduledEventTests.java @@ -7,6 +7,7 @@ import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.common.io.stream.Writeable; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -17,9 +18,6 @@ import org.elasticsearch.xpack.core.ml.job.config.RuleCondition; import java.io.IOException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.EnumSet; import java.util.List; @@ -29,7 +27,7 @@ public class ScheduledEventTests extends AbstractSerializingTestCase { public static ScheduledEvent createScheduledEvent(String calendarId) { - ZonedDateTime start = nowWithMillisResolution(); + ZonedDateTime start = DateUtils.nowWithMillisResolution(); return new ScheduledEvent(randomAlphaOfLength(10), start, start.plusSeconds(randomIntBetween(1, 10000)), calendarId, null); } @@ -120,8 +118,4 @@ public void testLenientParser() throws IOException { ScheduledEvent.LENIENT_PARSER.apply(parser, null); } } - - private static ZonedDateTime nowWithMillisResolution() { - return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC); - } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java index be7f42d3f0c78..9b8fbdef43a77 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java @@ -11,10 +11,6 @@ import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.util.DateUtils; -import java.time.Clock; -import java.time.Duration; -import java.time.ZonedDateTime; - public class TestUtils { private TestUtils() {} @@ -23,16 +19,4 @@ private TestUtils() {} Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, Mode.PLAIN, null, null, null); - /** - * Returns the current UTC date-time with milliseconds precision. - * In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean - * that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8 - * {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock} - * which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision. - * - * @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC - */ - public static final ZonedDateTime now() { - return ZonedDateTime.now(Clock.tick(Clock.system(DateUtils.UTC), Duration.ofMillis(1))); - } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java index 73b4ea8fa8daa..686c97b91a06b 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java @@ -7,7 +7,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.TestUtils; import org.elasticsearch.xpack.sql.expression.Literal; import org.elasticsearch.xpack.sql.tree.Location; import org.elasticsearch.xpack.sql.tree.Source; @@ -157,7 +156,8 @@ public void testConversionToDate() { assertEquals(date(18000000L), conversion.convert("1970-01-01T03:10:20-05:00")); // double check back and forth conversion - ZonedDateTime zdt = TestUtils.now(); + + ZonedDateTime zdt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution(); Conversion forward = conversionFor(DATE, KEYWORD); Conversion back = conversionFor(KEYWORD, DATE); assertEquals(DateUtils.asDateOnly(zdt), back.convert(forward.convert(zdt))); @@ -205,7 +205,8 @@ public void testConversionToDateTime() { assertEquals(dateTime(18000000L), conversion.convert("1970-01-01T00:00:00-05:00")); // double check back and forth conversion - ZonedDateTime dt = TestUtils.now(); + + ZonedDateTime dt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution(); Conversion forward = conversionFor(DATETIME, KEYWORD); Conversion back = conversionFor(KEYWORD, DATETIME); assertEquals(dt, back.convert(forward.convert(dt))); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionTests.java index 8ce8a15e25e87..1864bd3bd5cce 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/index/IndexActionTests.java @@ -17,6 +17,7 @@ import org.elasticsearch.client.Client; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -276,7 +277,6 @@ public void testConfigureIndexInMapAndAction() { fieldName + "] or [ctx.payload._doc." + fieldName + "]")); } - @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/38581") public void testIndexActionExecuteSingleDoc() throws Exception { boolean customId = randomBoolean(); boolean docIdAsParam = customId && randomBoolean(); @@ -287,7 +287,7 @@ public void testIndexActionExecuteSingleDoc() throws Exception { refreshPolicy); ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, client, TimeValue.timeValueSeconds(30), TimeValue.timeValueSeconds(30)); - ZonedDateTime executionTime = ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime executionTime = DateUtils.nowWithMillisResolution(); Payload payload; if (customId && docIdAsParam == false) {