diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java index ec413c10fa728..41a13c216b501 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java @@ -23,10 +23,10 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.XContentParser; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Locale; import java.util.Objects; @@ -119,15 +119,16 @@ public enum State { ACKED; } - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final State state; - public AckStatus(DateTime timestamp, State state) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + public AckStatus(ZonedDateTime timestamp, State state) { + assert timestamp.getOffset() == ZoneOffset.UTC; + this.timestamp = timestamp; this.state = state; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -151,7 +152,7 @@ public int hashCode() { } public static AckStatus parse(String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; State state = null; String currentFieldName = null; @@ -181,25 +182,25 @@ public static AckStatus parse(String actionId, XContentParser parser) throws IOE public static class Execution { - public static Execution successful(DateTime timestamp) { + public static Execution successful(ZonedDateTime timestamp) { return new Execution(timestamp, true, null); } - public static Execution failure(DateTime timestamp, String reason) { + public static Execution failure(ZonedDateTime timestamp, String reason) { return new Execution(timestamp, false, reason); } - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final boolean successful; private final String reason; - private Execution(DateTime timestamp, boolean successful, String reason) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + private Execution(ZonedDateTime timestamp, boolean successful, String reason) { + this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.successful = successful; this.reason = reason; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -229,7 +230,7 @@ public int hashCode() { } public static Execution parse(String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; Boolean successful = null; String reason = null; @@ -269,15 +270,15 @@ public static Execution parse(String actionId, XContentParser parser) throws IOE public static class Throttle { - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final String reason; - public Throttle(DateTime timestamp, String reason) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + public Throttle(ZonedDateTime timestamp, String reason) { + this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.reason = reason; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -300,7 +301,7 @@ public int hashCode() { } public static Throttle parse(String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; String reason = null; String currentFieldName = null; diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java index b11673f9e552d..c8e9fc96d1387 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java @@ -23,9 +23,10 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.XContentParser; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -35,15 +36,14 @@ import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.client.watcher.WatchStatusDateParser.parseDate; import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; -import static org.joda.time.DateTimeZone.UTC; public class WatchStatus { private final State state; private final ExecutionState executionState; - private final DateTime lastChecked; - private final DateTime lastMetCondition; + private final ZonedDateTime lastChecked; + private final ZonedDateTime lastMetCondition; private final long version; private final Map actions; @Nullable private Map headers; @@ -51,8 +51,8 @@ public class WatchStatus { public WatchStatus(long version, State state, ExecutionState executionState, - DateTime lastChecked, - DateTime lastMetCondition, + ZonedDateTime lastChecked, + ZonedDateTime lastMetCondition, Map actions, Map headers) { this.version = version; @@ -72,11 +72,11 @@ public boolean checked() { return lastChecked != null; } - public DateTime lastChecked() { + public ZonedDateTime lastChecked() { return lastChecked; } - public DateTime lastMetCondition() { + public ZonedDateTime lastMetCondition() { return lastMetCondition; } @@ -123,8 +123,8 @@ public int hashCode() { public static WatchStatus parse(XContentParser parser) throws IOException { State state = null; ExecutionState executionState = null; - DateTime lastChecked = null; - DateTime lastMetCondition = null; + ZonedDateTime lastChecked = null; + ZonedDateTime lastMetCondition = null; Map actions = null; Map headers = Collections.emptyMap(); long version = -1; @@ -203,9 +203,9 @@ public static WatchStatus parse(XContentParser parser) throws IOException { public static class State { private final boolean active; - private final DateTime timestamp; + private final ZonedDateTime timestamp; - public State(boolean active, DateTime timestamp) { + public State(boolean active, ZonedDateTime timestamp) { this.active = active; this.timestamp = timestamp; } @@ -214,7 +214,7 @@ public boolean isActive() { return active; } - public DateTime getTimestamp() { + public ZonedDateTime getTimestamp() { return timestamp; } @@ -223,7 +223,7 @@ public static State parse(XContentParser parser) throws IOException { throw new ElasticsearchParseException("expected an object but found [{}] instead", parser.currentToken()); } boolean active = true; - DateTime timestamp = DateTime.now(UTC); + ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java index 33de475410f7f..65e9fb8e7e1f7 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java @@ -21,12 +21,14 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.time.DateFormatter; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.DateFieldMapper; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; public final class WatchStatusDateParser { @@ -36,14 +38,14 @@ private WatchStatusDateParser() { // Prevent instantiation. } - public static DateTime parseDate(String fieldName, XContentParser parser) throws IOException { + public static ZonedDateTime parseDate(String fieldName, XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NUMBER) { - return new DateTime(parser.longValue(), DateTimeZone.UTC); + return Instant.ofEpochMilli(parser.longValue()).atZone(ZoneOffset.UTC); } if (token == XContentParser.Token.VALUE_STRING) { - DateTime dateTime = parseDate(parser.text()); - return dateTime.toDateTime(DateTimeZone.UTC); + ZonedDateTime dateTime = parseDate(parser.text()); + return dateTime.withZoneSameInstant(ZoneOffset.UTC); } if (token == XContentParser.Token.VALUE_NULL) { return null; @@ -52,7 +54,7 @@ public static DateTime parseDate(String fieldName, XContentParser parser) throws "to be either a number or a string but found [{}] instead", fieldName, token); } - public static DateTime parseDate(String text) { - return FORMATTER.parseJoda(text); + public static ZonedDateTime parseDate(String text) { + return DateFormatters.from(FORMATTER.parse(text)); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/WatchStatusTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/WatchStatusTests.java index cb302b5e0286f..2d96b7752677b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/WatchStatusTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/watcher/WatchStatusTests.java @@ -27,10 +27,11 @@ import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.XContentTestUtils; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.function.Predicate; public class WatchStatusTests extends ESTestCase { @@ -50,32 +51,32 @@ public void testBasicParsing() throws IOException { assertEquals(expectedVersion, watchStatus.version()); assertEquals(expectedExecutionState, watchStatus.getExecutionState()); - assertEquals(new DateTime(1432663467763L, DateTimeZone.UTC), watchStatus.lastChecked()); - assertEquals(DateTime.parse("2015-05-26T18:04:27.763Z"), watchStatus.lastMetCondition()); + assertEquals(Instant.ofEpochMilli(1432663467763L).atZone(ZoneOffset.UTC), watchStatus.lastChecked()); + assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.763Z"), watchStatus.lastMetCondition()); WatchStatus.State watchState = watchStatus.state(); assertEquals(expectedActive, watchState.isActive()); - assertEquals(DateTime.parse("2015-05-26T18:04:27.723Z"), watchState.getTimestamp()); + assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.723Z"), watchState.getTimestamp()); ActionStatus actionStatus = watchStatus.actionStatus("test_index"); assertNotNull(actionStatus); ActionStatus.AckStatus ackStatus = actionStatus.ackStatus(); - assertEquals(DateTime.parse("2015-05-26T18:04:27.763Z"), ackStatus.timestamp()); + assertEquals(ZonedDateTime.parse("2015-05-26T18:04:27.763Z"), ackStatus.timestamp()); assertEquals(expectedAckState, ackStatus.state()); ActionStatus.Execution lastExecution = actionStatus.lastExecution(); - assertEquals(DateTime.parse("2015-05-25T18:04:27.733Z"), lastExecution.timestamp()); + assertEquals(ZonedDateTime.parse("2015-05-25T18:04:27.733Z"), lastExecution.timestamp()); assertFalse(lastExecution.successful()); assertEquals("failed to send email", lastExecution.reason()); ActionStatus.Execution lastSuccessfulExecution = actionStatus.lastSuccessfulExecution(); - assertEquals(DateTime.parse("2015-05-25T18:04:27.773Z"), lastSuccessfulExecution.timestamp()); + assertEquals(ZonedDateTime.parse("2015-05-25T18:04:27.773Z"), lastSuccessfulExecution.timestamp()); assertTrue(lastSuccessfulExecution.successful()); assertNull(lastSuccessfulExecution.reason()); ActionStatus.Throttle lastThrottle = actionStatus.lastThrottle(); - assertEquals(DateTime.parse("2015-04-25T18:05:23.445Z"), lastThrottle.timestamp()); + assertEquals(ZonedDateTime.parse("2015-04-25T18:05:23.445Z"), lastThrottle.timestamp()); assertEquals("throttling interval is set to [5 seconds] ...", lastThrottle.reason()); } diff --git a/server/src/test/java/org/elasticsearch/common/time/DateFormattersTests.java b/server/src/test/java/org/elasticsearch/common/time/DateFormattersTests.java index e573a2ede6bdb..acb202f80fc55 100644 --- a/server/src/test/java/org/elasticsearch/common/time/DateFormattersTests.java +++ b/server/src/test/java/org/elasticsearch/common/time/DateFormattersTests.java @@ -204,6 +204,7 @@ public void testRoundupFormatterWithEpochDates() { assertRoundupFormatter("strict_date_optional_time||epoch_millis", "2018-10-10T12:13:14.123Z", 1539173594123L); assertRoundupFormatter("strict_date_optional_time||epoch_millis", "1234567890", 1234567890L); assertRoundupFormatter("strict_date_optional_time||epoch_millis", "2018-10-10", 1539215999999L); + assertRoundupFormatter("strict_date_optional_time||epoch_millis", "2019-01-25T15:37:17.346928Z", 1548430637346L); assertRoundupFormatter("uuuu-MM-dd'T'HH:mm:ss.SSS||epoch_millis", "2018-10-10T12:13:14.123", 1539173594123L); assertRoundupFormatter("uuuu-MM-dd'T'HH:mm:ss.SSS||epoch_millis", "1234567890", 1234567890L); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java index aeaadfd5139f1..ae68840d153f1 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java @@ -10,13 +10,15 @@ import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Locale; import java.util.Objects; @@ -30,7 +32,7 @@ public class ActionStatus implements ToXContentObject { @Nullable private Execution lastSuccessfulExecution; @Nullable private Throttle lastThrottle; - public ActionStatus(DateTime now) { + public ActionStatus(ZonedDateTime now) { this(new AckStatus(now, AckStatus.State.AWAITS_SUCCESSFUL_EXECUTION), null, null, null); } @@ -76,7 +78,7 @@ public int hashCode() { return Objects.hash(ackStatus, lastExecution, lastSuccessfulExecution, lastThrottle); } - public void update(DateTime timestamp, Action.Result result) { + public void update(ZonedDateTime timestamp, Action.Result result) { switch (result.status()) { case FAILURE: @@ -99,7 +101,7 @@ public void update(DateTime timestamp, Action.Result result) { } } - public boolean onAck(DateTime timestamp) { + public boolean onAck(ZonedDateTime timestamp) { if (ackStatus.state == AckStatus.State.ACKABLE) { ackStatus = new AckStatus(timestamp, AckStatus.State.ACKED); return true; @@ -107,7 +109,7 @@ public boolean onAck(DateTime timestamp) { return false; } - public boolean resetAckStatus(DateTime timestamp) { + public boolean resetAckStatus(ZonedDateTime timestamp) { if (ackStatus.state != AckStatus.State.AWAITS_SUCCESSFUL_EXECUTION) { ackStatus = new AckStatus(timestamp, AckStatus.State.AWAITS_SUCCESSFUL_EXECUTION); return true; @@ -210,15 +212,15 @@ static State resolve(byte value) { } } - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final State state; - public AckStatus(DateTime timestamp, State state) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + public AckStatus(ZonedDateTime timestamp, State state) { + this.timestamp = timestamp; this.state = state; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -244,13 +246,13 @@ public int hashCode() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() - .field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.formatJoda(timestamp)) + .field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.format(timestamp)) .field(Field.ACK_STATUS_STATE.getPreferredName(), state.name().toLowerCase(Locale.ROOT)) .endObject(); } public static AckStatus parse(String watchId, String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; State state = null; String currentFieldName = null; @@ -259,7 +261,7 @@ public static AckStatus parse(String watchId, String actionId, XContentParser pa if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = dateTimeFormatter.parseJoda(parser.text()); + timestamp = DateFormatters.from(dateTimeFormatter.parse(parser.text())); } else if (Field.ACK_STATUS_STATE.match(currentFieldName, parser.getDeprecationHandler())) { state = State.valueOf(parser.text().toUpperCase(Locale.ROOT)); } else { @@ -279,12 +281,12 @@ public static AckStatus parse(String watchId, String actionId, XContentParser pa } static void writeTo(AckStatus status, StreamOutput out) throws IOException { - out.writeLong(status.timestamp.getMillis()); + out.writeLong(status.timestamp.toInstant().toEpochMilli()); out.writeByte(status.state.value); } static AckStatus readFrom(StreamInput in) throws IOException { - DateTime timestamp = new DateTime(in.readLong(), DateTimeZone.UTC); + ZonedDateTime timestamp = Instant.ofEpochMilli(in.readLong()).atZone(ZoneOffset.UTC); State state = State.resolve(in.readByte()); return new AckStatus(timestamp, state); } @@ -292,25 +294,25 @@ static AckStatus readFrom(StreamInput in) throws IOException { public static class Execution implements ToXContentObject { - public static Execution successful(DateTime timestamp) { + public static Execution successful(ZonedDateTime timestamp) { return new Execution(timestamp, true, null); } - public static Execution failure(DateTime timestamp, String reason) { + public static Execution failure(ZonedDateTime timestamp, String reason) { return new Execution(timestamp, false, reason); } - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final boolean successful; private final String reason; - private Execution(DateTime timestamp, boolean successful, String reason) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + private Execution(ZonedDateTime timestamp, boolean successful, String reason) { + this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.successful = successful; this.reason = reason; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -342,7 +344,7 @@ public int hashCode() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - builder.field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.formatJoda(timestamp)); + builder.field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.format(timestamp)); builder.field(Field.EXECUTION_SUCCESSFUL.getPreferredName(), successful); if (reason != null) { builder.field(Field.REASON.getPreferredName(), reason); @@ -351,7 +353,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws } public static Execution parse(String watchId, String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; Boolean successful = null; String reason = null; @@ -361,7 +363,7 @@ public static Execution parse(String watchId, String actionId, XContentParser pa if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = dateTimeFormatter.parseJoda(parser.text()); + timestamp = DateFormatters.from(dateTimeFormatter.parse(parser.text())); } else if (Field.EXECUTION_SUCCESSFUL.match(currentFieldName, parser.getDeprecationHandler())) { successful = parser.booleanValue(); } else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) { @@ -390,7 +392,7 @@ public static Execution parse(String watchId, String actionId, XContentParser pa } public static void writeTo(Execution execution, StreamOutput out) throws IOException { - out.writeLong(execution.timestamp.getMillis()); + out.writeLong(execution.timestamp.toInstant().toEpochMilli()); out.writeBoolean(execution.successful); if (!execution.successful) { out.writeString(execution.reason); @@ -398,7 +400,7 @@ public static void writeTo(Execution execution, StreamOutput out) throws IOExcep } public static Execution readFrom(StreamInput in) throws IOException { - DateTime timestamp = new DateTime(in.readLong(), DateTimeZone.UTC); + ZonedDateTime timestamp = Instant.ofEpochMilli(in.readLong()).atZone(ZoneOffset.UTC); boolean successful = in.readBoolean(); if (successful) { return successful(timestamp); @@ -409,15 +411,15 @@ public static Execution readFrom(StreamInput in) throws IOException { public static class Throttle implements ToXContentObject { - private final DateTime timestamp; + private final ZonedDateTime timestamp; private final String reason; - public Throttle(DateTime timestamp, String reason) { - this.timestamp = timestamp.toDateTime(DateTimeZone.UTC); + public Throttle(ZonedDateTime timestamp, String reason) { + this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.reason = reason; } - public DateTime timestamp() { + public ZonedDateTime timestamp() { return timestamp; } @@ -442,13 +444,13 @@ public int hashCode() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() - .field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.formatJoda(timestamp)) + .field(Field.TIMESTAMP.getPreferredName()).value(dateTimeFormatter.format(timestamp)) .field(Field.REASON.getPreferredName(), reason) .endObject(); } public static Throttle parse(String watchId, String actionId, XContentParser parser) throws IOException { - DateTime timestamp = null; + ZonedDateTime timestamp = null; String reason = null; String currentFieldName = null; @@ -457,7 +459,7 @@ public static Throttle parse(String watchId, String actionId, XContentParser par if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = dateTimeFormatter.parseJoda(parser.text()); + timestamp = DateFormatters.from(dateTimeFormatter.parse(parser.text())); } else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) { reason = parser.text(); } else { @@ -477,12 +479,12 @@ public static Throttle parse(String watchId, String actionId, XContentParser par } static void writeTo(Throttle throttle, StreamOutput out) throws IOException { - out.writeLong(throttle.timestamp.getMillis()); + out.writeLong(throttle.timestamp.toInstant().toEpochMilli()); out.writeString(throttle.reason); } static Throttle readFrom(StreamInput in) throws IOException { - DateTime timestamp = new DateTime(in.readLong(), DateTimeZone.UTC); + ZonedDateTime timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(in.readLong()), ZoneOffset.UTC); return new Throttle(timestamp, in.readString()); } } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionWrapper.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionWrapper.java index f2cdc63c6e94c..eec08453498ab 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionWrapper.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionWrapper.java @@ -25,11 +25,11 @@ import org.elasticsearch.xpack.core.watcher.transform.Transform; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.core.watcher.watch.WatchField; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Objects; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; @@ -109,7 +109,7 @@ public ActionWrapperResult execute(WatchExecutionContext ctx) { try { conditionResult = condition.execute(ctx); if (conditionResult.met() == false) { - ctx.watch().status().actionStatus(id).resetAckStatus(DateTime.now(DateTimeZone.UTC)); + ctx.watch().status().actionStatus(id).resetAckStatus(ZonedDateTime.now(ZoneOffset.UTC)); return new ActionWrapperResult(id, conditionResult, null, new Action.Result.ConditionFailed(action.type(), "condition not met. skipping")); } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/PeriodThrottler.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/PeriodThrottler.java index 34f4af70b8354..be1de60f9b338 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/PeriodThrottler.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/PeriodThrottler.java @@ -47,7 +47,9 @@ public Result throttle(String actionId, WatchExecutionContext ctx) { if (status.lastSuccessfulExecution() == null) { return Result.NO; } - TimeValue timeElapsed = TimeValue.timeValueMillis(clock.millis() - status.lastSuccessfulExecution().timestamp().getMillis()); + long now = clock.millis(); + long executionTime = status.lastSuccessfulExecution().timestamp().toInstant().toEpochMilli(); + TimeValue timeElapsed = TimeValue.timeValueMillis(now - executionTime); if (timeElapsed.getMillis() <= period.getMillis()) { return Result.throttle(PERIOD, "throttling interval is set to [{}] but time elapsed since last execution is [{}]", period, timeElapsed); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/QueuedWatch.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/QueuedWatch.java index b6b67057769aa..69f1295bb20b2 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/QueuedWatch.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/QueuedWatch.java @@ -10,17 +10,18 @@ import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; public class QueuedWatch implements Streamable, ToXContentObject { private String watchId; private String watchRecordId; - private DateTime triggeredTime; - private DateTime executionTime; + private ZonedDateTime triggeredTime; + private ZonedDateTime executionTime; public QueuedWatch() { } @@ -36,19 +37,19 @@ public String watchId() { return watchId; } - public DateTime triggeredTime() { + public ZonedDateTime triggeredTime() { return triggeredTime; } - public void triggeredTime(DateTime triggeredTime) { + public void triggeredTime(ZonedDateTime triggeredTime) { this.triggeredTime = triggeredTime; } - public DateTime executionTime() { + public ZonedDateTime executionTime() { return executionTime; } - public void executionTime(DateTime executionTime) { + public void executionTime(ZonedDateTime executionTime) { this.executionTime = executionTime; } @@ -56,16 +57,16 @@ public void executionTime(DateTime executionTime) { public void readFrom(StreamInput in) throws IOException { watchId = in.readString(); watchRecordId = in.readString(); - triggeredTime = new DateTime(in.readVLong(), DateTimeZone.UTC); - executionTime = new DateTime(in.readVLong(), DateTimeZone.UTC); + triggeredTime = Instant.ofEpochMilli(in.readVLong()).atZone(ZoneOffset.UTC); + executionTime = Instant.ofEpochMilli(in.readVLong()).atZone(ZoneOffset.UTC); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(watchId); out.writeString(watchRecordId); - out.writeVLong(triggeredTime.getMillis()); - out.writeVLong(executionTime.getMillis()); + out.writeVLong(triggeredTime.toInstant().toEpochMilli()); + out.writeVLong(executionTime.toInstant().toEpochMilli()); } @Override diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java index dbbff33dcefe9..52d0f648f99be 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java @@ -18,9 +18,9 @@ import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.core.watcher.watch.Watch; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,7 @@ public abstract class WatchExecutionContext { private final Wid id; - private final DateTime executionTime; + private final ZonedDateTime executionTime; private final TriggerEvent triggerEvent; private final TimeValue defaultThrottlePeriod; @@ -48,7 +48,7 @@ public abstract class WatchExecutionContext { private String nodeId; private String user; - public WatchExecutionContext(String watchId, DateTime executionTime, TriggerEvent triggerEvent, TimeValue defaultThrottlePeriod) { + public WatchExecutionContext(String watchId, ZonedDateTime executionTime, TriggerEvent triggerEvent, TimeValue defaultThrottlePeriod) { this.id = new Wid(watchId, executionTime); this.executionTime = executionTime; this.triggerEvent = triggerEvent; @@ -97,7 +97,7 @@ public Wid id() { return id; } - public DateTime executionTime() { + public ZonedDateTime executionTime() { return executionTime; } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionResult.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionResult.java index cce6a1a25114c..063296e542f2d 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionResult.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionResult.java @@ -14,14 +14,14 @@ import org.elasticsearch.xpack.core.watcher.input.Input; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; import org.elasticsearch.xpack.core.watcher.transform.Transform; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.ZonedDateTime; import java.util.Map; public class WatchExecutionResult implements ToXContentObject { - private final DateTime executionTime; + private final ZonedDateTime executionTime; private final long executionDurationMs; @Nullable private final Input.Result inputResult; @Nullable private final Condition.Result conditionResult; @@ -33,7 +33,7 @@ public WatchExecutionResult(WatchExecutionContext context, long executionDuratio context.actionsResults()); } - private WatchExecutionResult(DateTime executionTime, long executionDurationMs, Input.Result inputResult, + private WatchExecutionResult(ZonedDateTime executionTime, long executionDurationMs, Input.Result inputResult, Condition.Result conditionResult, @Nullable Transform.Result transformResult, Map actionsResults) { this.executionTime = executionTime; @@ -44,7 +44,7 @@ private WatchExecutionResult(DateTime executionTime, long executionDurationMs, I this.executionDurationMs = executionDurationMs; } - public DateTime executionTime() { + public ZonedDateTime executionTime() { return executionTime; } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionSnapshot.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionSnapshot.java index 986011d35205f..055e08cd7a58c 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionSnapshot.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionSnapshot.java @@ -11,18 +11,19 @@ import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.xpack.core.watcher.actions.ActionWrapperResult; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Map; public class WatchExecutionSnapshot implements Streamable, ToXContentObject { private String watchId; private String watchRecordId; - private DateTime triggeredTime; - private DateTime executionTime; + private ZonedDateTime triggeredTime; + private ZonedDateTime executionTime; private ExecutionPhase phase; private String[] executedActions; private StackTraceElement[] executionStackTrace; @@ -55,11 +56,11 @@ public String watchRecordId() { return watchRecordId; } - public DateTime triggeredTime() { + public ZonedDateTime triggeredTime() { return triggeredTime; } - public DateTime executionTime() { + public ZonedDateTime executionTime() { return executionTime; } @@ -75,8 +76,8 @@ public StackTraceElement[] executionStackTrace() { public void readFrom(StreamInput in) throws IOException { watchId = in.readString(); watchRecordId = in.readString(); - triggeredTime = new DateTime(in.readVLong(), DateTimeZone.UTC); - executionTime = new DateTime(in.readVLong(), DateTimeZone.UTC); + triggeredTime = Instant.ofEpochMilli(in.readVLong()).atZone(ZoneOffset.UTC); + executionTime = Instant.ofEpochMilli(in.readVLong()).atZone(ZoneOffset.UTC); phase = ExecutionPhase.resolve(in.readString()); int size = in.readVInt(); executionStackTrace = new StackTraceElement[size]; @@ -93,8 +94,8 @@ public void readFrom(StreamInput in) throws IOException { public void writeTo(StreamOutput out) throws IOException { out.writeString(watchId); out.writeString(watchRecordId); - out.writeVLong(triggeredTime.getMillis()); - out.writeVLong(executionTime.getMillis()); + out.writeVLong(triggeredTime.toInstant().toEpochMilli()); + out.writeVLong(executionTime.toInstant().toEpochMilli()); out.writeString(phase.id()); out.writeVInt(executionStackTrace.length); for (StackTraceElement element : executionStackTrace) { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/Wid.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/Wid.java index a7a8fb4bea3cb..48764dc46e2f8 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/Wid.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/Wid.java @@ -5,10 +5,9 @@ */ package org.elasticsearch.xpack.core.watcher.execution; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import java.util.UUID; import static org.elasticsearch.xpack.core.watcher.support.Exceptions.illegalArgument; @@ -26,14 +25,14 @@ */ public class Wid { - private static final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; private final String watchId; private final String value; - public Wid(String watchId, DateTime executionTime) { + public Wid(String watchId, ZonedDateTime executionTime) { this.watchId = watchId; - this.value = watchId + "_" + UUID.randomUUID().toString() + "-" + formatter.print(executionTime); + this.value = watchId + "_" + UUID.randomUUID().toString() + "-" + formatter.format(executionTime); } public Wid(String value) { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/history/HistoryStoreField.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/history/HistoryStoreField.java index e655be8beff6b..9952033747535 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/history/HistoryStoreField.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/history/HistoryStoreField.java @@ -5,21 +5,21 @@ */ package org.elasticsearch.xpack.core.watcher.history; +import org.elasticsearch.common.time.DateFormatter; import org.elasticsearch.xpack.core.watcher.support.WatcherIndexTemplateRegistryField; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; + +import java.time.ZonedDateTime; public final class HistoryStoreField { public static final String INDEX_PREFIX = ".watcher-history-"; public static final String INDEX_PREFIX_WITH_TEMPLATE = INDEX_PREFIX + WatcherIndexTemplateRegistryField.INDEX_TEMPLATE_VERSION + "-"; - static final DateTimeFormatter indexTimeFormat = DateTimeFormat.forPattern("YYYY.MM.dd"); + private static final DateFormatter indexTimeFormat = DateFormatter.forPattern("yyyy.MM.dd"); /** * Calculates the correct history index name for a given time */ - public static String getHistoryIndexNameForTime(DateTime time) { - return INDEX_PREFIX_WITH_TEMPLATE + indexTimeFormat.print(time); + public static String getHistoryIndexNameForTime(ZonedDateTime time) { + return INDEX_PREFIX_WITH_TEMPLATE + indexTimeFormat.format(time); } } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java index e67baeaad3916..ef8b541e0355b 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java @@ -10,17 +10,20 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.time.DateFormatter; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.time.DateMathParser; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.DateFieldMapper; import org.elasticsearch.script.JodaCompatibleZonedDateTime; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Locale; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -29,39 +32,40 @@ public class WatcherDateTimeUtils { public static final DateFormatter dateTimeFormatter = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER; public static final DateMathParser dateMathParser = dateTimeFormatter.toDateMathParser(); + private WatcherDateTimeUtils() { } - public static DateTime convertToDate(Object value, Clock clock) { - if (value instanceof DateTime) { - return (DateTime) value; + public static ZonedDateTime convertToDate(Object value, Clock clock) { + if (value instanceof ZonedDateTime) { + return (ZonedDateTime) value; } if (value instanceof JodaCompatibleZonedDateTime) { - return new DateTime(((JodaCompatibleZonedDateTime) value).toInstant().toEpochMilli(), DateTimeZone.UTC); + return ((JodaCompatibleZonedDateTime) value).getZonedDateTime(); } if (value instanceof String) { - return parseDateMath((String) value, DateTimeZone.UTC, clock); + return parseDateMath((String) value, ZoneOffset.UTC, clock); } if (value instanceof Number) { - return new DateTime(((Number) value).longValue(), DateTimeZone.UTC); + return Instant.ofEpochMilli(((Number) value).longValue()).atZone(ZoneOffset.UTC); } return null; } - public static DateTime parseDate(String dateAsText) { + public static ZonedDateTime parseDate(String dateAsText) { return parseDate(dateAsText, null); } - public static DateTime parseDate(String format, DateTimeZone timeZone) { - DateTime dateTime = dateTimeFormatter.parseJoda(format); - return timeZone != null ? dateTime.toDateTime(timeZone) : dateTime; + public static ZonedDateTime parseDate(String format, ZoneId timeZone) { + ZonedDateTime zonedDateTime = DateFormatters.from(dateTimeFormatter.parse(format)); + return timeZone != null ? zonedDateTime.withZoneSameInstant(timeZone) : zonedDateTime; } - public static String formatDate(DateTime date) { - return dateTimeFormatter.formatJoda(date); + public static String formatDate(ZonedDateTime date) { + return dateTimeFormatter.format(date); } - public static DateTime parseDateMath(String fieldName, XContentParser parser, DateTimeZone timeZone, Clock clock) throws IOException { + public static ZonedDateTime parseDateMath(String fieldName, XContentParser parser, ZoneId timeZone, Clock clock) throws IOException { if (parser.currentToken() == XContentParser.Token.VALUE_NULL) { throw new ElasticsearchParseException("could not parse date/time expected date field [{}] to not be null but was null", fieldName); @@ -69,11 +73,11 @@ public static DateTime parseDateMath(String fieldName, XContentParser parser, Da return parseDateMathOrNull(fieldName, parser, timeZone, clock); } - public static DateTime parseDateMathOrNull(String fieldName, XContentParser parser, DateTimeZone timeZone, + public static ZonedDateTime parseDateMathOrNull(String fieldName, XContentParser parser, ZoneId timeZone, Clock clock) throws IOException { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NUMBER) { - return new DateTime(parser.longValue(), timeZone); + return Instant.ofEpochMilli(parser.longValue()).atZone(timeZone); } if (token == XContentParser.Token.VALUE_STRING) { try { @@ -90,14 +94,14 @@ public static DateTime parseDateMathOrNull(String fieldName, XContentParser pars "found [{}] instead", fieldName, token); } - public static DateTime parseDateMath(String valueString, DateTimeZone timeZone, final Clock clock) { - return new DateTime(dateMathParser.parse(valueString, clock::millis).toEpochMilli(), timeZone); + public static ZonedDateTime parseDateMath(String valueString, ZoneId timeZone, final Clock clock) { + return dateMathParser.parse(valueString, clock::millis).atZone(timeZone); } - public static DateTime parseDate(String fieldName, XContentParser parser, DateTimeZone timeZone) throws IOException { + public static ZonedDateTime parseDate(String fieldName, XContentParser parser, ZoneId timeZone) throws IOException { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NUMBER) { - return new DateTime(parser.longValue(), timeZone); + return Instant.ofEpochMilli(parser.longValue()).atZone(timeZone); } if (token == XContentParser.Token.VALUE_STRING) { return parseDate(parser.text(), timeZone); @@ -109,32 +113,28 @@ public static DateTime parseDate(String fieldName, XContentParser parser, DateTi "found [{}] instead", fieldName, token); } - public static XContentBuilder writeDate(String fieldName, XContentBuilder builder, DateTime date) throws IOException { + public static XContentBuilder writeDate(String fieldName, XContentBuilder builder, ZonedDateTime date) throws IOException { if (date == null) { return builder.nullField(fieldName); } return builder.field(fieldName, formatDate(date)); } - public static void writeDate(StreamOutput out, DateTime date) throws IOException { - out.writeLong(date.getMillis()); - } - - public static DateTime readDate(StreamInput in, DateTimeZone timeZone) throws IOException { - return new DateTime(in.readLong(), timeZone); + public static void writeDate(StreamOutput out, ZonedDateTime date) throws IOException { + out.writeLong(date.toInstant().toEpochMilli()); } - public static void writeOptionalDate(StreamOutput out, DateTime date) throws IOException { + public static void writeOptionalDate(StreamOutput out, ZonedDateTime date) throws IOException { if (date == null) { out.writeBoolean(false); return; } out.writeBoolean(true); - out.writeLong(date.getMillis()); + out.writeLong(date.toInstant().toEpochMilli()); } - public static DateTime readOptionalDate(StreamInput in, DateTimeZone timeZone) throws IOException { - return in.readBoolean() ? new DateTime(in.readLong(), timeZone) : null; + public static ZonedDateTime readOptionalDate(StreamInput in) throws IOException { + return in.readBoolean() ? Instant.ofEpochMilli(in.readLong()).atZone(ZoneOffset.UTC) : null; } public static TimeValue parseTimeValue(XContentParser parser, String settingName) throws IOException { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherUtils.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherUtils.java index 389d8ef9960e8..a27add6ab1d13 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherUtils.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherUtils.java @@ -11,10 +11,10 @@ import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; -import org.joda.time.DateTime; import java.io.IOException; import java.lang.reflect.Array; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; @@ -67,8 +67,8 @@ private static void flattenModel(String key, Object value, Map r } return; } - if (value instanceof DateTime) { - result.put(key, formatDate((DateTime) value)); + if (value instanceof ZonedDateTime) { + result.put(key, formatDate((ZonedDateTime) value)); return; } if (value instanceof TimeValue) { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherXContentParser.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherXContentParser.java index be422d4c38da7..fcb3802ca6b76 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherXContentParser.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherXContentParser.java @@ -14,11 +14,11 @@ import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.xpack.core.watcher.common.secret.Secret; import org.elasticsearch.xpack.core.watcher.crypto.CryptoService; -import org.joda.time.DateTime; import java.io.IOException; import java.nio.CharBuffer; import java.time.Clock; +import java.time.ZonedDateTime; import java.util.List; import java.util.Map; @@ -63,12 +63,12 @@ public static Secret secretOrNull(XContentParser parser) throws IOException { return new Secret(chars); } - private final DateTime parseTime; + private final ZonedDateTime parseTime; private final XContentParser parser; @Nullable private final CryptoService cryptoService; private final boolean allowRedactedPasswords; - public WatcherXContentParser(XContentParser parser, DateTime parseTime, @Nullable CryptoService cryptoService, + public WatcherXContentParser(XContentParser parser, ZonedDateTime parseTime, @Nullable CryptoService cryptoService, boolean allowRedactedPasswords) { this.parseTime = parseTime; this.parser = parser; @@ -76,7 +76,7 @@ public WatcherXContentParser(XContentParser parser, DateTime parseTime, @Nullabl this.allowRedactedPasswords = allowRedactedPasswords; } - public DateTime getParseDateTime() { return parseTime; } + public ZonedDateTime getParseDateTime() { return parseTime; } @Override public XContentType contentType() { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/trigger/TriggerEvent.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/trigger/TriggerEvent.java index e09f24f62efb0..be487792feef9 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/trigger/TriggerEvent.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/trigger/TriggerEvent.java @@ -10,26 +10,25 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.script.JodaCompatibleZonedDateTime; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; -import org.joda.time.DateTime; import java.io.IOException; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; public abstract class TriggerEvent implements ToXContentObject { private final String jobName; - protected final DateTime triggeredTime; + protected final ZonedDateTime triggeredTime; protected final Map data; - public TriggerEvent(String jobName, DateTime triggeredTime) { + public TriggerEvent(String jobName, ZonedDateTime triggeredTime) { this.jobName = jobName; this.triggeredTime = triggeredTime; this.data = new HashMap<>(); data.put(Field.TRIGGERED_TIME.getPreferredName(), - new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(triggeredTime.getMillis()), ZoneOffset.UTC)); + new JodaCompatibleZonedDateTime(triggeredTime.toInstant(), ZoneOffset.UTC)); } public String jobName() { @@ -38,7 +37,7 @@ public String jobName() { public abstract String type(); - public DateTime triggeredTime() { + public ZonedDateTime triggeredTime() { return triggeredTime; } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/Watch.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/Watch.java index e34b0a15e7133..f7942ec165e82 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/Watch.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/Watch.java @@ -16,9 +16,9 @@ import org.elasticsearch.xpack.core.watcher.input.ExecutableInput; import org.elasticsearch.xpack.core.watcher.transform.ExecutableTransform; import org.elasticsearch.xpack.core.watcher.trigger.Trigger; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.ZonedDateTime; import java.util.List; import java.util.Map; @@ -112,7 +112,7 @@ public long getSourcePrimaryTerm() { * * @return {@code true} if the status of this watch changed, {@code false} otherwise. */ - public boolean setState(boolean active, DateTime now) { + public boolean setState(boolean active, ZonedDateTime now) { return status.setActive(active, now); } @@ -121,7 +121,7 @@ public boolean setState(boolean active, DateTime now) { * * @return {@code true} if the status of this watch changed, {@code false} otherwise. */ - public boolean ack(DateTime now, String... actions) { + public boolean ack(ZonedDateTime now, String... actions) { return status.onAck(now, actions); } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/WatchStatus.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/WatchStatus.java index 93e713bb8844e..0da93fe9ab2d7 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/WatchStatus.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/watch/WatchStatus.java @@ -19,9 +19,11 @@ import org.elasticsearch.xpack.core.watcher.execution.ExecutionState; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherParams; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherXContentParser; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -30,11 +32,9 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.parseDate; -import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.readDate; import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.readOptionalDate; import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.writeDate; import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.writeOptionalDate; -import static org.joda.time.DateTimeZone.UTC; public class WatchStatus implements ToXContentObject, Streamable { @@ -43,8 +43,8 @@ public class WatchStatus implements ToXContentObject, Streamable { private State state; @Nullable private ExecutionState executionState; - @Nullable private DateTime lastChecked; - @Nullable private DateTime lastMetCondition; + @Nullable private ZonedDateTime lastChecked; + @Nullable private ZonedDateTime lastMetCondition; @Nullable private long version; @Nullable private Map headers; private Map actions; @@ -53,11 +53,11 @@ public class WatchStatus implements ToXContentObject, Streamable { private WatchStatus() { } - public WatchStatus(DateTime now, Map actions) { + public WatchStatus(ZonedDateTime now, Map actions) { this(-1, new State(true, now), null, null, null, actions, Collections.emptyMap()); } - public WatchStatus(long version, State state, ExecutionState executionState, DateTime lastChecked, DateTime lastMetCondition, + public WatchStatus(long version, State state, ExecutionState executionState, ZonedDateTime lastChecked, ZonedDateTime lastMetCondition, Map actions, Map headers) { this.version = version; this.lastChecked = lastChecked; @@ -76,7 +76,7 @@ public boolean checked() { return lastChecked != null; } - public DateTime lastChecked() { + public ZonedDateTime lastChecked() { return lastChecked; } @@ -134,7 +134,7 @@ public int hashCode() { * * @param metCondition indicates whether the watch's condition was met. */ - public void onCheck(boolean metCondition, DateTime timestamp) { + public void onCheck(boolean metCondition, ZonedDateTime timestamp) { lastChecked = timestamp; if (metCondition) { lastMetCondition = timestamp; @@ -145,7 +145,7 @@ public void onCheck(boolean metCondition, DateTime timestamp) { } } - public void onActionResult(String actionId, DateTime timestamp, Action.Result result) { + public void onActionResult(String actionId, ZonedDateTime timestamp, Action.Result result) { ActionStatus status = actions.get(actionId); status.update(timestamp, result); } @@ -159,7 +159,7 @@ public void onActionResult(String actionId, DateTime timestamp, Action.Result re * * @return {@code true} if the state of changed due to the ack, {@code false} otherwise. */ - boolean onAck(DateTime timestamp, String... actionIds) { + boolean onAck(ZonedDateTime timestamp, String... actionIds) { boolean changed = false; boolean containsAll = false; for (String actionId : actionIds) { @@ -185,7 +185,7 @@ boolean onAck(DateTime timestamp, String... actionIds) { return changed; } - boolean setActive(boolean active, DateTime now) { + boolean setActive(boolean active, ZonedDateTime now) { boolean change = this.state.active != active; if (change) { this.state = new State(active, now); @@ -219,15 +219,15 @@ public void writeTo(StreamOutput out) throws IOException { @Override public void readFrom(StreamInput in) throws IOException { version = in.readLong(); - lastChecked = readOptionalDate(in, UTC); - lastMetCondition = readOptionalDate(in, UTC); + lastChecked = readOptionalDate(in); + lastMetCondition = readOptionalDate(in); int count = in.readInt(); Map actions = new HashMap<>(count); for (int i = 0; i < count; i++) { actions.put(in.readString(), ActionStatus.readFrom(in)); } this.actions = unmodifiableMap(actions); - state = new State(in.readBoolean(), readDate(in, UTC)); + state = new State(in.readBoolean(), Instant.ofEpochMilli(in.readLong()).atZone(ZoneOffset.UTC)); boolean executionStateExists = in.readBoolean(); if (executionStateExists) { executionState = ExecutionState.resolve(in.readString()); @@ -277,8 +277,8 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws public static WatchStatus parse(String watchId, WatcherXContentParser parser) throws IOException { State state = null; ExecutionState executionState = null; - DateTime lastChecked = null; - DateTime lastMetCondition = null; + ZonedDateTime lastChecked = null; + ZonedDateTime lastMetCondition = null; Map actions = null; long version = -1; Map headers = Collections.emptyMap(); @@ -304,14 +304,14 @@ public static WatchStatus parse(String watchId, WatcherXContentParser parser) th } } else if (Field.LAST_CHECKED.match(currentFieldName, parser.getDeprecationHandler())) { if (token.isValue()) { - lastChecked = parseDate(currentFieldName, parser, UTC); + lastChecked = parseDate(currentFieldName, parser, ZoneOffset.UTC); } else { throw new ElasticsearchParseException("could not parse watch status for [{}]. expecting field [{}] to hold a date " + "value, found [{}] instead", watchId, currentFieldName, token); } } else if (Field.LAST_MET_CONDITION.match(currentFieldName, parser.getDeprecationHandler())) { if (token.isValue()) { - lastMetCondition = parseDate(currentFieldName, parser, UTC); + lastMetCondition = parseDate(currentFieldName, parser, ZoneOffset.UTC); } else { throw new ElasticsearchParseException("could not parse watch status for [{}]. expecting field [{}] to hold a date " + "value, found [{}] instead", watchId, currentFieldName, token); @@ -361,9 +361,9 @@ public static WatchStatus parse(String watchId, WatcherXContentParser parser) th public static class State implements ToXContentObject { final boolean active; - final DateTime timestamp; + final ZonedDateTime timestamp; - public State(boolean active, DateTime timestamp) { + public State(boolean active, ZonedDateTime timestamp) { this.active = active; this.timestamp = timestamp; } @@ -372,7 +372,7 @@ public boolean isActive() { return active; } - public DateTime getTimestamp() { + public ZonedDateTime getTimestamp() { return timestamp; } @@ -389,7 +389,7 @@ public static State parse(XContentParser parser) throws IOException { throw new ElasticsearchParseException("expected an object but found [{}] instead", parser.currentToken()); } boolean active = true; - DateTime timestamp = DateTime.now(UTC); + ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { @@ -398,7 +398,7 @@ public static State parse(XContentParser parser) throws IOException { } else if (Field.ACTIVE.match(currentFieldName, parser.getDeprecationHandler())) { active = parser.booleanValue(); } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = parseDate(currentFieldName, parser, UTC); + timestamp = parseDate(currentFieldName, parser, ZoneOffset.UTC); } else { parser.skipChildren(); } 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 13f4b0fb5d3b4..52ac74acc309b 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 @@ -20,11 +20,11 @@ import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.xpack.core.watcher.watch.WatchStatus; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.io.InputStream; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -124,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(), DateTime.now(DateTimeZone.UTC)); + WatchStatus.State state = new WatchStatus.State(randomBoolean(), ZonedDateTime.now(ZoneOffset.UTC)); ExecutionState executionState = randomFrom(ExecutionState.values()); - DateTime lastChecked = rarely() ? null : DateTime.now(DateTimeZone.UTC); - DateTime lastMetCondition = rarely() ? null : DateTime.now(DateTimeZone.UTC); + ZonedDateTime lastChecked = rarely() ? null : ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime lastMetCondition = rarely() ? null : ZonedDateTime.now(ZoneOffset.UTC); int size = randomIntBetween(0, 5); Map actionMap = new HashMap<>(); for (int i = 0; i < size; i++) { ActionStatus.AckStatus ack = new ActionStatus.AckStatus( - DateTime.now(DateTimeZone.UTC), + ZonedDateTime.now(ZoneOffset.UTC), randomFrom(ActionStatus.AckStatus.State.values()) ); ActionStatus actionStatus = new ActionStatus( @@ -152,16 +152,16 @@ private static WatchStatus randomWatchStatus() { } private static ActionStatus.Throttle randomThrottle() { - return new ActionStatus.Throttle(DateTime.now(DateTimeZone.UTC), randomAlphaOfLengthBetween(10, 20)); + return new ActionStatus.Throttle(ZonedDateTime.now(ZoneOffset.UTC), randomAlphaOfLengthBetween(10, 20)); } private static ActionStatus.Execution randomExecution() { if (randomBoolean()) { return null; } else if (randomBoolean()) { - return ActionStatus.Execution.failure(DateTime.now(DateTimeZone.UTC), randomAlphaOfLengthBetween(10, 20)); + return ActionStatus.Execution.failure(ZonedDateTime.now(ZoneOffset.UTC), randomAlphaOfLengthBetween(10, 20)); } else { - return ActionStatus.Execution.successful(DateTime.now(DateTimeZone.UTC)); + return ActionStatus.Execution.successful(ZonedDateTime.now(ZoneOffset.UTC)); } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/ReservedRolesStoreTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/ReservedRolesStoreTests.java index f0da0c5775e1f..bda5304a26141 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/ReservedRolesStoreTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/ReservedRolesStoreTests.java @@ -139,9 +139,9 @@ import org.elasticsearch.xpack.core.watcher.transport.actions.service.WatcherServiceAction; import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsAction; import org.elasticsearch.xpack.core.watcher.watch.Watch; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -1011,7 +1011,7 @@ public void testWatcherAdminRole() { assertThat(role.indices().allowedIndicesMatcher(IndexAction.NAME).test("foo"), is(false)); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); String historyIndex = HistoryStoreField.getHistoryIndexNameForTime(now); for (String index : new String[]{ Watch.INDEX, historyIndex, TriggeredWatchStoreField.INDEX_NAME }) { assertOnlyReadAllowed(role, index); @@ -1041,7 +1041,7 @@ public void testWatcherUserRole() { assertThat(role.indices().allowedIndicesMatcher(IndexAction.NAME).test("foo"), is(false)); assertThat(role.indices().allowedIndicesMatcher(IndexAction.NAME).test(TriggeredWatchStoreField.INDEX_NAME), is(false)); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); String historyIndex = HistoryStoreField.getHistoryIndexNameForTime(now); for (String index : new String[]{ Watch.INDEX, historyIndex }) { assertOnlyReadAllowed(role, index); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/watcher/watch/ClockMock.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/watcher/watch/ClockMock.java index b7f8e1e6d5672..2a2b35f4fa924 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/watcher/watch/ClockMock.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/watcher/watch/ClockMock.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.core.watcher.watch; import org.elasticsearch.common.unit.TimeValue; -import org.joda.time.DateTime; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; +import java.time.ZonedDateTime; /** * A clock that can be modified for testing. @@ -58,8 +58,8 @@ public Instant instant() { return wrappedClock.instant(); } - public synchronized void setTime(DateTime now) { - setTime(Instant.ofEpochMilli(now.getMillis())); + public synchronized void setTime(ZonedDateTime now) { + setTime(now.toInstant()); } private void setTime(Instant now) { diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/watcher/support/xcontent/WatcherXContentParserTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/watcher/support/xcontent/WatcherXContentParserTests.java index 39e4ffad8af28..7d489a2f1df98 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/watcher/support/xcontent/WatcherXContentParserTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/watcher/support/xcontent/WatcherXContentParserTests.java @@ -14,11 +14,12 @@ import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherXContentParser; -import org.joda.time.DateTime; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.is; -import static org.joda.time.DateTimeZone.UTC; public class WatcherXContentParserTests extends ESTestCase { @@ -34,11 +35,13 @@ public void testThatRedactedSecretsThrowException() throws Exception { assertThat(xContentParser.currentName(), is(fieldName)); xContentParser.nextToken(); assertThat(xContentParser.currentToken(), is(XContentParser.Token.VALUE_STRING)); - WatcherXContentParser parser = new WatcherXContentParser(xContentParser, DateTime.now(UTC), null, false); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + + WatcherXContentParser parser = new WatcherXContentParser(xContentParser, now, null, false); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> WatcherXContentParser.secretOrNull(parser)); assertThat(e.getMessage(), is("found redacted password in field [" + fieldName + "]")); } } } -} \ No newline at end of file +} diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java index d5eea54a80c85..6648241d82a3b 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java @@ -176,12 +176,12 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.YearlySchedule; import org.elasticsearch.xpack.watcher.trigger.schedule.engine.TickerScheduleTriggerEngine; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.io.UncheckedIOException; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -609,7 +609,7 @@ static void validAutoCreateIndex(Settings settings, Logger logger) { List indices = new ArrayList<>(); indices.add(".watches"); indices.add(".triggered_watches"); - DateTime now = new DateTime(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); indices.add(HistoryStoreField.getHistoryIndexNameForTime(now)); indices.add(HistoryStoreField.getHistoryIndexNameForTime(now.plusDays(1))); indices.add(HistoryStoreField.getHistoryIndexNameForTime(now.plusMonths(1))); @@ -645,7 +645,7 @@ static void validAutoCreateIndex(Settings settings, Logger logger) { logger.warn("the [action.auto_create_index] setting is configured to be restrictive [{}]. " + " for the next 6 months daily history indices are allowed to be created, but please make sure" + " that any future history indices after 6 months with the pattern " + - "[.watcher-history-YYYY.MM.dd] are allowed to be created", value); + "[.watcher-history-yyyy.MM.dd] are allowed to be created", value); } // These are all old templates from pre 6.0 era, that need to be deleted diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/WatcherIndexingListener.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/WatcherIndexingListener.java index 1f2ddb4ed07a6..48e8dd7813e19 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/WatcherIndexingListener.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/WatcherIndexingListener.java @@ -29,10 +29,12 @@ import org.elasticsearch.xpack.watcher.trigger.TriggerService; import org.elasticsearch.xpack.watcher.watch.WatchParser; import org.elasticsearch.xpack.watcher.watch.WatchStoreUtils; -import org.joda.time.DateTime; import java.io.IOException; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -45,7 +47,6 @@ import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING; import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED; -import static org.joda.time.DateTimeZone.UTC; /** * This index listener ensures, that watches that are being indexed are put into the trigger service @@ -101,7 +102,7 @@ void setConfiguration(Configuration configuration) { @Override public Engine.Index preIndex(ShardId shardId, Engine.Index operation) { if (isWatchDocument(shardId.getIndexName(), operation.type())) { - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = Instant.ofEpochMilli(clock.millis()).atZone(ZoneOffset.UTC); try { Watch watch = parser.parseWithSecrets(operation.id(), true, operation.source(), now, XContentType.JSON, operation.getIfSeqNo(), operation.getIfPrimaryTerm()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/ExecutableIndexAction.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/ExecutableIndexAction.java index a156e68a4b1ed..82ac6f8d6d7f5 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/ExecutableIndexAction.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/ExecutableIndexAction.java @@ -26,9 +26,9 @@ import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.support.ArrayObjectIterator; -import org.joda.time.DateTime; import java.io.IOException; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; @@ -158,7 +158,7 @@ Action.Result indexBulk(Iterable list, String actionId, WatchExecutionContext ct } } - private Map addTimestampToDocument(Map data, DateTime executionTime) { + private Map addTimestampToDocument(Map data, ZonedDateTime executionTime) { if (action.executionTimeField != null) { data = mutableMap(data); data.put(action.executionTimeField, WatcherDateTimeUtils.formatDate(executionTime)); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/IndexAction.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/IndexAction.java index 1b9bc373aae47..c6a8375937374 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/IndexAction.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/IndexAction.java @@ -11,15 +11,16 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.xpack.core.watcher.actions.Action; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneId; import java.util.Objects; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; @@ -33,7 +34,7 @@ public class IndexAction implements Action { @Nullable final String docId; @Nullable final String executionTimeField; @Nullable final TimeValue timeout; - @Nullable final DateTimeZone dynamicNameTimeZone; + @Nullable final ZoneId dynamicNameTimeZone; @Nullable final RefreshPolicy refreshPolicy; private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(IndexAction.class)); @@ -41,7 +42,7 @@ public class IndexAction implements Action { public IndexAction(@Nullable String index, @Nullable String docType, @Nullable String docId, @Nullable String executionTimeField, - @Nullable TimeValue timeout, @Nullable DateTimeZone dynamicNameTimeZone, @Nullable RefreshPolicy refreshPolicy) { + @Nullable TimeValue timeout, @Nullable ZoneId dynamicNameTimeZone, @Nullable RefreshPolicy refreshPolicy) { this.index = index; this.docType = docType; this.docId = docId; @@ -72,7 +73,7 @@ public String getExecutionTimeField() { return executionTimeField; } - public DateTimeZone getDynamicNameTimeZone() { + public ZoneId getDynamicNameTimeZone() { return dynamicNameTimeZone; } @@ -132,7 +133,7 @@ public static IndexAction parse(String watchId, String actionId, XContentParser String docId = null; String executionTimeField = null; TimeValue timeout = null; - DateTimeZone dynamicNameTimeZone = null; + ZoneId dynamicNameTimeZone = null; RefreshPolicy refreshPolicy = null; String currentFieldName = null; @@ -167,7 +168,7 @@ public static IndexAction parse(String watchId, String actionId, XContentParser timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString()); } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) { if (token == XContentParser.Token.VALUE_STRING) { - dynamicNameTimeZone = DateTimeZone.forID(parser.text()); + dynamicNameTimeZone = DateUtils.of(parser.text()); } else { throw new ElasticsearchParseException("could not parse [{}] action for watch [{}]. failed to parse [{}]. must be " + "a string value (e.g. 'UTC' or '+01:00').", TYPE, watchId, currentFieldName); @@ -274,7 +275,7 @@ public static class Builder implements Action.Builder { String docId; String executionTimeField; TimeValue timeout; - DateTimeZone dynamicNameTimeZone; + ZoneId dynamicNameTimeZone; RefreshPolicy refreshPolicy; private Builder(String index, String docType) { @@ -297,7 +298,7 @@ public Builder setTimeout(TimeValue writeTimeout) { return this; } - public Builder setDynamicNameTimeZone(DateTimeZone dynamicNameTimeZone) { + public Builder setDynamicNameTimeZone(ZoneId dynamicNameTimeZone) { this.dynamicNameTimeZone = dynamicNameTimeZone; return this; } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/AbstractCompareCondition.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/AbstractCompareCondition.java index 7b0c176927d8d..2e68475dbed72 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/AbstractCompareCondition.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/AbstractCompareCondition.java @@ -5,17 +5,17 @@ */ package org.elasticsearch.xpack.watcher.condition; +import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.xpack.core.watcher.condition.ExecutableCondition; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; -import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.xpack.watcher.support.Variables; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; @@ -47,8 +47,8 @@ protected Object resolveConfiguredValue(Map resolvedValues, Map< Matcher matcher = DATE_MATH_PATTERN.matcher((String) configuredValue); if (matcher.matches()) { String dateMath = matcher.group(1); - configuredValue = WatcherDateTimeUtils.parseDateMath(dateMath, DateTimeZone.UTC, clock); - resolvedValues.put(dateMath, WatcherDateTimeUtils.formatDate((DateTime) configuredValue)); + configuredValue = WatcherDateTimeUtils.parseDateMath(dateMath, ZoneOffset.UTC, clock); + resolvedValues.put(dateMath, WatcherDateTimeUtils.formatDate((ZonedDateTime) configuredValue)); } else { // checking if the given value is a path expression matcher = PATH_PATTERN.matcher((String) configuredValue); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/LenientCompare.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/LenientCompare.java index 0594b6c8cf097..1c59c26df38e7 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/LenientCompare.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/LenientCompare.java @@ -6,9 +6,10 @@ package org.elasticsearch.xpack.watcher.condition; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Objects; public class LenientCompare { @@ -53,9 +54,9 @@ public static Integer compare(Object v1, Object v2) { } // special case for date/times. If v1 is not a dateTime, we'll try to convert it to a datetime - if (v2 instanceof DateTime) { - if (v1 instanceof DateTime) { - return ((DateTime) v1).compareTo((DateTime) v2); + if (v2 instanceof ZonedDateTime) { + if (v1 instanceof ZonedDateTime) { + return ((ZonedDateTime) v1).compareTo((ZonedDateTime) v2); } if (v1 instanceof String) { try { @@ -64,12 +65,12 @@ public static Integer compare(Object v1, Object v2) { return null; } } else if (v1 instanceof Number) { - v1 = new DateTime(((Number) v1).longValue(), DateTimeZone.UTC); + v1 = Instant.ofEpochMilli(((Number) v1).longValue()).atZone(ZoneOffset.UTC); } else { // cannot convert to date... return null; } - return ((DateTime) v1).compareTo((DateTime) v2); + return ((ZonedDateTime) v1).compareTo((ZonedDateTime) v2); } if (v1.getClass() != v2.getClass() || Comparable.class.isAssignableFrom(v1.getClass())) { diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ExecutionService.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ExecutionService.java index 3950b05034eb4..237da4ae6ae1e 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ExecutionService.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ExecutionService.java @@ -53,10 +53,11 @@ import org.elasticsearch.xpack.watcher.Watcher; import org.elasticsearch.xpack.watcher.history.HistoryStore; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; import java.io.IOException; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -72,7 +73,6 @@ import static org.elasticsearch.xpack.core.ClientHelper.WATCHER_ORIGIN; import static org.elasticsearch.xpack.core.ClientHelper.stashWithOrigin; -import static org.joda.time.DateTimeZone.UTC; public class ExecutionService { @@ -233,7 +233,7 @@ private Tuple, List> createTrigg final LinkedList triggeredWatches = new LinkedList<>(); final LinkedList contexts = new LinkedList<>(); - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); for (TriggerEvent event : events) { GetResponse response = getWatch(event.jobName()); if (response.isExists() == false) { @@ -484,7 +484,7 @@ public void executeTriggeredWatches(Collection triggeredWatches) historyStore.forcePut(record); triggeredWatchStore.delete(triggeredWatch.id()); } else { - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); TriggeredExecutionContext ctx = new TriggeredExecutionContext(triggeredWatch.id().watchId(), now, triggeredWatch.triggerEvent(), defaultThrottlePeriod, true); executeAsync(ctx, triggeredWatch); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ManualExecutionContext.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ManualExecutionContext.java index abf1e5aec0da4..9a795faea6bad 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ManualExecutionContext.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ManualExecutionContext.java @@ -15,9 +15,9 @@ import org.elasticsearch.xpack.core.watcher.input.Input; import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.watcher.trigger.manual.ManualTriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; @@ -29,7 +29,7 @@ public class ManualExecutionContext extends WatchExecutionContext { private final boolean recordExecution; private final boolean knownWatch; - ManualExecutionContext(Watch watch, boolean knownWatch, DateTime executionTime, ManualTriggerEvent triggerEvent, + ManualExecutionContext(Watch watch, boolean knownWatch, ZonedDateTime executionTime, ManualTriggerEvent triggerEvent, TimeValue defaultThrottlePeriod, Input.Result inputResult, Condition.Result conditionResult, Map actionModes, boolean recordExecution) throws Exception { @@ -113,7 +113,7 @@ public static class Builder { private final boolean knownWatch; private final ManualTriggerEvent triggerEvent; private final TimeValue defaultThrottlePeriod; - protected DateTime executionTime; + protected ZonedDateTime executionTime; private boolean recordExecution = false; private Map actionModes = new HashMap<>(); private Input.Result inputResult; @@ -127,7 +127,7 @@ private Builder(Watch watch, boolean knownWatch, ManualTriggerEvent triggerEvent this.defaultThrottlePeriod = defaultThrottlePeriod; } - public Builder executionTime(DateTime executionTime) { + public Builder executionTime(ZonedDateTime executionTime) { this.executionTime = executionTime; return this; } @@ -164,7 +164,7 @@ public Builder withCondition(Condition.Result conditionResult) { public ManualExecutionContext build() throws Exception { if (executionTime == null) { - executionTime = DateTime.now(DateTimeZone.UTC); + executionTime = ZonedDateTime.now(ZoneOffset.UTC); } ManualExecutionContext context = new ManualExecutionContext(watch, knownWatch, executionTime, triggerEvent, defaultThrottlePeriod, inputResult, conditionResult, unmodifiableMap(actionModes), recordExecution); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/TriggeredExecutionContext.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/TriggeredExecutionContext.java index 41486a7f810e1..39bbf1cab87e1 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/TriggeredExecutionContext.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/TriggeredExecutionContext.java @@ -8,17 +8,19 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; -import org.joda.time.DateTime; + +import java.time.ZonedDateTime; public class TriggeredExecutionContext extends WatchExecutionContext { private final boolean overrideOnConflict; - public TriggeredExecutionContext(String watchId, DateTime executionTime, TriggerEvent triggerEvent, TimeValue defaultThrottlePeriod) { + public TriggeredExecutionContext(String watchId, ZonedDateTime executionTime, TriggerEvent triggerEvent, + TimeValue defaultThrottlePeriod) { this(watchId, executionTime, triggerEvent, defaultThrottlePeriod, false); } - TriggeredExecutionContext(String watchId, DateTime executionTime, TriggerEvent triggerEvent, TimeValue defaultThrottlePeriod, + TriggeredExecutionContext(String watchId, ZonedDateTime executionTime, TriggerEvent triggerEvent, TimeValue defaultThrottlePeriod, boolean overrideOnConflict) { super(watchId, executionTime, triggerEvent, defaultThrottlePeriod); this.overrideOnConflict = overrideOnConflict; diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/history/HistoryStore.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/history/HistoryStore.java index d5007061cb631..42f5f79a37de2 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/history/HistoryStore.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/history/HistoryStore.java @@ -19,10 +19,10 @@ import org.elasticsearch.xpack.core.watcher.history.WatchRecord; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherParams; import org.elasticsearch.xpack.watcher.watch.WatchStoreUtils; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import static org.elasticsearch.xpack.core.watcher.support.Exceptions.ioException; @@ -80,7 +80,7 @@ public void forcePut(WatchRecord watchRecord) { * @return true, if history store is ready to be started */ public static boolean validate(ClusterState state) { - String currentIndex = HistoryStoreField.getHistoryIndexNameForTime(DateTime.now(DateTimeZone.UTC)); + String currentIndex = HistoryStoreField.getHistoryIndexNameForTime(ZonedDateTime.now(ZoneOffset.UTC)); IndexMetaData indexMetaData = WatchStoreUtils.getConcreteIndex(currentIndex, state.metaData()); return indexMetaData == null || (indexMetaData.getState() == IndexMetaData.State.OPEN && state.routingTable().index(indexMetaData.getIndex()).allPrimaryShardsActive()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/search/SearchInput.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/search/SearchInput.java index e8acf1eae0889..a0eda322b593d 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/search/SearchInput.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/search/SearchInput.java @@ -8,6 +8,7 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -15,9 +16,9 @@ import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneId; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -33,10 +34,10 @@ public class SearchInput implements Input { private final WatcherSearchTemplateRequest request; @Nullable private final Set extractKeys; @Nullable private final TimeValue timeout; - @Nullable private final DateTimeZone dynamicNameTimeZone; + @Nullable private final ZoneId dynamicNameTimeZone; public SearchInput(WatcherSearchTemplateRequest request, @Nullable Set extractKeys, - @Nullable TimeValue timeout, @Nullable DateTimeZone dynamicNameTimeZone) { + @Nullable TimeValue timeout, @Nullable ZoneId dynamicNameTimeZone) { this.request = request; this.extractKeys = extractKeys; this.timeout = timeout; @@ -82,7 +83,7 @@ public TimeValue getTimeout() { return timeout; } - public DateTimeZone getDynamicNameTimeZone() { + public ZoneId getDynamicNameTimeZone() { return dynamicNameTimeZone; } @@ -109,7 +110,7 @@ public static SearchInput parse(String watchId, XContentParser parser) throws IO WatcherSearchTemplateRequest request = null; Set extract = null; TimeValue timeout = null; - DateTimeZone dynamicNameTimeZone = null; + ZoneId dynamicNameTimeZone = null; String currentFieldName = null; XContentParser.Token token; @@ -145,7 +146,7 @@ public static SearchInput parse(String watchId, XContentParser parser) throws IO timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString()); } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) { if (token == XContentParser.Token.VALUE_STRING) { - dynamicNameTimeZone = DateTimeZone.forID(parser.text()); + dynamicNameTimeZone = DateUtils.of(parser.text()); } else { throw new ElasticsearchParseException("could not parse [{}] input for watch [{}]. failed to parse [{}]. must be a " + "string value (e.g. 'UTC' or '+01:00').", TYPE, watchId, currentFieldName); @@ -201,7 +202,7 @@ public static class Builder implements Input.Builder { private final WatcherSearchTemplateRequest request; private final Set extractKeys = new HashSet<>(); private TimeValue timeout; - private DateTimeZone dynamicNameTimeZone; + private ZoneId dynamicNameTimeZone; private Builder(WatcherSearchTemplateRequest request) { this.request = request; @@ -222,7 +223,7 @@ public Builder timeout(TimeValue readTimeout) { return this; } - public Builder dynamicNameTimeZone(DateTimeZone dynamicNameTimeZone) { + public Builder dynamicNameTimeZone(ZoneId dynamicNameTimeZone) { this.dynamicNameTimeZone = dynamicNameTimeZone; return this; } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java index afa8795e1cb5a..5a2e2986285c3 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java @@ -8,16 +8,22 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.time.DateFormatter; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.xcontent.ToXContentFragment; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import javax.mail.MessagingException; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -26,20 +32,15 @@ import java.util.Locale; import java.util.Map; -import javax.mail.MessagingException; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - import static java.util.Collections.unmodifiableMap; public class Email implements ToXContentObject { - + private static final DateFormatter DATE_TIME_FORMATTER = DateFormatter.forPattern("strict_date_time").withZone(ZoneOffset.UTC); final String id; final Address from; final AddressList replyTo; final Priority priority; - final DateTime sentDate; + final ZonedDateTime sentDate; final AddressList to; final AddressList cc; final AddressList bcc; @@ -48,7 +49,7 @@ public class Email implements ToXContentObject { final String htmlBody; final Map attachments; - public Email(String id, Address from, AddressList replyTo, Priority priority, DateTime sentDate, + public Email(String id, Address from, AddressList replyTo, Priority priority, ZonedDateTime sentDate, AddressList to, AddressList cc, AddressList bcc, String subject, String textBody, String htmlBody, Map attachments) { @@ -56,7 +57,7 @@ public Email(String id, Address from, AddressList replyTo, Priority priority, Da this.from = from; this.replyTo = replyTo; this.priority = priority; - this.sentDate = sentDate != null ? sentDate : new DateTime(DateTimeZone.UTC); + this.sentDate = sentDate != null ? sentDate : ZonedDateTime.now(ZoneOffset.UTC); this.to = to; this.cc = cc; this.bcc = bcc; @@ -82,7 +83,7 @@ public Priority priority() { return priority; } - public DateTime sentDate() { + public ZonedDateTime sentDate() { return sentDate; } @@ -196,7 +197,7 @@ public static Email parse(XContentParser parser) throws IOException{ } else if (Field.PRIORITY.match(currentFieldName, parser.getDeprecationHandler())) { email.priority(Email.Priority.resolve(parser.text())); } else if (Field.SENT_DATE.match(currentFieldName, parser.getDeprecationHandler())) { - email.sentDate(new DateTime(parser.text(), DateTimeZone.UTC)); + email.sentDate(DateFormatters.from(DATE_TIME_FORMATTER.parse(parser.text()))); } else if (Field.SUBJECT.match(currentFieldName, parser.getDeprecationHandler())) { email.subject(parser.text()); } else if (Field.BODY.match(currentFieldName, parser.getDeprecationHandler())) { @@ -233,7 +234,7 @@ public static class Builder { private Address from; private AddressList replyTo; private Priority priority; - private DateTime sentDate; + private ZonedDateTime sentDate; private AddressList to; private AddressList cc; private AddressList bcc; @@ -289,7 +290,7 @@ public Builder priority(Priority priority) { return this; } - public Builder sentDate(DateTime sentDate) { + public Builder sentDate(ZonedDateTime sentDate) { this.sentDate = sentDate; return this; } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Profile.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Profile.java index b59ee070d7f24..9d4a70dc034d0 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Profile.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Profile.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.sql.Date; import java.util.Locale; import javax.mail.Message; @@ -182,7 +183,7 @@ static MimeMessage createCommon(Email email, Session session) throws MessagingEx if (email.priority != null) { email.priority.applyTo(message); } - message.setSentDate(email.sentDate.toDate()); + message.setSentDate(Date.from(email.sentDate.toInstant())); message.setRecipients(Message.RecipientType.TO, email.to.toArray()); if (email.cc != null) { message.setRecipients(Message.RecipientType.CC, email.cc.toArray()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/support/Variables.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/support/Variables.java index 485d1426b8e90..a05ba07c098a2 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/support/Variables.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/support/Variables.java @@ -9,7 +9,6 @@ import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.watch.Payload; -import java.time.Instant; import java.time.ZoneOffset; import java.util.HashMap; import java.util.Map; @@ -38,7 +37,7 @@ public static Map createCtx(WatchExecutionContext ctx, Payload p ctxModel.put(ID, ctx.id().value()); ctxModel.put(WATCH_ID, ctx.id().watchId()); ctxModel.put(EXECUTION_TIME, - new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(ctx.executionTime().getMillis()), ZoneOffset.UTC)); + new JodaCompatibleZonedDateTime(ctx.executionTime().toInstant(), ZoneOffset.UTC)); ctxModel.put(TRIGGER, ctx.triggerEvent().data()); if (payload != null) { ctxModel.put(PAYLOAD, payload.data()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/search/SearchTransform.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/search/SearchTransform.java index b7d57a67c6a06..83a1cc179430d 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/search/SearchTransform.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/search/SearchTransform.java @@ -8,6 +8,7 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; +import org.elasticsearch.common.time.DateUtils; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; @@ -15,9 +16,9 @@ import org.elasticsearch.xpack.core.watcher.transform.Transform; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneId; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; @@ -27,9 +28,9 @@ public class SearchTransform implements Transform { private final WatcherSearchTemplateRequest request; @Nullable private final TimeValue timeout; - @Nullable private final DateTimeZone dynamicNameTimeZone; + @Nullable private final ZoneId dynamicNameTimeZone; - public SearchTransform(WatcherSearchTemplateRequest request, @Nullable TimeValue timeout, @Nullable DateTimeZone dynamicNameTimeZone) { + public SearchTransform(WatcherSearchTemplateRequest request, @Nullable TimeValue timeout, @Nullable ZoneId dynamicNameTimeZone) { this.request = request; this.timeout = timeout; this.dynamicNameTimeZone = dynamicNameTimeZone; @@ -48,7 +49,7 @@ public TimeValue getTimeout() { return timeout; } - public DateTimeZone getDynamicNameTimeZone() { + public ZoneId getDynamicNameTimeZone() { return dynamicNameTimeZone; } @@ -91,7 +92,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws public static SearchTransform parse(String watchId, XContentParser parser) throws IOException { WatcherSearchTemplateRequest request = null; TimeValue timeout = null; - DateTimeZone dynamicNameTimeZone = null; + ZoneId dynamicNameTimeZone = null; String currentFieldName = null; XContentParser.Token token; @@ -112,7 +113,7 @@ public static SearchTransform parse(String watchId, XContentParser parser) throw timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString()); } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) { if (token == XContentParser.Token.VALUE_STRING) { - dynamicNameTimeZone = DateTimeZone.forID(parser.text()); + dynamicNameTimeZone = DateUtils.of(parser.text()); } else { throw new ElasticsearchParseException("could not parse [{}] transform for watch [{}]. failed to parse [{}]. must be a" + " string value (e.g. 'UTC' or '+01:00').", TYPE, watchId, currentFieldName); @@ -167,7 +168,7 @@ public static class Builder implements Transform.Builder { private final WatcherSearchTemplateRequest request; private TimeValue timeout; - private DateTimeZone dynamicNameTimeZone; + private ZoneId dynamicNameTimeZone; public Builder(WatcherSearchTemplateRequest request) { this.request = request; @@ -178,7 +179,7 @@ public Builder timeout(TimeValue readTimeout) { return this; } - public Builder dynamicNameTimeZone(DateTimeZone dynamicNameTimeZone) { + public Builder dynamicNameTimeZone(ZoneId dynamicNameTimeZone) { this.dynamicNameTimeZone = dynamicNameTimeZone; return this; } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/ack/TransportAckWatchAction.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/ack/TransportAckWatchAction.java index 229c146f24017..6683f085fe228 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/ack/TransportAckWatchAction.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/ack/TransportAckWatchAction.java @@ -34,16 +34,16 @@ import org.elasticsearch.xpack.core.watcher.watch.WatchField; import org.elasticsearch.xpack.watcher.transport.actions.WatcherTransportAction; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xpack.core.ClientHelper.WATCHER_ORIGIN; import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin; -import static org.joda.time.DateTimeZone.UTC; public class TransportAckWatchAction extends WatcherTransportAction { @@ -83,7 +83,7 @@ protected void doExecute(AckWatchRequest request, ActionListener listener) { try { - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); UpdateRequest updateRequest = new UpdateRequest(Watch.INDEX, Watch.DOC_TYPE, request.getWatchId()); updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); XContentBuilder builder = activateWatchBuilder(request.isActivate(), now); @@ -93,7 +93,7 @@ protected void doExecute(ActivateWatchRequest request, ActionListener entry : request.getActionModes().entrySet()) { ctxBuilder.actionMode(entry.getKey(), entry.getValue()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/get/TransportGetWatchAction.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/get/TransportGetWatchAction.java index 214a083210c8b..85f899b915e6e 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/get/TransportGetWatchAction.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/get/TransportGetWatchAction.java @@ -26,14 +26,14 @@ import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.watcher.transport.actions.WatcherTransportAction; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xpack.core.ClientHelper.WATCHER_ORIGIN; import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin; -import static org.joda.time.DateTimeZone.UTC; public class TransportGetWatchAction extends WatcherTransportAction { @@ -62,7 +62,7 @@ protected void doExecute(GetWatchRequest request, ActionListener listener) { try { - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); boolean isUpdate = request.getVersion() > 0 || request.getIfSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO; Watch watch = parser.parseWithSecrets(request.getId(), false, request.getSource(), now, request.xContentType(), isUpdate, request.getIfSeqNo(), request.getIfPrimaryTerm()); + watch.setState(request.isActive(), now); // ensure we only filter for the allowed headers diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEngine.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEngine.java index 0c6b39c476b84..94a16f44615df 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEngine.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEngine.java @@ -11,17 +11,17 @@ import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; import org.elasticsearch.xpack.watcher.trigger.TriggerEngine; import org.elasticsearch.xpack.watcher.trigger.TriggerService; -import org.joda.time.DateTime; import java.io.IOException; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import static org.elasticsearch.xpack.core.watcher.support.Exceptions.illegalArgument; -import static org.joda.time.DateTimeZone.UTC; public abstract class ScheduleTriggerEngine implements TriggerEngine { @@ -49,19 +49,19 @@ public void register(Consumer> consumer) { @Override public ScheduleTriggerEvent simulateEvent(String jobId, @Nullable Map data, TriggerService service) { - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); if (data == null) { return new ScheduleTriggerEvent(jobId, now, now); } Object value = data.get(ScheduleTriggerEvent.Field.TRIGGERED_TIME.getPreferredName()); - DateTime triggeredTime = value != null ? WatcherDateTimeUtils.convertToDate(value, clock) : now; + ZonedDateTime triggeredTime = value != null ? WatcherDateTimeUtils.convertToDate(value, clock) : now; if (triggeredTime == null) { throw illegalArgument("could not simulate schedule event. could not convert provided triggered time [{}] to date/time", value); } value = data.get(ScheduleTriggerEvent.Field.SCHEDULED_TIME.getPreferredName()); - DateTime scheduledTime = value != null ? WatcherDateTimeUtils.convertToDate(value, clock) : triggeredTime; + ZonedDateTime scheduledTime = value != null ? WatcherDateTimeUtils.convertToDate(value, clock) : triggeredTime; if (scheduledTime == null) { throw illegalArgument("could not simulate schedule event. could not convert provided scheduled time [{}] to date/time", value); } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEvent.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEvent.java index 513a1b95adfbe..5359745fd94ab 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEvent.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEvent.java @@ -12,27 +12,25 @@ import org.elasticsearch.script.JodaCompatibleZonedDateTime; import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils; import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; import java.time.Clock; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; public class ScheduleTriggerEvent extends TriggerEvent { - private final DateTime scheduledTime; + private final ZonedDateTime scheduledTime; - public ScheduleTriggerEvent(DateTime triggeredTime, DateTime scheduledTime) { + public ScheduleTriggerEvent(ZonedDateTime triggeredTime, ZonedDateTime scheduledTime) { this(null, triggeredTime, scheduledTime); } - public ScheduleTriggerEvent(String jobName, DateTime triggeredTime, DateTime scheduledTime) { + public ScheduleTriggerEvent(String jobName, ZonedDateTime triggeredTime, ZonedDateTime scheduledTime) { super(jobName, triggeredTime); this.scheduledTime = scheduledTime; data.put(Field.SCHEDULED_TIME.getPreferredName(), - new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(scheduledTime.getMillis()), ZoneOffset.UTC)); + new JodaCompatibleZonedDateTime(scheduledTime.toInstant(), ZoneOffset.UTC)); } @Override @@ -40,7 +38,7 @@ public String type() { return ScheduleTrigger.TYPE; } - public DateTime scheduledTime() { + public ZonedDateTime scheduledTime() { return scheduledTime; } @@ -60,8 +58,8 @@ public void recordDataXContent(XContentBuilder builder, Params params) throws IO } public static ScheduleTriggerEvent parse(XContentParser parser, String watchId, String context, Clock clock) throws IOException { - DateTime triggeredTime = null; - DateTime scheduledTime = null; + ZonedDateTime triggeredTime = null; + ZonedDateTime scheduledTime = null; String currentFieldName = null; XContentParser.Token token; @@ -70,7 +68,7 @@ public static ScheduleTriggerEvent parse(XContentParser parser, String watchId, currentFieldName = parser.currentName(); } else if (Field.TRIGGERED_TIME.match(currentFieldName, parser.getDeprecationHandler())) { try { - triggeredTime = WatcherDateTimeUtils.parseDateMath(currentFieldName, parser, DateTimeZone.UTC, clock); + triggeredTime = WatcherDateTimeUtils.parseDateMath(currentFieldName, parser, ZoneOffset.UTC, clock); } catch (ElasticsearchParseException pe) { //Failed to parse as a date try datemath parsing throw new ElasticsearchParseException("could not parse [{}] trigger event for [{}] for watch [{}]. failed to parse " + @@ -78,7 +76,7 @@ public static ScheduleTriggerEvent parse(XContentParser parser, String watchId, } } else if (Field.SCHEDULED_TIME.match(currentFieldName, parser.getDeprecationHandler())) { try { - scheduledTime = WatcherDateTimeUtils.parseDateMath(currentFieldName, parser, DateTimeZone.UTC, clock); + scheduledTime = WatcherDateTimeUtils.parseDateMath(currentFieldName, parser, ZoneOffset.UTC, clock); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException("could not parse [{}] trigger event for [{}] for watch [{}]. failed to parse " + "date field [{}]", pe, ScheduleTriggerEngine.TYPE, context, watchId, currentFieldName); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleTriggerEngine.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleTriggerEngine.java index 2ba64c8ddbaa4..af68324c7c80a 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleTriggerEngine.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleTriggerEngine.java @@ -19,9 +19,11 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEngine; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -32,7 +34,6 @@ import java.util.concurrent.CountDownLatch; import static org.elasticsearch.common.settings.Setting.positiveTimeSetting; -import static org.joda.time.DateTimeZone.UTC; public class TickerScheduleTriggerEngine extends ScheduleTriggerEngine { @@ -109,9 +110,10 @@ void checkJobs() { for (ActiveSchedule schedule : schedules.values()) { long scheduledTime = schedule.check(triggeredTime); if (scheduledTime > 0) { - DateTime triggeredDateTime = new DateTime(triggeredTime, UTC); - DateTime scheduledDateTime = new DateTime(scheduledTime, UTC); - logger.debug("triggered job [{}] at [{}] (scheduled time was [{}])", schedule.name, triggeredDateTime, scheduledDateTime); + ZonedDateTime triggeredDateTime = utcDateTimeAtEpochMillis(triggeredTime); + ZonedDateTime scheduledDateTime = utcDateTimeAtEpochMillis(scheduledTime); + logger.debug("triggered job [{}] at [{}] (scheduled time was [{}])", schedule.name, + triggeredDateTime, scheduledDateTime); events.add(new ScheduleTriggerEvent(schedule.name, triggeredDateTime, scheduledDateTime)); if (events.size() >= 1000) { notifyListeners(events); @@ -124,6 +126,10 @@ void checkJobs() { } } + private ZonedDateTime utcDateTimeAtEpochMillis(long triggeredTime) { + return Instant.ofEpochMilli(triggeredTime).atZone(ZoneOffset.UTC); + } + // visible for testing Map getSchedules() { return Collections.unmodifiableMap(schedules); @@ -181,7 +187,7 @@ class Ticker extends Thread { @Override public void run() { while (active) { - logger.trace("checking jobs [{}]", new DateTime(clock.millis(), UTC)); + logger.trace("checking jobs [{}]", clock.instant().atZone(ZoneOffset.UTC)); checkJobs(); try { sleep(tickInterval.millis()); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalTool.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalTool.java index 9ebc3adc291a1..28b2a363ceba3 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalTool.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalTool.java @@ -11,12 +11,13 @@ import org.elasticsearch.cli.LoggingAwareCommand; import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.UserException; +import org.elasticsearch.common.time.DateFormatter; import org.elasticsearch.xpack.core.scheduler.Cron; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; import java.util.Locale; @@ -27,10 +28,12 @@ public static void main(String[] args) throws Exception { exit(new CronEvalTool().main(args, Terminal.DEFAULT)); } - private static final DateTimeFormatter UTC_FORMATTER = DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss") - .withZone(DateTimeZone.UTC).withLocale(Locale.ROOT); - private static final DateTimeFormatter LOCAL_FORMATTER = DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z") - .withZone(DateTimeZone.forTimeZone(null)); + private static final DateFormatter UTC_FORMATTER = DateFormatter.forPattern("EEE, d MMM yyyy HH:mm:ss") + .withZone(ZoneOffset.UTC) + .withLocale(Locale.ROOT); + + private static final DateFormatter LOCAL_FORMATTER = DateFormatter.forPattern("EEE, d MMM yyyy HH:mm:ss Z") + .withZone(ZoneId.systemDefault()); private final OptionSpec countOption; private final OptionSpec arguments; @@ -57,18 +60,18 @@ void execute(Terminal terminal, String expression, int count) throws Exception { Cron.validate(expression); terminal.println("Valid!"); - final DateTime date = DateTime.now(DateTimeZone.UTC); - final boolean isLocalTimeUTC = UTC_FORMATTER.getZone().equals(LOCAL_FORMATTER.getZone()); + final ZonedDateTime date = ZonedDateTime.now(ZoneOffset.UTC); + final boolean isLocalTimeUTC = UTC_FORMATTER.zone().equals(LOCAL_FORMATTER.zone()); if (isLocalTimeUTC) { - terminal.println("Now is [" + UTC_FORMATTER.print(date) + "] in UTC"); + terminal.println("Now is [" + UTC_FORMATTER.format(date) + "] in UTC"); } else { - terminal.println("Now is [" + UTC_FORMATTER.print(date) + "] in UTC, local time is [" + LOCAL_FORMATTER.print(date) + "]"); + terminal.println("Now is [" + UTC_FORMATTER.format(date) + "] in UTC, local time is [" + LOCAL_FORMATTER.format(date) + "]"); } terminal.println("Here are the next " + count + " times this cron expression will trigger:"); Cron cron = new Cron(expression); - long time = date.getMillis(); + long time = date.toInstant().toEpochMilli(); for (int i = 0; i < count; i++) { long prevTime = time; @@ -76,16 +79,19 @@ void execute(Terminal terminal, String expression, int count) throws Exception { if (time < 0) { if (i == 0) { throw new UserException(ExitCodes.OK, "Could not compute future times since [" - + UTC_FORMATTER.print(prevTime) + "] " + "(perhaps the cron expression only points to times in the past?)"); + + UTC_FORMATTER.format(Instant.ofEpochMilli(prevTime)) + "] " + "(perhaps the cron expression only points to " + + "times in the" + + " " + + "past?)"); } break; } if (isLocalTimeUTC) { - terminal.println((i + 1) + ".\t" + UTC_FORMATTER.print(time)); + terminal.println((i + 1) + ".\t" + UTC_FORMATTER.format(Instant.ofEpochMilli(time))); } else { - terminal.println((i + 1) + ".\t" + UTC_FORMATTER.print(time)); - terminal.println("\t" + LOCAL_FORMATTER.print(time)); + terminal.println((i + 1) + ".\t" + UTC_FORMATTER.format(Instant.ofEpochMilli(time))); + terminal.println("\t" + LOCAL_FORMATTER.format(Instant.ofEpochMilli(time))); } } } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/watch/WatchParser.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/watch/WatchParser.java index 55f65943a1381..c77285bdd4088 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/watch/WatchParser.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/watch/WatchParser.java @@ -33,11 +33,12 @@ import org.elasticsearch.xpack.watcher.input.InputRegistry; import org.elasticsearch.xpack.watcher.input.none.ExecutableNoneInput; import org.elasticsearch.xpack.watcher.trigger.TriggerService; -import org.joda.time.DateTime; import java.io.IOException; import java.io.InputStream; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -46,7 +47,6 @@ import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; import static org.elasticsearch.xpack.core.watcher.support.Exceptions.ioException; -import static org.joda.time.DateTimeZone.UTC; public class WatchParser { @@ -75,11 +75,13 @@ public WatchParser(TriggerService triggerService, ActionRegistry actionRegistry, public Watch parse(String name, boolean includeStatus, BytesReference source, XContentType xContentType, long sourceSeqNo, long sourcePrimaryTerm) throws IOException { - return parse(name, includeStatus, false, source, new DateTime(clock.millis(), UTC), xContentType, false, + + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); + return parse(name, includeStatus, false, source, now, xContentType, false, sourceSeqNo, sourcePrimaryTerm); } - public Watch parse(String name, boolean includeStatus, BytesReference source, DateTime now, + public Watch parse(String name, boolean includeStatus, BytesReference source, ZonedDateTime now, XContentType xContentType, long sourceSeqNo, long sourcePrimaryTerm) throws IOException { return parse(name, includeStatus, false, source, now, xContentType, false, sourceSeqNo, sourcePrimaryTerm); } @@ -95,19 +97,19 @@ public Watch parse(String name, boolean includeStatus, BytesReference source, Da * of the watch in the system will be use secrets for sensitive data. * */ - public Watch parseWithSecrets(String id, boolean includeStatus, BytesReference source, DateTime now, + public Watch parseWithSecrets(String id, boolean includeStatus, BytesReference source, ZonedDateTime now, XContentType xContentType, boolean allowRedactedPasswords, long sourceSeqNo, long sourcePrimaryTerm ) throws IOException { return parse(id, includeStatus, true, source, now, xContentType, allowRedactedPasswords, sourceSeqNo, sourcePrimaryTerm); } - public Watch parseWithSecrets(String id, boolean includeStatus, BytesReference source, DateTime now, + public Watch parseWithSecrets(String id, boolean includeStatus, BytesReference source, ZonedDateTime now, XContentType xContentType, long sourceSeqNo, long sourcePrimaryTerm) throws IOException { return parse(id, includeStatus, true, source, now, xContentType, false, sourceSeqNo, sourcePrimaryTerm); } - private Watch parse(String id, boolean includeStatus, boolean withSecrets, BytesReference source, DateTime now, + private Watch parse(String id, boolean includeStatus, boolean withSecrets, BytesReference source, ZonedDateTime now, XContentType xContentType, boolean allowRedactedPasswords, long sourceSeqNo, long sourcePrimaryTerm) throws IOException { if (logger.isTraceEnabled()) { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherIndexingListenerTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherIndexingListenerTests.java index 7a37f71e22f28..b6e5e53e2483d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherIndexingListenerTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherIndexingListenerTests.java @@ -38,10 +38,11 @@ import org.elasticsearch.xpack.watcher.WatcherIndexingListener.ShardAllocationConfiguration; import org.elasticsearch.xpack.watcher.trigger.TriggerService; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; import org.junit.Before; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; @@ -61,7 +62,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; @@ -140,7 +140,7 @@ public void testPreIndex() throws Exception { Engine.Index returnedOperation = listener.preIndex(shardId, operation); assertThat(returnedOperation, is(operation)); - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); verify(parser).parseWithSecrets(eq(operation.id()), eq(true), eq(BytesArray.EMPTY), eq(now), anyObject(), anyLong(), anyLong()); if (isNewWatch) { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherServiceTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherServiceTests.java index 96186905c26ad..3b8d844cc1241 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherServiceTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherServiceTests.java @@ -56,11 +56,11 @@ import org.elasticsearch.xpack.watcher.trigger.TriggerEngine; import org.elasticsearch.xpack.watcher.trigger.TriggerService; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import org.mockito.ArgumentCaptor; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -190,7 +190,7 @@ void stopExecutor() { if (active) { activeWatchCount++; } - WatchStatus.State state = new WatchStatus.State(active, DateTime.now(DateTimeZone.UTC)); + WatchStatus.State state = new WatchStatus.State(active, ZonedDateTime.now(ZoneOffset.UTC)); WatchStatus watchStatus = mock(WatchStatus.class); Watch watch = mock(Watch.class); when(watchStatus.state()).thenReturn(state); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/ActionWrapperTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/ActionWrapperTests.java index a81868f05edfc..e3a41062caee5 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/ActionWrapperTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/ActionWrapperTests.java @@ -16,9 +16,9 @@ import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.core.watcher.watch.WatchStatus; import org.elasticsearch.xpack.watcher.condition.NeverCondition; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,7 @@ public class ActionWrapperTests extends ESTestCase { - private DateTime now = DateTime.now(DateTimeZone.UTC); + private ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); private Watch watch = mock(Watch.class); @SuppressWarnings("unchecked") private ExecutableAction executableAction = mock(ExecutableAction.class); @@ -72,4 +72,4 @@ private ActionStatus createActionStatus(State state) { ActionStatus.Execution execution = ActionStatus.Execution.successful(now); return new ActionStatus(ackStatus, execution, execution, null); } -} \ No newline at end of file +} diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailActionTests.java index a8cb1f7d2fac1..037a70602ba33 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailActionTests.java @@ -45,16 +45,14 @@ import org.elasticsearch.xpack.watcher.notification.email.attachment.HttpRequestAttachment; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.test.MockTextTemplateEngine; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -131,8 +129,8 @@ public void testExecute() throws Exception { Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); - DateTime now = DateTime.now(DateTimeZone.UTC); - JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(now.getMillis()), ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(now.toInstant(), ZoneOffset.UTC); Wid wid = new Wid("watch1", now); WatchExecutionContext ctx = mockExecutionContextBuilder("watch1") @@ -536,7 +534,7 @@ public void testThatOneFailedEmailAttachmentResultsInActionFailure() throws Exce ExecutableEmailAction executableEmailAction = new EmailActionFactory(Settings.EMPTY, emailService, engine, emailAttachmentsParser) .parseExecutable(randomAlphaOfLength(3), randomAlphaOfLength(7), parser); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); WatchExecutionContext ctx = mockExecutionContextBuilder("watch1") @@ -562,7 +560,7 @@ private EmailActionFactory createEmailActionFactory() { } private WatchExecutionContext createWatchExecutionContext() { - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); return mockExecutionContextBuilder("watch1") diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/hipchat/HipChatActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/hipchat/HipChatActionTests.java index 640eb76769ea0..f36f00b54dd8c 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/hipchat/HipChatActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/hipchat/HipChatActionTests.java @@ -31,13 +31,11 @@ import org.elasticsearch.xpack.watcher.notification.hipchat.HipChatMessage; import org.elasticsearch.xpack.watcher.notification.hipchat.HipChatService; import org.elasticsearch.xpack.watcher.notification.hipchat.SentMessages; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import java.io.IOException; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -80,8 +78,8 @@ public void testExecute() throws Exception { Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); - DateTime now = DateTime.now(DateTimeZone.UTC); - JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(now.getMillis()), ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(now.toInstant(), ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext ctx = mockExecutionContextBuilder(wid.watchId()) 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 85f17fbd0e8d1..da702e01047bd 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 @@ -31,10 +31,11 @@ import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.test.WatcherTestUtils; -import org.joda.time.DateTime; import org.junit.Before; import org.mockito.ArgumentCaptor; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -52,7 +53,6 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -161,7 +161,7 @@ public void testUsingParameterIdWithBulkOrIdFieldThrowsIllegalState() { final ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, client, TimeValue.timeValueSeconds(30), TimeValue.timeValueSeconds(30)); final Map docWithId = MapBuilder.newMapBuilder().put("foo", "bar").put("_id", "0").immutableMap(); - final DateTime executionTime = DateTime.now(UTC); + final ZonedDateTime executionTime = ZonedDateTime.now(ZoneOffset.UTC); // using doc_id with bulk fails regardless of using ID expectThrows(IllegalStateException.class, () -> { @@ -285,7 +285,7 @@ public void testIndexActionExecuteSingleDoc() throws Exception { refreshPolicy); ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, client, TimeValue.timeValueSeconds(30), TimeValue.timeValueSeconds(30)); - DateTime executionTime = DateTime.now(UTC); + ZonedDateTime executionTime = ZonedDateTime.now(ZoneOffset.UTC); Payload payload; if (customId && docIdAsParam == false) { @@ -344,7 +344,7 @@ public void testFailureResult() throws Exception { docs.add(Collections.singletonMap("foo", Collections.singletonMap("foo", "bar"))); Payload payload = new Payload.Simple(Collections.singletonMap("_doc", docs)); - WatchExecutionContext ctx = WatcherTestUtils.mockExecutionContext("_id", DateTime.now(UTC), payload); + WatchExecutionContext ctx = WatcherTestUtils.mockExecutionContext("_id", ZonedDateTime.now(ZoneOffset.UTC), payload); ArgumentCaptor captor = ArgumentCaptor.forClass(BulkRequest.class); PlainActionFuture listener = PlainActionFuture.newFuture(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/ExecutableJiraActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/ExecutableJiraActionTests.java index afc3d4dfb5582..76c8a07749eb6 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/ExecutableJiraActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/ExecutableJiraActionTests.java @@ -14,19 +14,19 @@ import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.execution.Wid; import org.elasticsearch.xpack.core.watcher.watch.Payload; +import org.elasticsearch.xpack.watcher.common.http.BasicAuth; import org.elasticsearch.xpack.watcher.common.http.HttpClient; import org.elasticsearch.xpack.watcher.common.http.HttpProxy; import org.elasticsearch.xpack.watcher.common.http.HttpRequest; import org.elasticsearch.xpack.watcher.common.http.HttpResponse; -import org.elasticsearch.xpack.watcher.common.http.BasicAuth; import org.elasticsearch.xpack.watcher.common.text.TextTemplate; import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine; import org.elasticsearch.xpack.watcher.notification.jira.JiraAccount; import org.elasticsearch.xpack.watcher.notification.jira.JiraService; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.mockito.ArgumentCaptor; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -77,7 +77,7 @@ public void testProxy() throws Exception { JiraService service = mock(JiraService.class); when(service.getAccount(eq("account1"))).thenReturn(account); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext ctx = mockExecutionContextBuilder(wid.watchId()) @@ -288,7 +288,7 @@ private JiraAction.Simulated simulateExecution(Map actionFields, } private WatchExecutionContext createWatchExecutionContext() { - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); return mockExecutionContextBuilder("watch1") diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionTests.java index b4ce31f75778e..f0458831072bd 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionTests.java @@ -32,9 +32,9 @@ import org.elasticsearch.xpack.watcher.notification.jira.JiraIssue; import org.elasticsearch.xpack.watcher.notification.jira.JiraService; import org.elasticsearch.xpack.watcher.support.Variables; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; @@ -238,7 +238,7 @@ public void testExecute() throws Exception { Map data = new HashMap<>(); Payload payload = new Payload.Simple(data); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext context = mockExecutionContextBuilder(wid.watchId()) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/logging/LoggingActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/logging/LoggingActionTests.java index b735d94f58949..5ecfe8019d0b5 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/logging/LoggingActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/logging/LoggingActionTests.java @@ -19,12 +19,11 @@ import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine; import org.elasticsearch.xpack.watcher.notification.email.Attachment; import org.elasticsearch.xpack.watcher.test.WatcherTestUtils; -import org.joda.time.DateTime; import org.junit.Before; import java.io.IOException; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; @@ -37,7 +36,6 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -57,8 +55,8 @@ public void init() throws IOException { } public void testExecute() throws Exception { - final DateTime now = DateTime.now(UTC); - JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(now.getMillis()), ZoneOffset.UTC); + final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(now.toInstant(), ZoneOffset.UTC); WatchExecutionContext ctx = WatcherTestUtils.mockExecutionContextBuilder("_watch_id") .time("_watch_id", now) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/pagerduty/PagerDutyActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/pagerduty/PagerDutyActionTests.java index c238cfb292300..4034f032f977d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/pagerduty/PagerDutyActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/pagerduty/PagerDutyActionTests.java @@ -30,12 +30,10 @@ import org.elasticsearch.xpack.watcher.notification.pagerduty.PagerDutyAccount; import org.elasticsearch.xpack.watcher.notification.pagerduty.PagerDutyService; import org.elasticsearch.xpack.watcher.notification.pagerduty.SentEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -80,8 +78,8 @@ public void testExecute() throws Exception { Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); - DateTime now = DateTime.now(DateTimeZone.UTC); - JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(now.getMillis()), ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(now.toInstant(), ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext ctx = mockExecutionContextBuilder(wid.watchId()) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/ExecutableSlackActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/ExecutableSlackActionTests.java index e78f1afc548c5..956c924d1bab1 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/ExecutableSlackActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/ExecutableSlackActionTests.java @@ -20,10 +20,11 @@ import org.elasticsearch.xpack.watcher.notification.slack.SlackService; import org.elasticsearch.xpack.watcher.notification.slack.message.SlackMessage; import org.elasticsearch.xpack.watcher.test.MockTextTemplateEngine; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.mockito.ArgumentCaptor; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; + import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContextBuilder; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.eq; @@ -49,7 +50,7 @@ public void testProxy() throws Exception { SlackService service = mock(SlackService.class); when(service.getAccount(eq("account1"))).thenReturn(account); - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext ctx = mockExecutionContextBuilder(wid.watchId()) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/SlackActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/SlackActionTests.java index 5a6ce3c4aa189..b14545c97d4fb 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/SlackActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/slack/SlackActionTests.java @@ -28,12 +28,10 @@ import org.elasticsearch.xpack.watcher.notification.slack.message.SlackMessage; import org.elasticsearch.xpack.watcher.notification.slack.message.SlackMessageDefaults; import org.elasticsearch.xpack.watcher.notification.slack.message.SlackMessageTests; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -77,8 +75,8 @@ public void testExecute() throws Exception { Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); - DateTime now = DateTime.now(DateTimeZone.UTC); - JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(now.getMillis()), ZoneOffset.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + JodaCompatibleZonedDateTime jodaJavaNow = new JodaCompatibleZonedDateTime(now.toInstant(), ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); WatchExecutionContext ctx = mockExecutionContextBuilder(wid.watchId()) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/AckThrottlerTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/AckThrottlerTests.java index 787c2c7ce51f8..685461737845f 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/AckThrottlerTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/AckThrottlerTests.java @@ -13,21 +13,20 @@ import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.core.watcher.watch.WatchStatus; -import org.joda.time.DateTime; -import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import static org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils.formatDate; import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AckThrottlerTests extends ESTestCase { public void testWhenAcked() throws Exception { - DateTime timestamp = new DateTime(Clock.systemUTC().millis(), UTC); + ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); WatchExecutionContext ctx = mockExecutionContext("_watch", Payload.EMPTY); Watch watch = ctx.watch(); ActionStatus actionStatus = mock(ActionStatus.class); @@ -43,7 +42,7 @@ public void testWhenAcked() throws Exception { } public void testThrottleWhenAwaitsSuccessfulExecution() throws Exception { - DateTime timestamp = new DateTime(Clock.systemUTC().millis(), UTC); + ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); WatchExecutionContext ctx = mockExecutionContext("_watch", Payload.EMPTY); Watch watch = ctx.watch(); ActionStatus actionStatus = mock(ActionStatus.class); @@ -59,7 +58,7 @@ public void testThrottleWhenAwaitsSuccessfulExecution() throws Exception { } public void testThrottleWhenAckable() throws Exception { - DateTime timestamp = new DateTime(Clock.systemUTC().millis(), UTC); + ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); WatchExecutionContext ctx = mockExecutionContext("_watch", Payload.EMPTY); Watch watch = ctx.watch(); ActionStatus actionStatus = mock(ActionStatus.class); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/ActionThrottleTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/ActionThrottleTests.java index ccb25de61e46e..7e5a8b989105d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/ActionThrottleTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/ActionThrottleTests.java @@ -8,6 +8,7 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.protocol.xpack.watcher.PutWatchRequest; @@ -15,7 +16,6 @@ import org.elasticsearch.xpack.core.watcher.client.WatchSourceBuilder; import org.elasticsearch.xpack.core.watcher.execution.ActionExecutionMode; import org.elasticsearch.xpack.core.watcher.execution.ExecutionState; -import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchRequestBuilder; import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.xpack.core.watcher.watch.Watch; @@ -32,10 +32,10 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.IntervalSchedule; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.HashSet; import java.util.List; import java.util.Locale; @@ -134,7 +134,7 @@ private Map executeWatch(String id) { } public void testDifferentThrottlePeriods() throws Exception { - timeWarp().clock().setTime(DateTime.now(DateTimeZone.UTC)); + timeWarp().clock().setTime(ZonedDateTime.now(ZoneOffset.UTC)); WatchSourceBuilder watchSourceBuilder = watchBuilder() .trigger(schedule(interval("60m"))); @@ -185,11 +185,11 @@ public void testDefaultThrottlePeriod() throws Exception { watchSourceBuilder.buildAsBytes(XContentType.JSON), XContentType.JSON)).actionGet(); refresh(Watch.INDEX); - timeWarp().clock().setTime(new DateTime(DateTimeZone.UTC)); + timeWarp().clock().setTime(ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); @@ -201,7 +201,7 @@ public void testDefaultThrottlePeriod() throws Exception { executeWatchResponse = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); @@ -214,7 +214,7 @@ public void testDefaultThrottlePeriod() throws Exception { try { ExecuteWatchResponse executeWatchResponse1 = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); @@ -238,11 +238,11 @@ public void testWatchThrottlePeriod() throws Exception { watchSourceBuilder.buildAsBytes(XContentType.JSON), XContentType.JSON)).actionGet(); refresh(Watch.INDEX); - timeWarp().clock().setTime(new DateTime(DateTimeZone.UTC)); + timeWarp().clock().setTime(ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); @@ -253,7 +253,7 @@ public void testWatchThrottlePeriod() throws Exception { executeWatchResponse = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); @@ -267,7 +267,7 @@ public void testWatchThrottlePeriod() throws Exception { //Since the default throttle period is 5 seconds but we have overridden the period in the watch this should trigger ExecuteWatchResponse executeWatchResponse1 = watcherClient().prepareExecuteWatch("_id") .setTriggerEvent(new ManualTriggerEvent("execute_id", - new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)))) + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)))) .setActionMode("default_global_throttle", ActionExecutionMode.SIMULATE) .setRecordExecution(true) .get(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/PeriodThrottlerTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/PeriodThrottlerTests.java index 89ef2e23ccca3..4b41a27013e55 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/PeriodThrottlerTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/throttler/PeriodThrottlerTests.java @@ -13,9 +13,10 @@ import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.core.watcher.watch.WatchStatus; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.CoreMatchers.nullValue; @@ -32,7 +33,7 @@ public void testBelowPeriodSuccessful() throws Exception { WatchExecutionContext ctx = mockExecutionContext("_name", Payload.EMPTY); ActionStatus actionStatus = mock(ActionStatus.class); - DateTime now = new DateTime(Clock.systemUTC().millis()); + ZonedDateTime now = Clock.systemUTC().instant().atZone(ZoneOffset.UTC); when(actionStatus.lastSuccessfulExecution()) .thenReturn(ActionStatus.Execution.successful(now.minusSeconds((int) period.seconds() - 1))); WatchStatus status = mock(WatchStatus.class); @@ -53,7 +54,7 @@ public void testAbovePeriod() throws Exception { WatchExecutionContext ctx = mockExecutionContext("_name", Payload.EMPTY); ActionStatus actionStatus = mock(ActionStatus.class); - DateTime now = new DateTime(Clock.systemUTC().millis()); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); when(actionStatus.lastSuccessfulExecution()) .thenReturn(ActionStatus.Execution.successful(now.minusSeconds((int) period.seconds() + 1))); WatchStatus status = mock(WatchStatus.class); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java index e8b59ca9e6310..439eb45f0159f 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java @@ -38,11 +38,12 @@ import org.elasticsearch.xpack.watcher.test.WatcherTestUtils; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; import org.hamcrest.Matchers; -import org.joda.time.DateTime; import org.junit.Before; import javax.mail.internet.AddressException; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Map; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; @@ -56,7 +57,6 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.core.Is.is; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -227,8 +227,10 @@ public void testThatSelectingProxyWorks() throws Exception { ExecutableWebhookAction executable = new ExecutableWebhookAction(action, logger, httpClient, templateEngine); String watchId = "test_url_encode" + randomAlphaOfLength(10); - TriggeredExecutionContext ctx = new TriggeredExecutionContext(watchId, new DateTime(UTC), - new ScheduleTriggerEvent(watchId, new DateTime(UTC), new DateTime(UTC)), timeValueSeconds(5)); + ScheduleTriggerEvent triggerEvent = new ScheduleTriggerEvent(watchId, ZonedDateTime.now(ZoneOffset.UTC), + ZonedDateTime.now(ZoneOffset.UTC)); + TriggeredExecutionContext ctx = new TriggeredExecutionContext(watchId, ZonedDateTime.now(ZoneOffset.UTC), + triggerEvent, timeValueSeconds(5)); Watch watch = createWatch(watchId); ctx.ensureWatchExists(() -> watch); executable.execute("_id", ctx, new Payload.Simple()); @@ -252,8 +254,10 @@ public void testValidUrls() throws Exception { ExecutableWebhookAction executable = new ExecutableWebhookAction(action, logger, client, templateEngine); - TriggeredExecutionContext ctx = new TriggeredExecutionContext(watchId, new DateTime(UTC), - new ScheduleTriggerEvent(watchId, new DateTime(UTC), new DateTime(UTC)), timeValueSeconds(5)); + ScheduleTriggerEvent triggerEvent = new ScheduleTriggerEvent(watchId, ZonedDateTime.now(ZoneOffset.UTC), + ZonedDateTime.now(ZoneOffset.UTC)); + TriggeredExecutionContext ctx = new TriggeredExecutionContext(watchId, ZonedDateTime.now(ZoneOffset.UTC), + triggerEvent, timeValueSeconds(5)); Watch watch = createWatch(watchId); ctx.ensureWatchExists(() -> watch); Action.Result result = executable.execute("_id", ctx, new Payload.Simple()); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ArrayCompareConditionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ArrayCompareConditionTests.java index 8b072dddc7e31..11a69bc7d2221 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ArrayCompareConditionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ArrayCompareConditionTests.java @@ -14,12 +14,12 @@ import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.watch.ClockMock; import org.elasticsearch.xpack.core.watcher.watch.Payload; -import org.joda.time.DateTime; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.io.IOException; import java.time.Clock; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -158,7 +158,7 @@ public void testExecuteDateMath() { List values = new ArrayList<>(numberOfValues); for (int i = 0; i < numberOfValues; i++) { clock.fastForwardSeconds(1); - values.add(new DateTime(clock.millis())); + values.add(clock.instant().atZone(ZoneOffset.UTC)); } ArrayCompareCondition condition = new ArrayCompareCondition("ctx.payload.value", "", op, value, quantifier, clock); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/CompareConditionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/CompareConditionTests.java index 7c3abd1d808e9..16cd09fcae756 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/CompareConditionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/CompareConditionTests.java @@ -15,9 +15,10 @@ import org.elasticsearch.xpack.core.watcher.watch.ClockMock; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.condition.CompareCondition.Op; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Locale; @@ -178,7 +179,7 @@ public void testExecuteDateMath() throws Exception { Op op = met ? randomFrom(CompareCondition.Op.GT, CompareCondition.Op.GTE, CompareCondition.Op.NOT_EQ) : randomFrom(CompareCondition.Op.LT, CompareCondition.Op.LTE, CompareCondition.Op.EQ); String value = "<{now-1d}>"; - DateTime payloadValue = new DateTime(clock.millis()); + ZonedDateTime payloadValue = clock.instant().atZone(ZoneId.systemDefault()); CompareCondition condition = new CompareCondition("ctx.payload.value", op, value, clock); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.Simple("value", payloadValue)); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java index 72ab01009bb99..4a7b50c2b18de 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java @@ -33,11 +33,11 @@ import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.test.WatcherMockScriptPlugin; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -194,7 +194,7 @@ public void testScriptConditionAccessCtx() throws Exception { mockScript("ctx.trigger.scheduled_time.toInstant().toEpochMill() < new Date().time"), scriptService); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); - WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), + WatchExecutionContext ctx = mockExecutionContext("_name", ZonedDateTime.now(ZoneOffset.UTC), new Payload.XContent(response, ToXContent.EMPTY_PARAMS)); Thread.sleep(10); assertThat(condition.execute(ctx).met(), is(true)); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java index 5f2b807f10757..321cf979bca73 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java @@ -69,12 +69,14 @@ import org.elasticsearch.xpack.watcher.trigger.manual.ManualTriggerEvent; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.xpack.watcher.watch.WatchParser; -import org.joda.time.DateTime; import org.junit.Before; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -98,8 +100,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.joda.time.DateTime.now; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; @@ -164,7 +164,7 @@ public void testExecute() throws Exception { when(getResponse.isExists()).thenReturn(true); mockGetWatchResponse(client, "_id", getResponse); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); when(parser.parseWithSecrets(eq(watch.id()), eq(true), any(), any(), any(), anyLong(), anyLong())).thenReturn(watch); @@ -268,7 +268,7 @@ public void testExecuteFailedInput() throws Exception { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); when(parser.parseWithSecrets(eq(watch.id()), eq(true), any(), any(), any(), anyLong(), anyLong())).thenReturn(watch); @@ -337,7 +337,7 @@ public void testExecuteFailedCondition() throws Exception { when(getResponse.isExists()).thenReturn(true); mockGetWatchResponse(client, "_id", getResponse); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); when(parser.parseWithSecrets(eq(watch.id()), eq(true), any(), any(), any(), anyLong(), anyLong())).thenReturn(watch); @@ -402,7 +402,7 @@ public void testExecuteFailedWatchTransform() throws Exception { when(getResponse.isExists()).thenReturn(true); mockGetWatchResponse(client, "_id", getResponse); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); when(parser.parseWithSecrets(eq(watch.id()), eq(true), any(), any(), any(), anyLong(), anyLong())).thenReturn(watch); @@ -467,7 +467,7 @@ public void testExecuteFailedActionTransform() throws Exception { mockGetWatchResponse(client, "_id", getResponse); when(parser.parseWithSecrets(eq(watch.id()), eq(true), any(), any(), any(), anyLong(), anyLong())).thenReturn(watch); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); @@ -543,7 +543,7 @@ public void testExecuteFailedActionTransform() throws Exception { } public void testExecuteInner() throws Exception { - DateTime now = now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); @@ -595,7 +595,8 @@ public void testExecuteInner() throws Exception { when(action.execute("_action", context, payload)).thenReturn(actionResult); ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionCondition, actionTransform, action); - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), singletonMap("_action", new ActionStatus(now))); + ZonedDateTime time = clock.instant().atZone(ZoneOffset.UTC); + WatchStatus watchStatus = new WatchStatus(time, singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -619,7 +620,7 @@ public void testExecuteInner() throws Exception { } public void testExecuteInnerThrottled() throws Exception { - DateTime now = now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); @@ -643,7 +644,8 @@ public void testExecuteInnerThrottled() throws Exception { ExecutableAction action = mock(ExecutableAction.class); when(action.type()).thenReturn("_type"); ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionCondition, actionTransform, action); - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), singletonMap("_action", new ActionStatus(now))); + ZonedDateTime time = clock.instant().atZone(ZoneOffset.UTC); + WatchStatus watchStatus = new WatchStatus(time, singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -671,7 +673,7 @@ public void testExecuteInnerThrottled() throws Exception { } public void testExecuteInnerConditionNotMet() throws Exception { - DateTime now = now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); @@ -705,7 +707,8 @@ public void testExecuteInnerConditionNotMet() throws Exception { ExecutableAction action = mock(ExecutableAction.class); when(action.type()).thenReturn("_type"); ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionCondition, actionTransform, action); - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), singletonMap("_action", new ActionStatus(now))); + ZonedDateTime time = clock.instant().atZone(ZoneOffset.UTC); + WatchStatus watchStatus = new WatchStatus(time, singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -733,7 +736,7 @@ public void testExecuteInnerConditionNotMet() throws Exception { } public void testExecuteInnerConditionNotMetDueToException() throws Exception { - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); when(watch.id()).thenReturn(getTestName()); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); @@ -761,7 +764,8 @@ public void testExecuteInnerConditionNotMetDueToException() throws Exception { when(action.type()).thenReturn("_type"); when(action.logger()).thenReturn(logger); ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionCondition, actionTransform, action); - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), singletonMap("_action", new ActionStatus(now))); + ZonedDateTime time = clock.instant().atZone(ZoneOffset.UTC); + WatchStatus watchStatus = new WatchStatus(time, singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -789,7 +793,7 @@ public void testExecuteInnerConditionNotMetDueToException() throws Exception { } public void testExecuteConditionNotMet() throws Exception { - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), now, event, timeValueSeconds(5)); @@ -809,7 +813,8 @@ public void testExecuteConditionNotMet() throws Exception { ExecutableAction action = mock(ExecutableAction.class); ActionWrapper actionWrapper = new ActionWrapper("_action", throttler, actionCondition, actionTransform, action); - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), singletonMap("_action", new ActionStatus(now))); + ZonedDateTime time = clock.instant().atZone(ZoneOffset.UTC); + WatchStatus watchStatus = new WatchStatus(time, singletonMap("_action", new ActionStatus(now))); when(watch.input()).thenReturn(input); when(watch.condition()).thenReturn(condition); @@ -833,7 +838,7 @@ public void testExecuteConditionNotMet() throws Exception { public void testThatTriggeredWatchDeletionWorksOnExecutionRejection() throws Exception { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("foo"); - WatchStatus status = new WatchStatus(DateTime.now(UTC), Collections.emptyMap()); + WatchStatus status = new WatchStatus(ZonedDateTime.now(ZoneOffset.UTC), Collections.emptyMap()); when(watch.status()).thenReturn(status); GetResponse getResponse = mock(GetResponse.class); when(getResponse.isExists()).thenReturn(true); @@ -845,9 +850,10 @@ public void testThatTriggeredWatchDeletionWorksOnExecutionRejection() throws Exc doThrow(new EsRejectedExecutionException()).when(executor).execute(any()); doThrow(new ElasticsearchException("whatever")).when(historyStore).forcePut(any()); - Wid wid = new Wid(watch.id(), now()); + Wid wid = new Wid(watch.id(), ZonedDateTime.now(ZoneOffset.UTC)); - TriggeredWatch triggeredWatch = new TriggeredWatch(wid, new ScheduleTriggerEvent(now() ,now())); + TriggeredWatch triggeredWatch = new TriggeredWatch(wid, + new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC) ,ZonedDateTime.now(ZoneOffset.UTC))); executionService.executeTriggeredWatches(Collections.singleton(triggeredWatch)); verify(triggeredWatchStore, times(1)).delete(wid); @@ -863,7 +869,7 @@ public void testThatTriggeredWatchDeletionHappensOnlyIfWatchExists() throws Exce when(getResponse.isExists()).thenReturn(true); mockGetWatchResponse(client, "_id", getResponse); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); WatchExecutionContext context = ManualExecutionContext.builder(watch, false, new ManualTriggerEvent("foo", event), timeValueSeconds(5)).build(); @@ -900,7 +906,7 @@ public void testThatSingleWatchCannotBeExecutedConcurrently() throws Exception { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); when(ctx.watch()).thenReturn(watch); - Wid wid = new Wid(watch.id(), DateTime.now(UTC)); + Wid wid = new Wid(watch.id(), ZonedDateTime.now(ZoneOffset.UTC)); when(ctx.id()).thenReturn(wid); executionService.getCurrentExecutions().put("_id", new ExecutionService.WatchExecution(ctx, Thread.currentThread())); @@ -913,9 +919,9 @@ public void testThatSingleWatchCannotBeExecutedConcurrently() throws Exception { public void testExecuteWatchNotFound() throws Exception { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), - new DateTime(0, UTC), - new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), + ZonedDateTime epochZeroTime = Instant.EPOCH.atZone(ZoneOffset.UTC); + ScheduleTriggerEvent triggerEvent = new ScheduleTriggerEvent(watch.id(), epochZeroTime, epochZeroTime); + TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), epochZeroTime, triggerEvent, TimeValue.timeValueSeconds(5)); GetResponse notFoundResponse = mock(GetResponse.class); @@ -930,9 +936,9 @@ public void testExecuteWatchNotFound() throws Exception { public void testExecuteWatchIndexNotFoundException() { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), - new DateTime(0, UTC), - new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), + ZonedDateTime epochZeroTime = Instant.EPOCH.atZone(ZoneOffset.UTC); + ScheduleTriggerEvent triggerEvent = new ScheduleTriggerEvent(watch.id(), epochZeroTime, epochZeroTime); + TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), epochZeroTime, triggerEvent, TimeValue.timeValueSeconds(5)); mockGetWatchException(client, "_id", new IndexNotFoundException(".watch")); @@ -944,9 +950,10 @@ public void testExecuteWatchIndexNotFoundException() { public void testExecuteWatchParseWatchException() { Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); + ZonedDateTime epochZeroTime = Instant.EPOCH.atZone(ZoneOffset.UTC); TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), - new DateTime(0, UTC), - new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), + epochZeroTime, + new ScheduleTriggerEvent(watch.id(), epochZeroTime, epochZeroTime), TimeValue.timeValueSeconds(5)); IOException e = new IOException("something went wrong, i.e. index not found"); @@ -963,10 +970,10 @@ public void testWatchInactive() throws Exception { WatchExecutionContext ctx = mock(WatchExecutionContext.class); when(ctx.knownWatch()).thenReturn(true); WatchStatus status = mock(WatchStatus.class); - when(status.state()).thenReturn(new WatchStatus.State(false, now())); + when(status.state()).thenReturn(new WatchStatus.State(false, ZonedDateTime.now(ZoneOffset.UTC))); when(watch.status()).thenReturn(status); when(ctx.watch()).thenReturn(watch); - Wid wid = new Wid(watch.id(), DateTime.now(UTC)); + Wid wid = new Wid(watch.id(), ZonedDateTime.now(ZoneOffset.UTC)); when(ctx.id()).thenReturn(wid); GetResponse getResponse = mock(GetResponse.class); @@ -983,7 +990,7 @@ public void testWatchInactive() throws Exception { } public void testCurrentExecutionSnapshots() throws Exception { - DateTime time = DateTime.now(UTC); + ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC); int snapshotCount = randomIntBetween(2, 8); for (int i = 0; i < snapshotCount; i++) { time = time.minusSeconds(10); @@ -999,7 +1006,7 @@ public void testCurrentExecutionSnapshots() throws Exception { public void testQueuedWatches() throws Exception { Collection tasks = new ArrayList<>(); - DateTime time = DateTime.now(UTC); + ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC); int queuedWatchCount = randomIntBetween(2, 8); for (int i = 0; i < queuedWatchCount; i++) { time = time.minusSeconds(10); @@ -1016,7 +1023,7 @@ public void testQueuedWatches() throws Exception { } public void testUpdateWatchStatusDoesNotUpdateState() throws Exception { - WatchStatus status = new WatchStatus(DateTime.now(UTC), Collections.emptyMap()); + WatchStatus status = new WatchStatus(ZonedDateTime.now(ZoneOffset.UTC), Collections.emptyMap()); Watch watch = new Watch("_id", new ManualTrigger(), new ExecutableNoneInput(), InternalAlwaysCondition.INSTANCE, null, null, Collections.emptyList(), null, status, 1L, 1L); @@ -1046,7 +1053,7 @@ public void testManualWatchExecutionContextGetsAlwaysExecuted() throws Exception Watch watch = mock(Watch.class); when(watch.id()).thenReturn("_id"); - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); ManualExecutionContext ctx = ManualExecutionContext.builder(watch, true, new ManualTriggerEvent("foo", event), timeValueSeconds(5)).build(); @@ -1071,7 +1078,7 @@ public void testManualWatchExecutionContextGetsAlwaysExecuted() throws Exception when(watch.actions()).thenReturn(Collections.singletonList(actionWrapper)); WatchStatus status = mock(WatchStatus.class); - when(status.state()).thenReturn(new WatchStatus.State(false, now())); + when(status.state()).thenReturn(new WatchStatus.State(false, ZonedDateTime.now(ZoneOffset.UTC))); when(watch.status()).thenReturn(status); WatchRecord watchRecord = executionService.execute(ctx); @@ -1079,7 +1086,7 @@ public void testManualWatchExecutionContextGetsAlwaysExecuted() throws Exception } public void testLoadingWatchExecutionUser() throws Exception { - DateTime now = now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Watch watch = mock(Watch.class); WatchStatus status = mock(WatchStatus.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); @@ -1105,7 +1112,7 @@ public void testLoadingWatchExecutionUser() throws Exception { assertThat(context.getUser(), equalTo("joe")); } - private WatchExecutionContext createMockWatchExecutionContext(String watchId, DateTime executionTime) { + private WatchExecutionContext createMockWatchExecutionContext(String watchId, ZonedDateTime executionTime) { WatchExecutionContext ctx = mock(WatchExecutionContext.class); when(ctx.id()).thenReturn(new Wid(watchId, executionTime)); when(ctx.executionTime()).thenReturn(executionTime); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/TriggeredWatchStoreTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/TriggeredWatchStoreTests.java index e8e0e16b6ea4f..84d4ebd274dc0 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/TriggeredWatchStoreTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/TriggeredWatchStoreTests.java @@ -68,10 +68,10 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleRegistry; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.xpack.watcher.watch.WatchTests; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -84,7 +84,6 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; @@ -262,7 +261,7 @@ public void testFindTriggeredWatchesGoodCase() { }).when(client).execute(eq(ClearScrollAction.INSTANCE), any(), any()); assertThat(TriggeredWatchStore.validate(cs), is(true)); - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); ScheduleTriggerEvent triggerEvent = new ScheduleTriggerEvent(now, now); Watch watch1 = mock(Watch.class); @@ -393,8 +392,9 @@ public void testTriggeredWatchParser() throws Exception { WatcherSearchTemplateService searchTemplateService = mock(WatcherSearchTemplateService.class); Watch watch = WatcherTestUtils.createTestWatch("fired_test", client, httpClient, emailService, searchTemplateService, logger); - ScheduleTriggerEvent event = new ScheduleTriggerEvent(watch.id(), DateTime.now(DateTimeZone.UTC), DateTime.now(DateTimeZone.UTC)); - Wid wid = new Wid("_record", DateTime.now(DateTimeZone.UTC)); + ScheduleTriggerEvent event = new ScheduleTriggerEvent(watch.id(), ZonedDateTime.now(ZoneOffset.UTC), + ZonedDateTime.now(ZoneOffset.UTC)); + Wid wid = new Wid("_record", ZonedDateTime.now(ZoneOffset.UTC)); TriggeredWatch triggeredWatch = new TriggeredWatch(wid, event); XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); triggeredWatch.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS); @@ -413,7 +413,7 @@ public void testTriggeredWatchParser() throws Exception { } public void testPutTriggeredWatches() throws Exception { - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); int numberOfTriggeredWatches = randomIntBetween(1, 100); List triggeredWatches = new ArrayList<>(numberOfTriggeredWatches); @@ -445,7 +445,7 @@ public void testPutTriggeredWatches() throws Exception { } public void testDeleteTriggeredWatches() throws Exception { - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); doAnswer(invocation -> { BulkRequest bulkRequest = (BulkRequest) invocation.getArguments()[0]; diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/history/HistoryStoreTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/history/HistoryStoreTests.java index c12cfe380c0dc..866ec32cff0b8 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/history/HistoryStoreTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/history/HistoryStoreTests.java @@ -37,10 +37,13 @@ import org.elasticsearch.xpack.watcher.notification.jira.JiraAccount; import org.elasticsearch.xpack.watcher.notification.jira.JiraIssue; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; import org.junit.Before; import org.mockito.ArgumentCaptor; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; + import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.elasticsearch.xpack.core.watcher.history.HistoryStoreField.getHistoryIndexNameForTime; @@ -50,7 +53,6 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.IsEqual.equalTo; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -76,7 +78,7 @@ public void init() { } public void testPut() throws Exception { - DateTime now = new DateTime(0, UTC); + ZonedDateTime now = Instant.ofEpochMilli(0).atZone(ZoneOffset.UTC); Wid wid = new Wid("_name", now); String index = getHistoryIndexNameForTime(now); ScheduleTriggerEvent event = new ScheduleTriggerEvent(wid.watchId(), now, now); @@ -104,13 +106,13 @@ public void testPut() throws Exception { public void testIndexNameGeneration() { String indexTemplateVersion = INDEX_TEMPLATE_VERSION; - assertThat(getHistoryIndexNameForTime(new DateTime(0, UTC)), + assertThat(getHistoryIndexNameForTime(Instant.ofEpochMilli((long) 0).atZone(ZoneOffset.UTC)), equalTo(".watcher-history-"+ indexTemplateVersion +"-1970.01.01")); - assertThat(getHistoryIndexNameForTime(new DateTime(100000000000L, UTC)), + assertThat(getHistoryIndexNameForTime(Instant.ofEpochMilli(100000000000L).atZone(ZoneOffset.UTC)), equalTo(".watcher-history-" + indexTemplateVersion + "-1973.03.03")); - assertThat(getHistoryIndexNameForTime(new DateTime(1416582852000L, UTC)), + assertThat(getHistoryIndexNameForTime(Instant.ofEpochMilli(1416582852000L).atZone(ZoneOffset.UTC)), equalTo(".watcher-history-" + indexTemplateVersion + "-2014.11.21")); - assertThat(getHistoryIndexNameForTime(new DateTime(2833165811000L, UTC)), + assertThat(getHistoryIndexNameForTime(Instant.ofEpochMilli(2833165811000L).atZone(ZoneOffset.UTC)), equalTo(".watcher-history-" + indexTemplateVersion + "-2059.10.12")); } @@ -132,7 +134,7 @@ public void testStoreWithHideSecrets() throws Exception { JiraIssue jiraIssue = account.createIssue(singletonMap("foo", "bar"), null); ActionWrapperResult result = new ActionWrapperResult(JiraAction.TYPE, new JiraAction.Executed(jiraIssue)); - DateTime now = new DateTime(0, UTC); + ZonedDateTime now = Instant.ofEpochMilli((long) 0).atZone(ZoneOffset.UTC); Wid wid = new Wid("_name", now); Watch watch = mock(Watch.class); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/input/chain/ExecutableChainInputTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/input/chain/ExecutableChainInputTests.java index 03b9b1d993be6..72604ff7b5880 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/input/chain/ExecutableChainInputTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/input/chain/ExecutableChainInputTests.java @@ -15,10 +15,10 @@ import org.elasticsearch.xpack.core.watcher.input.Input; import org.elasticsearch.xpack.core.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.input.simple.SimpleInput; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import static org.elasticsearch.xpack.core.watcher.input.Input.Result.Status; @@ -62,7 +62,7 @@ protected XContentBuilder typeXContent(XContentBuilder builder, Params params) t } private WatchExecutionContext createWatchExecutionContext() { - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); return mockExecutionContextBuilder(wid.watchId()) .wid(wid) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailSecretsIntegrationTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailSecretsIntegrationTests.java index 02a2128e112fb..bef39298d6242 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailSecretsIntegrationTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailSecretsIntegrationTests.java @@ -24,10 +24,10 @@ import org.elasticsearch.xpack.watcher.notification.email.support.EmailServer; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.After; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -135,7 +135,7 @@ public void testEmail() throws Exception { latch.countDown(); }); - TriggerEvent triggerEvent = new ScheduleTriggerEvent(new DateTime(DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)); + TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeResponse = watcherClient.prepareExecuteWatch("_id") .setRecordExecution(false) .setTriggerEvent(triggerEvent) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailTests.java index 48dd20baa6784..60ce6775f78a2 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/EmailTests.java @@ -10,9 +10,10 @@ import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -30,7 +31,7 @@ public void testEmailParserSelfGenerated() throws Exception { Email.AddressList possibleList = new Email.AddressList(addresses); Email.AddressList replyTo = randomFrom(possibleList, null); Email.Priority priority = randomFrom(Email.Priority.values()); - DateTime sentDate = new DateTime(randomInt(), DateTimeZone.UTC); + ZonedDateTime sentDate = Instant.ofEpochMilli(randomInt()).atZone(ZoneOffset.UTC); Email.AddressList to = randomFrom(possibleList, null); Email.AddressList cc = randomFrom(possibleList, null); Email.AddressList bcc = randomFrom(possibleList, null); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/HttpEmailAttachementParserTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/HttpEmailAttachementParserTests.java index 2b0e632b0cac7..15e348a98bb1d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/HttpEmailAttachementParserTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/HttpEmailAttachementParserTests.java @@ -20,11 +20,11 @@ import org.elasticsearch.xpack.watcher.common.http.HttpRequestTemplate; import org.elasticsearch.xpack.watcher.common.http.HttpResponse; import org.elasticsearch.xpack.watcher.test.MockTextTemplateEngine; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -137,7 +137,7 @@ public void testHttpClientThrowsException() throws Exception { } private WatchExecutionContext createWatchExecutionContext() { - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid(randomAlphaOfLength(5), now); Map metadata = MapBuilder.newMapBuilder().put("_key", "_val").map(); return mockExecutionContextBuilder("watch1") diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/ReportingAttachmentParserTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/ReportingAttachmentParserTests.java index d46524b93e508..17b0498dc89fa 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/ReportingAttachmentParserTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/email/attachment/ReportingAttachmentParserTests.java @@ -18,23 +18,23 @@ import org.elasticsearch.xpack.core.watcher.execution.Wid; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherParams; import org.elasticsearch.xpack.core.watcher.watch.Payload; +import org.elasticsearch.xpack.watcher.common.http.BasicAuth; import org.elasticsearch.xpack.watcher.common.http.HttpClient; import org.elasticsearch.xpack.watcher.common.http.HttpMethod; import org.elasticsearch.xpack.watcher.common.http.HttpProxy; import org.elasticsearch.xpack.watcher.common.http.HttpRequest; import org.elasticsearch.xpack.watcher.common.http.HttpResponse; -import org.elasticsearch.xpack.watcher.common.http.BasicAuth; import org.elasticsearch.xpack.watcher.common.text.TextTemplate; import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine; import org.elasticsearch.xpack.watcher.notification.email.Attachment; import org.elasticsearch.xpack.watcher.test.MockTextTemplateEngine; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -406,7 +406,7 @@ public void testHttpProxy() throws Exception { } private WatchExecutionContext createWatchExecutionContext() { - DateTime now = DateTime.now(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); return mockExecutionContextBuilder("watch1") .wid(new Wid(randomAlphaOfLength(5), now)) .payload(new Payload.Simple()) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/VariablesTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/VariablesTests.java index 5ec2e639b9e89..7df981a5f2952 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/VariablesTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/VariablesTests.java @@ -15,23 +15,21 @@ import org.elasticsearch.xpack.watcher.test.WatcherTestUtils; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; import org.hamcrest.Matchers; -import org.joda.time.DateTime; -import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Map; import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.joda.time.DateTimeZone.UTC; public class VariablesTests extends ESTestCase { public void testCreateCtxModel() throws Exception { - DateTime scheduledTime = DateTime.now(UTC); - DateTime triggeredTime = scheduledTime.plusMillis(50); - DateTime executionTime = triggeredTime.plusMillis(50); + ZonedDateTime scheduledTime = ZonedDateTime.now(ZoneOffset.UTC); + ZonedDateTime triggeredTime = scheduledTime.toInstant().plusMillis(50).atZone(ZoneOffset.UTC); + ZonedDateTime executionTime = triggeredTime.toInstant().plusMillis(50).atZone(ZoneOffset.UTC); Payload payload = new Payload.Simple(singletonMap("payload_key", "payload_value")); Map metatdata = singletonMap("metadata_key", "metadata_value"); TriggerEvent event = new ScheduleTriggerEvent("_watch_id", triggeredTime, scheduledTime); @@ -49,7 +47,7 @@ public void testCreateCtxModel() throws Exception { assertThat(model.size(), is(1)); JodaCompatibleZonedDateTime jodaJavaExecutionTime = - new JodaCompatibleZonedDateTime(Instant.ofEpochMilli(executionTime.getMillis()), ZoneOffset.UTC); + new JodaCompatibleZonedDateTime(executionTime.toInstant(), ZoneOffset.UTC); assertThat(ObjectPath.eval("ctx", model), instanceOf(Map.class)); assertThat(ObjectPath.eval("ctx.id", model), is(wid.value())); // NOTE: we use toString() here because two ZonedDateTime are *not* equal, we need to check with isEqual diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherUtilsTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherUtilsTests.java index 7aab1d4d14504..b0d2a333838dd 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherUtilsTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherUtilsTests.java @@ -24,9 +24,9 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.watcher.support.WatcherUtils; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; @@ -46,7 +46,7 @@ public class WatcherUtilsTests extends ESTestCase { public void testFlattenModel() throws Exception { - DateTime now = new DateTime(Clock.systemUTC().millis()); + ZonedDateTime now = ZonedDateTime.now(Clock.systemUTC()); Map map = new HashMap<>(); map.put("a", singletonMap("a1", new int[] { 0, 1, 2 })); map.put("b", new String[] { "b0", "b1", "b2" }); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java index 6737de19baa13..f710531532b87 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java @@ -58,12 +58,12 @@ import org.elasticsearch.xpack.watcher.trigger.ScheduleTriggerEngineMock; import org.elasticsearch.xpack.watcher.watch.WatchParser; import org.hamcrest.Matcher; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.After; import org.junit.Before; import java.time.Clock; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -252,7 +252,7 @@ private void createWatcherIndicesOrAliases() throws Exception { assertAcked(client().admin().indices().prepareCreate(triggeredWatchIndexName)); } - String historyIndex = HistoryStoreField.getHistoryIndexNameForTime(DateTime.now(DateTimeZone.UTC)); + String historyIndex = HistoryStoreField.getHistoryIndexNameForTime(ZonedDateTime.now(ZoneOffset.UTC)); assertAcked(client().admin().indices().prepareCreate(historyIndex)); logger.info("creating watch history index [{}]", historyIndex); ensureGreen(historyIndex, watchIndexName, triggeredWatchIndexName); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatchExecutionContextMockBuilder.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatchExecutionContextMockBuilder.java index eb859baad8935..c4b046bcf9c28 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatchExecutionContextMockBuilder.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatchExecutionContextMockBuilder.java @@ -13,12 +13,12 @@ import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.core.watcher.watch.WatchStatus; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.Map; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -37,7 +37,7 @@ public WatchExecutionContextMockBuilder(String watchId) { when(ctx.watch()).thenReturn(watch); payload(Collections.emptyMap()); metadata(Collections.emptyMap()); - time(watchId, DateTime.now(UTC)); + time(watchId, ZonedDateTime.now(ZoneOffset.UTC)); } public WatchExecutionContextMockBuilder wid(Wid wid) { @@ -58,11 +58,11 @@ public WatchExecutionContextMockBuilder payload(Payload payload) { return this; } - public WatchExecutionContextMockBuilder time(String watchId, DateTime time) { + public WatchExecutionContextMockBuilder time(String watchId, ZonedDateTime time) { return executionTime(time).triggerEvent(new ScheduleTriggerEvent(watchId, time, time)); } - public WatchExecutionContextMockBuilder executionTime(DateTime time) { + public WatchExecutionContextMockBuilder executionTime(ZonedDateTime time) { when(ctx.executionTime()).thenReturn(time); return this; } diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherTestUtils.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherTestUtils.java index f2a9941ec35ed..7f7ff8c93601b 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherTestUtils.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherTestUtils.java @@ -52,10 +52,12 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.IntervalSchedule; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; import javax.mail.internet.AddressException; import java.io.IOException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -67,7 +69,6 @@ import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.ESTestCase.randomFrom; -import static org.joda.time.DateTimeZone.UTC; public final class WatcherTestUtils { @@ -97,27 +98,28 @@ public static WatcherSearchTemplateRequest templateRequest(SearchSourceBuilder s public static WatchExecutionContextMockBuilder mockExecutionContextBuilder(String watchId) { return new WatchExecutionContextMockBuilder(watchId) - .wid(new Wid(watchId, DateTime.now(UTC))); + .wid(new Wid(watchId, ZonedDateTime.now(ZoneOffset.UTC))); } public static WatchExecutionContext mockExecutionContext(String watchId, Payload payload) { return mockExecutionContextBuilder(watchId) - .wid(new Wid(watchId, DateTime.now(UTC))) + .wid(new Wid(watchId, ZonedDateTime.now(ZoneOffset.UTC))) .payload(payload) .buildMock(); } - public static WatchExecutionContext mockExecutionContext(String watchId, DateTime time, Payload payload) { + public static WatchExecutionContext mockExecutionContext(String watchId, ZonedDateTime time, Payload payload) { return mockExecutionContextBuilder(watchId) - .wid(new Wid(watchId, DateTime.now(UTC))) + .wid(new Wid(watchId, ZonedDateTime.now(ZoneOffset.UTC))) .payload(payload) .time(watchId, time) .buildMock(); } - public static WatchExecutionContext mockExecutionContext(String watchId, DateTime executionTime, TriggerEvent event, Payload payload) { + public static WatchExecutionContext mockExecutionContext(String watchId, ZonedDateTime executionTime, TriggerEvent event, + Payload payload) { return mockExecutionContextBuilder(watchId) - .wid(new Wid(watchId, DateTime.now(UTC))) + .wid(new Wid(watchId, ZonedDateTime.now(ZoneOffset.UTC))) .payload(payload) .executionTime(executionTime) .triggerEvent(event) @@ -125,6 +127,7 @@ public static WatchExecutionContext mockExecutionContext(String watchId, DateTim } public static WatchExecutionContext createWatchExecutionContext() throws Exception { + ZonedDateTime EPOCH_UTC = Instant.EPOCH.atZone(ZoneOffset.UTC); Watch watch = new Watch("test-watch", new ScheduleTrigger(new IntervalSchedule(new IntervalSchedule.Interval(1, IntervalSchedule.Interval.Unit.MINUTES))), new ExecutableSimpleInput(new SimpleInput(new Payload.Simple())), @@ -133,11 +136,10 @@ public static WatchExecutionContext createWatchExecutionContext() throws Excepti null, new ArrayList<>(), null, - new WatchStatus(new DateTime(0, UTC), emptyMap()), 1L, 1L); - TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), - new DateTime(0, UTC), - new ScheduleTriggerEvent(watch.id(), new DateTime(0, UTC), new DateTime(0, UTC)), - TimeValue.timeValueSeconds(5)); + + new WatchStatus(EPOCH_UTC, emptyMap()), 1L, 1L); + TriggeredExecutionContext context = new TriggeredExecutionContext(watch.id(), EPOCH_UTC, + new ScheduleTriggerEvent(watch.id(), EPOCH_UTC, EPOCH_UTC), TimeValue.timeValueSeconds(5)); context.ensureWatchExists(() -> watch); return context; } @@ -163,7 +165,7 @@ public static Watch createTestWatch(String watchName, Client client, HttpClient new HtmlSanitizer(Settings.EMPTY), Collections.emptyMap()); actions.add(new ActionWrapper("_email", null, null, null, executale)); - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Map statuses = new HashMap<>(); statuses.put("_webhook", new ActionStatus(now)); statuses.put("_email", new ActionStatus(now)); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/bench/ScheduleEngineTriggerBenchmark.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/bench/ScheduleEngineTriggerBenchmark.java index 183e80bf2528d..ea749d776f25d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/bench/ScheduleEngineTriggerBenchmark.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/bench/ScheduleEngineTriggerBenchmark.java @@ -77,8 +77,8 @@ protected void notifyListeners(List events) { if (running.get()) { for (TriggerEvent event : events) { ScheduleTriggerEvent scheduleTriggerEvent = (ScheduleTriggerEvent) event; - measure(total, triggerMetric, tooEarlyMetric, event.triggeredTime().getMillis(), - scheduleTriggerEvent.scheduledTime().getMillis()); + measure(total, triggerMetric, tooEarlyMetric, event.triggeredTime().toInstant().toEpochMilli(), + scheduleTriggerEvent.scheduledTime().toInstant().toEpochMilli()); } } } diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BasicWatcherTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BasicWatcherTests.java index 2b7d5706d233e..5b62bca40fb09 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BasicWatcherTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BasicWatcherTests.java @@ -11,6 +11,7 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse; import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; @@ -19,7 +20,6 @@ import org.elasticsearch.xpack.core.watcher.client.WatchSourceBuilder; import org.elasticsearch.xpack.core.watcher.client.WatcherClient; import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; -import org.elasticsearch.protocol.xpack.watcher.DeleteWatchResponse; import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.xpack.core.watcher.watch.Watch; import org.elasticsearch.xpack.watcher.condition.CompareCondition; @@ -30,9 +30,9 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.Schedules; import org.elasticsearch.xpack.watcher.trigger.schedule.support.MonthTimes; import org.elasticsearch.xpack.watcher.trigger.schedule.support.WeekTimes; -import org.joda.time.DateTime; import java.time.Clock; +import java.time.ZonedDateTime; import java.util.Collections; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; @@ -340,7 +340,7 @@ public void testPutWatchWithNegativeSchedule() throws Exception { private void testConditionSearch(WatcherSearchTemplateRequest request) throws Exception { // reset, so we don't miss event docs when we filter over the _timestamp field. - timeWarp().clock().setTime(new DateTime(Clock.systemUTC().millis())); + timeWarp().clock().setTime(ZonedDateTime.now(Clock.systemUTC())); String watchName = "_name"; assertAcked(prepareCreate("events").addMapping("event", "level", "type=text")); @@ -352,7 +352,7 @@ private void testConditionSearch(WatcherSearchTemplateRequest request) throws Ex .condition(new CompareCondition("ctx.payload.hits.total", CompareCondition.Op.GTE, 3L))) .get(); - logger.info("created watch [{}] at [{}]", watchName, new DateTime(Clock.systemUTC().millis())); + logger.info("created watch [{}] at [{}]", watchName, ZonedDateTime.now(Clock.systemUTC())); client().prepareIndex("events", "event") .setSource("level", "a") diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BootStrapTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BootStrapTests.java index 5a5c5c020dacd..6382909f96f33 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BootStrapTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/BootStrapTests.java @@ -29,9 +29,10 @@ import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; import org.hamcrest.Matchers; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @@ -52,7 +53,6 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsEqual.equalTo; -import static org.joda.time.DateTimeZone.UTC; public class BootStrapTests extends AbstractWatcherIntegrationTestCase { @@ -75,7 +75,7 @@ public void testLoadMalformedWatchRecord() throws Exception { .get(); // valid watch record: - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); Wid wid = new Wid("_id", now); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); ExecutableCondition condition = InternalAlwaysCondition.INSTANCE; @@ -198,7 +198,7 @@ public void testMixedTriggeredWatchLoading() throws Exception { stopWatcher(); - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); final int numRecords = scaledRandomIntBetween(numWatches, 128); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); for (int i = 0; i < numRecords; i++) { @@ -244,7 +244,7 @@ public void testTriggeredWatchLoading() throws Exception { stopWatcher(); - DateTime now = DateTime.now(UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); final int numRecords = scaledRandomIntBetween(2, 12); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); for (int i = 0; i < numRecords; i++) { @@ -310,7 +310,8 @@ public void testWatchRecordSavedTwice() throws Exception { // we rarely create an .watches alias in the base class assertAcked(client().admin().indices().prepareCreate(Watch.INDEX)); } - DateTime triggeredTime = new DateTime(2015, 11, 5, 0, 0, 0, 0, DateTimeZone.UTC); + LocalDateTime localDateTime = LocalDateTime.of(2015, 11, 5, 0, 0, 0, 0); + ZonedDateTime triggeredTime = ZonedDateTime.of(localDateTime,ZoneOffset.UTC); final String watchRecordIndex = HistoryStoreField.getHistoryIndexNameForTime(triggeredTime); logger.info("Stopping watcher"); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/HttpSecretsIntegrationTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/HttpSecretsIntegrationTests.java index 0de8fc1ee4bc0..60d049f4ff138 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/HttpSecretsIntegrationTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/HttpSecretsIntegrationTests.java @@ -27,11 +27,12 @@ import org.elasticsearch.xpack.watcher.condition.InternalAlwaysCondition; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import java.nio.charset.StandardCharsets; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Base64; import java.util.Map; @@ -49,7 +50,6 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; -import static org.joda.time.DateTimeZone.UTC; public class HttpSecretsIntegrationTests extends AbstractWatcherIntegrationTestCase { @@ -141,7 +141,7 @@ public void testHttpInput() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody( BytesReference.bytes(jsonBuilder().startObject().field("key", "value").endObject()).utf8ToString())); - TriggerEvent triggerEvent = new ScheduleTriggerEvent(new DateTime(UTC), new DateTime(UTC)); + TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeResponse = watcherClient.prepareExecuteWatch("_id") .setRecordExecution(false) .setTriggerEvent(triggerEvent) @@ -221,7 +221,7 @@ public void testWebhookAction() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody( BytesReference.bytes(jsonBuilder().startObject().field("key", "value").endObject()).utf8ToString())); - TriggerEvent triggerEvent = new ScheduleTriggerEvent(new DateTime(UTC), new DateTime(UTC)); + TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeResponse = watcherClient.prepareExecuteWatch("_id") .setRecordExecution(false) .setActionMode("_all", ActionExecutionMode.FORCE_EXECUTE) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatchMetadataTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatchMetadataTests.java index 7b54a043df864..1e2c1ddbc64f1 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatchMetadataTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatchMetadataTests.java @@ -7,9 +7,9 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.xpack.core.watcher.execution.ActionExecutionMode; import org.elasticsearch.xpack.core.watcher.history.HistoryStoreField; -import org.elasticsearch.common.xcontent.ObjectPath; import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; import org.elasticsearch.xpack.watcher.actions.logging.LoggingAction; @@ -19,8 +19,9 @@ import org.elasticsearch.xpack.watcher.condition.InternalAlwaysCondition; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -34,7 +35,6 @@ import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.cron; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; -import static org.joda.time.DateTimeZone.UTC; public class WatchMetadataTests extends AbstractWatcherIntegrationTestCase { @@ -84,7 +84,7 @@ public void testWatchMetadataAvailableAtExecution() throws Exception { .metadata(metadata)) .get(); - TriggerEvent triggerEvent = new ScheduleTriggerEvent(new DateTime(UTC), new DateTime(UTC)); + TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC)); ExecuteWatchResponse executeWatchResponse = watcherClient().prepareExecuteWatch("_name") .setTriggerEvent(triggerEvent).setActionMode("_all", ActionExecutionMode.SIMULATE).get(); Map result = executeWatchResponse.getRecordSource().getAsMap(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/ScheduleTriggerEngineMock.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/ScheduleTriggerEngineMock.java index 9ed7d1a3091d2..eaf952effd3c3 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/ScheduleTriggerEngineMock.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/ScheduleTriggerEngineMock.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.xpack.watcher.trigger; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.xpack.core.watcher.watch.ClockMock; @@ -15,10 +15,10 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEngine; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.joda.time.DateTime; import java.io.IOException; import java.time.Clock; +import java.time.ZonedDateTime; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; @@ -84,7 +84,7 @@ public boolean trigger(String jobName, int times, TimeValue interval) { } for (int i = 0; i < times; i++) { - DateTime now = new DateTime(clock.millis()); + ZonedDateTime now = ZonedDateTime.now(clock); logger.debug("firing watch [{}] at [{}]", jobName, now); ScheduleTriggerEvent event = new ScheduleTriggerEvent(jobName, now, now); consumers.forEach(consumer -> consumer.accept(Collections.singletonList(event))); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEventTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEventTests.java index 822dd02bd1909..f7bab1e7662d0 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEventTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTriggerEventTests.java @@ -12,6 +12,8 @@ import org.elasticsearch.test.ESTestCase; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; import static org.hamcrest.Matchers.is; @@ -29,7 +31,7 @@ public void testParserRandomDateMath() throws Exception { parser.nextToken(); ScheduleTriggerEvent scheduleTriggerEvent = ScheduleTriggerEvent.parse(parser, "_id", "_context", Clock.systemUTC()); - assertThat(scheduleTriggerEvent.scheduledTime().isAfter(0), is(true)); - assertThat(scheduleTriggerEvent.triggeredTime().isAfter(0), is(true)); + assertThat(scheduleTriggerEvent.scheduledTime().isAfter(Instant.ofEpochMilli(0).atZone(ZoneOffset.UTC)), is(true)); + assertThat(scheduleTriggerEvent.triggeredTime().isAfter(Instant.ofEpochMilli(0).atZone(ZoneOffset.UTC)), is(true)); } } diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleEngineTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleEngineTests.java index 0f6ca200cb4ab..bbca936994724 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleEngineTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/engine/TickerScheduleEngineTests.java @@ -18,10 +18,12 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.xpack.watcher.trigger.schedule.support.DayOfWeek; import org.elasticsearch.xpack.watcher.trigger.schedule.support.WeekTimes; -import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoField; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; @@ -36,7 +38,6 @@ import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.weekly; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; public class TickerScheduleEngineTests extends ESTestCase { @@ -58,7 +59,7 @@ private TickerScheduleTriggerEngine createEngine() { return new TickerScheduleTriggerEngine(settings, mock(ScheduleRegistry.class), clock); } - private void advanceClockIfNeeded(DateTime newCurrentDateTime) { + private void advanceClockIfNeeded(ZonedDateTime newCurrentDateTime) { clock.setTime(newCurrentDateTime); } @@ -95,12 +96,12 @@ public void accept(Iterable events) { }); engine.start(watches); - advanceClockIfNeeded(new DateTime(clock.millis(), UTC).plusMillis(1100)); + advanceClockIfNeeded(clock.instant().plusMillis(1100).atZone(ZoneOffset.UTC)); if (!firstLatch.await(3 * count, TimeUnit.SECONDS)) { fail("waiting too long for all watches to be triggered"); } - advanceClockIfNeeded(new DateTime(clock.millis(), UTC).plusMillis(1100)); + advanceClockIfNeeded(clock.instant().plusMillis(1100).atZone(ZoneOffset.UTC)); if (!secondLatch.await(3 * count, TimeUnit.SECONDS)) { fail("waiting too long for all watches to be triggered"); } @@ -124,15 +125,17 @@ public void accept(Iterable events) { }); int randomMinute = randomIntBetween(0, 59); - DateTime testNowTime = new DateTime(clock.millis(), UTC).withMinuteOfHour(randomMinute) - .withSecondOfMinute(59); - DateTime scheduledTime = testNowTime.plusSeconds(2); + ZonedDateTime testNowTime = clock.instant().atZone(ZoneOffset.UTC) + .with(ChronoField.MINUTE_OF_HOUR, randomMinute) + .with(ChronoField.SECOND_OF_MINUTE, 59); + + ZonedDateTime scheduledTime = testNowTime.plusSeconds(2); logger.info("Setting current time to [{}], job execution time [{}]", testNowTime, scheduledTime); clock.setTime(testNowTime); - engine.add(createWatch(name, daily().at(scheduledTime.getHourOfDay(), - scheduledTime.getMinuteOfHour()).build())); + engine.add(createWatch(name, daily().at(scheduledTime.getHour(), + scheduledTime.getMinute()).build())); advanceClockIfNeeded(scheduledTime); if (!latch.await(5, TimeUnit.SECONDS)) { @@ -150,7 +153,7 @@ public void testAddDaily() throws Exception { public void accept(Iterable events) { for (TriggerEvent event : events) { assertThat(event.jobName(), is(name)); - logger.info("triggered job on [{}]", new DateTime(clock.millis(), UTC)); + logger.info("triggered job on [{}]", clock.instant().atZone(ZoneOffset.UTC)); latch.countDown(); } } @@ -159,15 +162,17 @@ public void accept(Iterable events) { int randomHour = randomIntBetween(0, 23); int randomMinute = randomIntBetween(0, 59); - DateTime testNowTime = new DateTime(clock.millis(), UTC).withHourOfDay(randomHour) - .withMinuteOfHour(randomMinute).withSecondOfMinute(59); - DateTime scheduledTime = testNowTime.plusSeconds(2); + ZonedDateTime testNowTime = clock.instant().atZone(ZoneOffset.UTC) + .with(ChronoField.HOUR_OF_DAY, randomHour).with(ChronoField.MINUTE_OF_HOUR, randomMinute) + .with(ChronoField.SECOND_OF_MINUTE, 59); + + ZonedDateTime scheduledTime = testNowTime.plusSeconds(2); logger.info("Setting current time to [{}], job execution time [{}]", testNowTime, scheduledTime); clock.setTime(testNowTime); - engine.add(createWatch(name, daily().at(scheduledTime.getHourOfDay(), - scheduledTime.getMinuteOfHour()).build())); + engine.add(createWatch(name, daily().at(scheduledTime.getHour(), + scheduledTime.getMinute()).build())); advanceClockIfNeeded(scheduledTime); if (!latch.await(5, TimeUnit.SECONDS)) { @@ -194,9 +199,13 @@ public void accept(Iterable events) { int randomMinute = randomIntBetween(0, 59); int randomDay = randomIntBetween(1, 7); - DateTime testNowTime = new DateTime(clock.millis(), UTC).withDayOfWeek(randomDay) - .withHourOfDay(randomHour).withMinuteOfHour(randomMinute).withSecondOfMinute(59); - DateTime scheduledTime = testNowTime.plusSeconds(2); + ZonedDateTime testNowTime = clock.instant().atZone(ZoneOffset.UTC) + .with(ChronoField.DAY_OF_WEEK, randomDay) + .with(ChronoField.HOUR_OF_DAY, randomHour) + .with(ChronoField.MINUTE_OF_HOUR, randomMinute) + .with(ChronoField.SECOND_OF_MINUTE, 59); + + ZonedDateTime scheduledTime = testNowTime.plusSeconds(2); logger.info("Setting current time to [{}], job execution time [{}]", testNowTime, scheduledTime); @@ -204,10 +213,10 @@ public void accept(Iterable events) { // fun part here (aka WTF): DayOfWeek with Joda is MON-SUN, starting at 1 // DayOfWeek with Watcher is SUN-SAT, starting at 1 - int watcherDay = (scheduledTime.getDayOfWeek() % 7) + 1; + int watcherDay = (scheduledTime.getDayOfWeek().getValue() % 7) + 1; engine.add(createWatch(name, weekly().time(WeekTimes.builder() .on(DayOfWeek.resolve(watcherDay)) - .at(scheduledTime.getHourOfDay(), scheduledTime.getMinuteOfHour()).build()) + .at(scheduledTime.getHour(), scheduledTime.getMinute()).build()) .build())); advanceClockIfNeeded(scheduledTime); @@ -240,12 +249,12 @@ public void accept(Iterable events) { engine.add(createWatch("_id", interval("1s"))); } - advanceClockIfNeeded(new DateTime(clock.millis(), UTC).plusMillis(1100)); + advanceClockIfNeeded(clock.instant().plusMillis(1100).atZone(ZoneOffset.UTC)); if (!firstLatch.await(3, TimeUnit.SECONDS)) { fail("waiting too long for all watches to be triggered"); } - advanceClockIfNeeded(new DateTime(clock.millis(), UTC).plusMillis(1100)); + advanceClockIfNeeded(clock.instant().plusMillis(1100).atZone(ZoneOffset.UTC)); if (!secondLatch.await(3, TimeUnit.SECONDS)) { fail("waiting too long for all watches to be triggered"); } diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalToolTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalToolTests.java index aac27f1544b06..0c898d1363b0d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalToolTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/tool/CronEvalToolTests.java @@ -7,8 +7,9 @@ import org.elasticsearch.cli.Command; import org.elasticsearch.cli.CommandTestCase; -import org.joda.time.DateTimeZone; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.Arrays; import java.util.Calendar; import java.util.Locale; @@ -58,7 +59,7 @@ public void testGetNextValidTimes() throws Exception { @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/35687") public void testEnsureDateIsShownInRootLocale() throws Exception { String output = execute("-c","1", "0 0 11 ? * MON-SAT 2040"); - if (TimeZone.getDefault().equals(DateTimeZone.UTC.toTimeZone())) { + if (ZoneId.systemDefault().equals(ZoneOffset.UTC)) { assertThat(output, not(containsString("local time is"))); long linesStartingWithOne = Arrays.stream(output.split("\n")).filter(s -> s.startsWith("\t")).count(); assertThat(linesStartingWithOne, is(0L)); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchStatusTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchStatusTests.java index 1a8263c0c33c7..fce9f8cb05df5 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchStatusTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchStatusTests.java @@ -18,6 +18,8 @@ import org.elasticsearch.xpack.watcher.actions.logging.LoggingAction; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -28,27 +30,26 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.joda.time.DateTime.now; public class WatchStatusTests extends ESTestCase { public void testAckStatusIsResetOnUnmetCondition() { HashMap myMap = new HashMap<>(); - ActionStatus actionStatus = new ActionStatus(now()); + ActionStatus actionStatus = new ActionStatus(ZonedDateTime.now(ZoneOffset.UTC)); myMap.put("foo", actionStatus); - actionStatus.update(now(), new LoggingAction.Result.Success("foo")); - actionStatus.onAck(now()); + actionStatus.update(ZonedDateTime.now(ZoneOffset.UTC), new LoggingAction.Result.Success("foo")); + actionStatus.onAck(ZonedDateTime.now(ZoneOffset.UTC)); assertThat(actionStatus.ackStatus().state(), is(State.ACKED)); - WatchStatus status = new WatchStatus(now(), myMap); - status.onCheck(false, now()); + WatchStatus status = new WatchStatus(ZonedDateTime.now(ZoneOffset.UTC), myMap); + status.onCheck(false, ZonedDateTime.now(ZoneOffset.UTC)); assertThat(status.actionStatus("foo").ackStatus().state(), is(State.AWAITS_SUCCESSFUL_EXECUTION)); } public void testHeadersToXContent() throws Exception { - WatchStatus status = new WatchStatus(now(), Collections.emptyMap()); + WatchStatus status = new WatchStatus(ZonedDateTime.now(ZoneOffset.UTC), Collections.emptyMap()); String key = randomAlphaOfLength(10); String value = randomAlphaOfLength(10); Map headers = Collections.singletonMap(key, value); @@ -78,7 +79,7 @@ public void testHeadersToXContent() throws Exception { } public void testHeadersSerialization() throws IOException { - WatchStatus status = new WatchStatus(now(), Collections.emptyMap()); + WatchStatus status = new WatchStatus(ZonedDateTime.now(ZoneOffset.UTC), Collections.emptyMap()); String key = randomAlphaOfLength(10); String value = randomAlphaOfLength(10); Map headers = Collections.singletonMap(key, value); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java index 95a63c97f4dfe..ac944755b9c4d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java @@ -114,14 +114,13 @@ import org.elasticsearch.xpack.watcher.trigger.schedule.support.MonthTimes; import org.elasticsearch.xpack.watcher.trigger.schedule.support.WeekTimes; import org.elasticsearch.xpack.watcher.trigger.schedule.support.YearTimes; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.junit.Before; import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -147,7 +146,6 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; public class WatchTests extends ESTestCase { @@ -178,7 +176,7 @@ public void init() throws Exception { public void testParserSelfGenerated() throws Exception { Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); - DateTime now = new DateTime(clock.millis(), UTC); + ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); TransformRegistry transformRegistry = transformRegistry(); boolean includeStatus = randomBoolean(); Schedule schedule = randomSchedule(); @@ -248,8 +246,10 @@ public Trigger parseTrigger(String jobName, XContentParser parser) throws IOExce } }; - DateTime now = new DateTime(UTC); + Clock fixedClock = Clock.fixed(Instant.now(), ZoneOffset.UTC); + ClockMock clock = ClockMock.frozen(); + ZonedDateTime now = Instant.ofEpochMilli(fixedClock.millis()).atZone(ZoneOffset.UTC); clock.setTime(now); List actions = randomActions(); @@ -257,12 +257,12 @@ public Trigger parseTrigger(String jobName, XContentParser parser) throws IOExce for (ActionWrapper action : actions) { actionsStatuses.put(action.id(), new ActionStatus(now)); } - WatchStatus watchStatus = new WatchStatus(new DateTime(clock.millis()), unmodifiableMap(actionsStatuses)); + WatchStatus watchStatus = new WatchStatus(clock.instant().atZone(ZoneOffset.UTC), unmodifiableMap(actionsStatuses)); WatchParser watchParser = new WatchParser(triggerService, actionRegistry, inputRegistry, null, clock); XContentBuilder builder = jsonBuilder().startObject().startObject("trigger").endObject().field("status", watchStatus).endObject(); Watch watch = watchParser.parse("foo", true, BytesReference.bytes(builder), XContentType.JSON, 1L, 1L); - assertThat(watch.status().state().getTimestamp().getMillis(), is(clock.millis())); + assertThat(watch.status().state().getTimestamp().toInstant().toEpochMilli(), is(clock.millis())); for (ActionWrapper action : actions) { assertThat(watch.status().actionStatus(action.id()), is(actionsStatuses.get(action.id()))); } @@ -548,7 +548,7 @@ private ConditionRegistry conditionRegistry() { private ExecutableTransform randomTransform() { String type = randomFrom(ScriptTransform.TYPE, SearchTransform.TYPE, ChainTransform.TYPE); TimeValue timeout = randomBoolean() ? timeValueSeconds(between(1, 10000)) : null; - DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null; + ZoneOffset timeZone = randomBoolean() ? ZoneOffset.UTC : null; switch (type) { case ScriptTransform.TYPE: return new ExecutableScriptTransform(new ScriptTransform(mockScript("_script")), logger, scriptService); @@ -588,7 +588,7 @@ private List randomActions() { new ExecutableEmailAction(action, logger, emailService, templateEngine, htmlSanitizer, Collections.emptyMap()))); } if (randomBoolean()) { - DateTimeZone timeZone = randomBoolean() ? DateTimeZone.UTC : null; + ZoneOffset timeZone = randomBoolean() ? ZoneOffset.UTC : null; TimeValue timeout = randomBoolean() ? timeValueSeconds(between(1, 10000)) : null; WriteRequest.RefreshPolicy refreshPolicy = randomBoolean() ? null : randomFrom(WriteRequest.RefreshPolicy.values()); IndexAction action = new IndexAction("_index", null, randomBoolean() ? "123" : null, null, timeout, timeZone, diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/clock/ClockTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/clock/ClockTests.java index d9f57e28b4842..7104a7b01e17c 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/clock/ClockTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/clock/ClockTests.java @@ -7,20 +7,11 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.watcher.watch.ClockMock; -import org.joda.time.DateTime; - -import java.time.Clock; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; -import static org.joda.time.DateTimeZone.UTC; public class ClockTests extends ESTestCase { - public void testNowUTC() { - Clock clockMock = ClockMock.frozen(); - assertThat(new DateTime(clockMock.millis(), UTC).getZone(), equalTo(UTC)); - assertThat(new DateTime(Clock.systemUTC().millis(), UTC).getZone(), equalTo(UTC)); - } public void testFreezeUnfreeze() throws Exception { ClockMock clockMock = ClockMock.frozen();