From ac4e0f1b1d34d913b7d5394ba99794e06186d757 Mon Sep 17 00:00:00 2001 From: Alexander Reelsen Date: Thu, 12 Jul 2018 09:55:17 +0200 Subject: [PATCH] Tests: Remove use of joda time in some tests (#31922) This also extends the dateformatters test to ensure that the printers are acting the same in java time and joda time. --- .../ingest/common/DateProcessorTests.java | 35 +++--- .../cluster/metadata/IndexMetaData.java | 8 +- .../metadata/MetaDataCreateIndexService.java | 5 +- .../common/time/DateFormatters.java | 109 ++++++++++++------ .../rest/action/cat/RestIndicesAction.java | 7 +- .../admin/indices/rollover/RolloverIT.java | 20 ++-- .../HumanReadableIndexSettingsTests.java | 9 +- .../joda/JavaJodaTimeDuellingTests.java | 100 ++++++++++++++++ .../explain/ExplainActionIT.java | 11 +- .../indices/IndicesRequestCacheIT.java | 12 +- .../aggregations/bucket/MinDocCountIT.java | 12 +- .../highlight/HighlighterSearchIT.java | 6 +- .../search/fields/SearchFieldsIT.java | 22 ++-- .../functionscore/DecayFunctionScoreIT.java | 14 +-- .../search/query/SearchQueryIT.java | 8 +- .../validate/SimpleValidateQueryIT.java | 20 ++-- 16 files changed, 274 insertions(+), 124 deletions(-) diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/DateProcessorTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/DateProcessorTests.java index 8fba759aa16f9..43a5f9245b185 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/DateProcessorTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/DateProcessorTests.java @@ -24,9 +24,10 @@ import org.elasticsearch.ingest.TestTemplateService; import org.elasticsearch.script.TemplateScript; import org.elasticsearch.test.ESTestCase; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -36,19 +37,21 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; -import static org.joda.time.DateTimeZone.UTC; public class DateProcessorTests extends ESTestCase { + private TemplateScript.Factory templatize(Locale locale) { return new TestTemplateService.MockTemplateScript.Factory(locale.getLanguage()); } - private TemplateScript.Factory templatize(DateTimeZone timezone) { - return new TestTemplateService.MockTemplateScript.Factory(timezone.getID()); + private TemplateScript.Factory templatize(ZoneId timezone) { + // prevent writing "UTC" as string, as joda time does not parse it + String id = timezone.equals(ZoneOffset.UTC) ? "UTC" : timezone.getId(); + return new TestTemplateService.MockTemplateScript.Factory(id); } public void testJodaPattern() { DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), - templatize(DateTimeZone.forID("Europe/Amsterdam")), templatize(Locale.ENGLISH), + templatize(ZoneId.of("Europe/Amsterdam")), templatize(Locale.ENGLISH), "date_as_string", Collections.singletonList("yyyy dd MM hh:mm:ss"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "2010 12 06 11:05:15"); @@ -63,7 +66,7 @@ public void testJodaPatternMultipleFormats() { matchFormats.add("dd/MM/yyyy"); matchFormats.add("dd-MM-yyyy"); DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), - templatize(DateTimeZone.forID("Europe/Amsterdam")), templatize(Locale.ENGLISH), + templatize(ZoneId.of("Europe/Amsterdam")), templatize(Locale.ENGLISH), "date_as_string", matchFormats, "date_as_date"); Map document = new HashMap<>(); @@ -98,7 +101,7 @@ public void testJodaPatternMultipleFormats() { public void testInvalidJodaPattern() { try { DateProcessor processor = new DateProcessor(randomAlphaOfLength(10), - templatize(UTC), templatize(randomLocale(random())), + templatize(ZoneOffset.UTC), templatize(randomLocale(random())), "date_as_string", Collections.singletonList("invalid pattern"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "2010"); @@ -112,7 +115,7 @@ public void testInvalidJodaPattern() { public void testJodaPatternLocale() { DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), - templatize(DateTimeZone.forID("Europe/Amsterdam")), templatize(Locale.ITALIAN), + templatize(ZoneId.of("Europe/Amsterdam")), templatize(Locale.ITALIAN), "date_as_string", Collections.singletonList("yyyy dd MMM"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "2010 12 giugno"); @@ -123,18 +126,18 @@ public void testJodaPatternLocale() { public void testJodaPatternDefaultYear() { DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), - templatize(DateTimeZone.forID("Europe/Amsterdam")), templatize(Locale.ENGLISH), + templatize(ZoneId.of("Europe/Amsterdam")), templatize(Locale.ENGLISH), "date_as_string", Collections.singletonList("dd/MM"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "12/06"); IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), document); dateProcessor.execute(ingestDocument); assertThat(ingestDocument.getFieldValue("date_as_date", String.class), - equalTo(DateTime.now().getYear() + "-06-12T00:00:00.000+02:00")); + equalTo(ZonedDateTime.now().getYear() + "-06-12T00:00:00.000+02:00")); } public void testTAI64N() { - DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(DateTimeZone.forOffsetHours(2)), + DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(ZoneOffset.ofHours(2)), templatize(randomLocale(random())), "date_as_string", Collections.singletonList("TAI64N"), "date_as_date"); Map document = new HashMap<>(); @@ -146,8 +149,8 @@ public void testTAI64N() { } public void testUnixMs() { - DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(UTC), templatize(randomLocale(random())), - "date_as_string", Collections.singletonList("UNIX_MS"), "date_as_date"); + DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(ZoneOffset.UTC), + templatize(randomLocale(random())), "date_as_string", Collections.singletonList("UNIX_MS"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "1000500"); IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), document); @@ -162,7 +165,7 @@ public void testUnixMs() { } public void testUnix() { - DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(UTC), + DateProcessor dateProcessor = new DateProcessor(randomAlphaOfLength(10), templatize(ZoneOffset.UTC), templatize(randomLocale(random())), "date_as_string", Collections.singletonList("UNIX"), "date_as_date"); Map document = new HashMap<>(); @@ -186,7 +189,7 @@ public void testInvalidTimezone() { public void testInvalidLocale() { DateProcessor processor = new DateProcessor(randomAlphaOfLength(10), - templatize(UTC), new TestTemplateService.MockTemplateScript.Factory("invalid_locale"), + templatize(ZoneOffset.UTC), new TestTemplateService.MockTemplateScript.Factory("invalid_locale"), "date_as_string", Collections.singletonList("yyyy"), "date_as_date"); Map document = new HashMap<>(); document.put("date_as_string", "2010"); diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java index d978e214fc96c..903802050127e 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java @@ -23,7 +23,6 @@ import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; - import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.rollover.RolloverInfo; import org.elasticsearch.action.support.ActiveShardCount; @@ -56,10 +55,11 @@ import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.rest.RestStatus; -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.Arrays; import java.util.Collections; import java.util.EnumSet; @@ -1345,7 +1345,7 @@ public static Settings addHumanReadableSettings(Settings settings) { } Long creationDate = settings.getAsLong(SETTING_CREATION_DATE, null); if (creationDate != null) { - DateTime creationDateTime = new DateTime(creationDate, DateTimeZone.UTC); + ZonedDateTime creationDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(creationDate), ZoneOffset.UTC); builder.put(SETTING_CREATION_DATE_STRING, creationDateTime.toString()); } return builder.build(); diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java b/server/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java index be9db5262b00c..b19d65090c6b6 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java @@ -73,11 +73,10 @@ import org.elasticsearch.indices.InvalidIndexNameException; import org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason; import org.elasticsearch.threadpool.ThreadPool; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import java.io.UnsupportedEncodingException; import java.nio.file.Path; +import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -383,7 +382,7 @@ public ClusterState execute(ClusterState currentState) throws Exception { } if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) { - indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis()); + indexSettingsBuilder.put(SETTING_CREATION_DATE, Instant.now().toEpochMilli()); } indexSettingsBuilder.put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, request.getProvidedName()); indexSettingsBuilder.put(SETTING_INDEX_UUID, UUIDs.randomBase64UUID()); diff --git a/server/src/main/java/org/elasticsearch/common/time/DateFormatters.java b/server/src/main/java/org/elasticsearch/common/time/DateFormatters.java index e781c979ed9eb..eef2ab5558789 100644 --- a/server/src/main/java/org/elasticsearch/common/time/DateFormatters.java +++ b/server/src/main/java/org/elasticsearch/common/time/DateFormatters.java @@ -52,12 +52,6 @@ public class DateFormatters { - private static final DateTimeFormatter TIME_ZONE_FORMATTER = new DateTimeFormatterBuilder() - .optionalStart().appendZoneId().optionalEnd() - .optionalStart().appendOffset("+HHmm", "Z").optionalEnd() - .optionalStart().appendOffset("+HH:mm", "Z").optionalEnd() - .toFormatter(Locale.ROOT); - private static final DateTimeFormatter TIME_ZONE_FORMATTER_ZONE_ID = new DateTimeFormatterBuilder() .appendZoneId() .toFormatter(Locale.ROOT); @@ -70,12 +64,80 @@ public class DateFormatters { .appendOffset("+HH:mm", "Z") .toFormatter(Locale.ROOT); + private static final DateTimeFormatter TIME_ZONE_FORMATTER = new DateTimeFormatterBuilder() + .optionalStart().appendZoneId().optionalEnd() + .optionalStart().appendOffset("+HHmm", "Z").optionalEnd() + .optionalStart().appendOffset("+HH:mm", "Z").optionalEnd() + .toFormatter(Locale.ROOT); + private static final DateTimeFormatter OPTIONAL_TIME_ZONE_FORMATTER = new DateTimeFormatterBuilder() .optionalStart() .append(TIME_ZONE_FORMATTER) .optionalEnd() .toFormatter(Locale.ROOT); + private static final DateTimeFormatter STRICT_YEAR_MONTH_DAY_FORMATTER = new DateTimeFormatterBuilder() + .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD) + .appendLiteral("-") + .appendValue(MONTH_OF_YEAR, 2, 2, SignStyle.NOT_NEGATIVE) + .appendLiteral('-') + .appendValue(DAY_OF_MONTH, 2, 2, SignStyle.NOT_NEGATIVE) + .toFormatter(Locale.ROOT); + + private static final DateTimeFormatter STRICT_HOUR_MINUTE_SECOND_FORMATTER = new DateTimeFormatterBuilder() + .appendValue(HOUR_OF_DAY, 2, 2, SignStyle.NOT_NEGATIVE) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2, 2, SignStyle.NOT_NEGATIVE) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2, 2, SignStyle.NOT_NEGATIVE) + .toFormatter(Locale.ROOT); + + private static final DateTimeFormatter STRICT_DATE_OPTIONAL_TIME_FORMATTER_1 = new DateTimeFormatterBuilder() + .append(STRICT_YEAR_MONTH_DAY_FORMATTER) + .optionalStart() + .appendLiteral('T') + .append(STRICT_HOUR_MINUTE_SECOND_FORMATTER) + .optionalStart() + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .optionalEnd() + .optionalStart() + .append(TIME_ZONE_FORMATTER_WITHOUT_COLON) + .optionalEnd() + .optionalEnd() + .toFormatter(Locale.ROOT); + + private static final DateTimeFormatter STRICT_DATE_OPTIONAL_TIME_FORMATTER_2 = new DateTimeFormatterBuilder() + .append(STRICT_YEAR_MONTH_DAY_FORMATTER) + .optionalStart() + .appendLiteral('T') + .append(STRICT_HOUR_MINUTE_SECOND_FORMATTER) + .optionalStart() + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .optionalEnd() + .optionalStart() + .append(TIME_ZONE_FORMATTER_WITH_COLON) + .optionalEnd() + .optionalEnd() + .toFormatter(Locale.ROOT); + + private static final DateTimeFormatter STRICT_DATE_OPTIONAL_TIME_FORMATTER_3 = new DateTimeFormatterBuilder() + .append(STRICT_YEAR_MONTH_DAY_FORMATTER) + .optionalStart() + .appendLiteral('T') + .append(STRICT_HOUR_MINUTE_SECOND_FORMATTER) + .optionalStart() + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .optionalEnd() + .optionalStart() + .append(TIME_ZONE_FORMATTER_ZONE_ID) + .optionalEnd() + .optionalEnd() + .toFormatter(Locale.ROOT); + + private static final CompoundDateTimeFormatter STRICT_DATE_OPTIONAL_TIME = + new CompoundDateTimeFormatter(STRICT_DATE_OPTIONAL_TIME_FORMATTER_1, STRICT_DATE_OPTIONAL_TIME_FORMATTER_2, + STRICT_DATE_OPTIONAL_TIME_FORMATTER_3); + private static final DateTimeFormatter BASIC_TIME_NO_MILLIS_FORMATTER = new DateTimeFormatterBuilder() .appendValue(HOUR_OF_DAY, 2, 2, SignStyle.NOT_NEGATIVE) .appendValue(MINUTE_OF_HOUR, 2, 2, SignStyle.NOT_NEGATIVE) @@ -258,7 +320,8 @@ public class DateFormatters { .append(OPTIONAL_TIME_ZONE_FORMATTER) .toFormatter(Locale.ROOT)); - private static final CompoundDateTimeFormatter DATE_OPTIONAL_TIME = new CompoundDateTimeFormatter(new DateTimeFormatterBuilder() + private static final CompoundDateTimeFormatter DATE_OPTIONAL_TIME = new CompoundDateTimeFormatter(STRICT_DATE_OPTIONAL_TIME.printer, + new DateTimeFormatterBuilder() .append(DATE_FORMATTER) .parseLenient() .optionalStart() @@ -560,14 +623,6 @@ public class DateFormatters { private static final CompoundDateTimeFormatter STRICT_DATE_HOUR_MINUTE = new CompoundDateTimeFormatter( DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm", Locale.ROOT)); - private static final DateTimeFormatter STRICT_YEAR_MONTH_DAY_FORMATTER = new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD) - .appendLiteral("-") - .appendValue(MONTH_OF_YEAR, 2, 2, SignStyle.NOT_NEGATIVE) - .appendLiteral('-') - .appendValue(DAY_OF_MONTH, 2, 2, SignStyle.NOT_NEGATIVE) - .toFormatter(Locale.ROOT); - private static final CompoundDateTimeFormatter STRICT_YEAR_MONTH_DAY = new CompoundDateTimeFormatter(STRICT_YEAR_MONTH_DAY_FORMATTER); private static final CompoundDateTimeFormatter STRICT_YEAR_MONTH = new CompoundDateTimeFormatter(new DateTimeFormatterBuilder() @@ -580,14 +635,6 @@ public class DateFormatters { .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .toFormatter(Locale.ROOT)); - private static final DateTimeFormatter STRICT_HOUR_MINUTE_SECOND_FORMATTER = new DateTimeFormatterBuilder() - .appendValue(HOUR_OF_DAY, 2, 2, SignStyle.NOT_NEGATIVE) - .appendLiteral(':') - .appendValue(MINUTE_OF_HOUR, 2, 2, SignStyle.NOT_NEGATIVE) - .appendLiteral(':') - .appendValue(SECOND_OF_MINUTE, 2, 2, SignStyle.NOT_NEGATIVE) - .toFormatter(Locale.ROOT); - private static final CompoundDateTimeFormatter STRICT_HOUR_MINUTE_SECOND = new CompoundDateTimeFormatter(STRICT_HOUR_MINUTE_SECOND_FORMATTER); @@ -601,18 +648,6 @@ public class DateFormatters { .append(OPTIONAL_TIME_ZONE_FORMATTER) .toFormatter(Locale.ROOT)); - private static final CompoundDateTimeFormatter STRICT_DATE_OPTIONAL_TIME = new CompoundDateTimeFormatter(new DateTimeFormatterBuilder() - .append(STRICT_YEAR_MONTH_DAY_FORMATTER) - .optionalStart() - .appendLiteral('T') - .append(STRICT_HOUR_MINUTE_SECOND_FORMATTER) - .optionalStart() - .appendFraction(MILLI_OF_SECOND, 3, 3, true) - .optionalEnd() - .append(OPTIONAL_TIME_ZONE_FORMATTER) - .optionalEnd() - .toFormatter(Locale.ROOT)); - private static final CompoundDateTimeFormatter STRICT_ORDINAL_DATE_TIME_NO_MILLIS = new CompoundDateTimeFormatter( new DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD) @@ -918,8 +953,8 @@ public static CompoundDateTimeFormatter forPattern(String input, Locale locale) return forPattern(formats[0], locale); } else { Collection parsers = new LinkedHashSet<>(formats.length); - for (int i = 0; i < formats.length; i++) { - CompoundDateTimeFormatter dateTimeFormatter = forPattern(formats[i], locale); + for (String format : formats) { + CompoundDateTimeFormatter dateTimeFormatter = forPattern(format, locale); try { parsers.addAll(Arrays.asList(dateTimeFormatter.parsers)); } catch (IllegalArgumentException e) { diff --git a/server/src/main/java/org/elasticsearch/rest/action/cat/RestIndicesAction.java b/server/src/main/java/org/elasticsearch/rest/action/cat/RestIndicesAction.java index 52da10a378576..3a76c7ca0c952 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/cat/RestIndicesAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/cat/RestIndicesAction.java @@ -45,9 +45,10 @@ import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.action.RestActionListener; import org.elasticsearch.rest.action.RestResponseListener; -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.Arrays; import java.util.Collections; import java.util.HashSet; @@ -379,7 +380,7 @@ Table buildTable(RestRequest request, Index[] indices, ClusterHealthResponse res table.addCell(primaryStats.getDocs() == null ? null : primaryStats.getDocs().getDeleted()); table.addCell(indexMetaData.getCreationDate()); - table.addCell(new DateTime(indexMetaData.getCreationDate(), DateTimeZone.UTC)); + table.addCell(ZonedDateTime.ofInstant(Instant.ofEpochMilli(indexMetaData.getCreationDate()), ZoneOffset.UTC)); table.addCell(totalStats.getStore() == null ? null : totalStats.getStore().size()); table.addCell(primaryStats.getStore() == null ? null : primaryStats.getStore().size()); diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverIT.java b/server/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverIT.java index 4d86dbbc51f33..5379769e819dc 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverIT.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/rollover/RolloverIT.java @@ -25,16 +25,16 @@ import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -197,8 +197,8 @@ public void testRolloverOnExistingIndex() throws Exception { } public void testRolloverWithDateMath() { - DateTime now = new DateTime(DateTimeZone.UTC); - String index = "test-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now) + "-1"; + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + String index = "test-" + DateFormatters.forPattern("YYYY.MM.dd").format(now) + "-1"; String dateMathExp = ""; assertAcked(prepareCreate(dateMathExp).addAlias(new Alias("test_alias")).get()); ensureGreen(index); @@ -212,14 +212,14 @@ public void testRolloverWithDateMath() { ensureGreen(index); RolloverResponse response = client().admin().indices().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo(index)); - assertThat(response.getNewIndex(), equalTo("test-" + DateTimeFormat.forPattern("YYYY.MM").print(now) + "-000002")); + assertThat(response.getNewIndex(), equalTo("test-" + DateFormatters.forPattern("YYYY.MM").format(now) + "-000002")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); response = client().admin().indices().prepareRolloverIndex("test_alias").get(); - assertThat(response.getOldIndex(), equalTo("test-" + DateTimeFormat.forPattern("YYYY.MM").print(now) + "-000002")); - assertThat(response.getNewIndex(), equalTo("test-" + DateTimeFormat.forPattern("YYYY.MM").print(now) + "-000003")); + assertThat(response.getOldIndex(), equalTo("test-" + DateFormatters.forPattern("YYYY.MM").format(now) + "-000002")); + assertThat(response.getNewIndex(), equalTo("test-" + DateFormatters.forPattern("YYYY.MM").format(now) + "-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); @@ -232,8 +232,8 @@ public void testRolloverWithDateMath() { IndexMetaData.SETTING_INDEX_PROVIDED_NAME)); response = client().admin().indices().prepareRolloverIndex("test_alias").setNewIndexName("").get(); - assertThat(response.getOldIndex(), equalTo("test-" + DateTimeFormat.forPattern("YYYY.MM").print(now) + "-000003")); - assertThat(response.getNewIndex(), equalTo("test-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now) + "-000004")); + assertThat(response.getOldIndex(), equalTo("test-" + DateFormatters.forPattern("YYYY.MM").format(now) + "-000003")); + assertThat(response.getNewIndex(), equalTo("test-" + DateFormatters.forPattern("YYYY.MM.dd").format(now) + "-000004")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/HumanReadableIndexSettingsTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/HumanReadableIndexSettingsTests.java index 9be087e0e5dbc..83c615e48822a 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/HumanReadableIndexSettingsTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/HumanReadableIndexSettingsTests.java @@ -22,8 +22,10 @@ import org.elasticsearch.Version; import org.elasticsearch.common.settings.Settings; 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 static org.elasticsearch.test.VersionUtils.randomVersion; @@ -42,6 +44,7 @@ public void testHumanReadableSettings() { assertEquals(versionCreated.toString(), humanSettings.get(IndexMetaData.SETTING_VERSION_CREATED_STRING, null)); assertEquals(versionUpgraded.toString(), humanSettings.get(IndexMetaData.SETTING_VERSION_UPGRADED_STRING, null)); - assertEquals(new DateTime(created, DateTimeZone.UTC).toString(), humanSettings.get(IndexMetaData.SETTING_CREATION_DATE_STRING, null)); + ZonedDateTime creationDate = ZonedDateTime.ofInstant(Instant.ofEpochMilli(created), ZoneOffset.UTC); + assertEquals(creationDate.toString(), humanSettings.get(IndexMetaData.SETTING_CREATION_DATE_STRING, null)); } } diff --git a/server/src/test/java/org/elasticsearch/common/joda/JavaJodaTimeDuellingTests.java b/server/src/test/java/org/elasticsearch/common/joda/JavaJodaTimeDuellingTests.java index 7c6f087228830..d6f733d7c1cd4 100644 --- a/server/src/test/java/org/elasticsearch/common/joda/JavaJodaTimeDuellingTests.java +++ b/server/src/test/java/org/elasticsearch/common/joda/JavaJodaTimeDuellingTests.java @@ -23,7 +23,9 @@ import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.test.ESTestCase; import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; @@ -354,11 +356,109 @@ public void testDuelingStrictParsing() { assertParseException("2012-W1-1", "strict_weekyear_week_day"); } + public void testSamePrinterOutput() { + int year = randomIntBetween(1970, 2030); + int month = randomIntBetween(1, 12); + int day = randomIntBetween(1, 28); + int hour = randomIntBetween(0, 23); + int minute = randomIntBetween(0, 59); + int second = randomIntBetween(0, 59); + + ZonedDateTime javaDate = ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneOffset.UTC); + DateTime jodaDate = new DateTime(year, month, day, hour, minute, second, DateTimeZone.UTC); + + assertSamePrinterOutput("basicDate", javaDate, jodaDate); + assertSamePrinterOutput("basicDateTime", javaDate, jodaDate); + assertSamePrinterOutput("basicDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("basicOrdinalDate", javaDate, jodaDate); + assertSamePrinterOutput("basicOrdinalDateTime", javaDate, jodaDate); + assertSamePrinterOutput("basicOrdinalDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("basicTime", javaDate, jodaDate); + assertSamePrinterOutput("basicTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("basicTTime", javaDate, jodaDate); + assertSamePrinterOutput("basicTTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("basicWeekDate", javaDate, jodaDate); + assertSamePrinterOutput("basicWeekDateTime", javaDate, jodaDate); + assertSamePrinterOutput("basicWeekDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("date", javaDate, jodaDate); + assertSamePrinterOutput("dateHour", javaDate, jodaDate); + assertSamePrinterOutput("dateHourMinute", javaDate, jodaDate); + assertSamePrinterOutput("dateHourMinuteSecond", javaDate, jodaDate); + assertSamePrinterOutput("dateHourMinuteSecondFraction", javaDate, jodaDate); + assertSamePrinterOutput("dateHourMinuteSecondMillis", javaDate, jodaDate); + assertSamePrinterOutput("dateOptionalTime", javaDate, jodaDate); + assertSamePrinterOutput("dateTime", javaDate, jodaDate); + assertSamePrinterOutput("dateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("hour", javaDate, jodaDate); + assertSamePrinterOutput("hourMinute", javaDate, jodaDate); + assertSamePrinterOutput("hourMinuteSecond", javaDate, jodaDate); + assertSamePrinterOutput("hourMinuteSecondFraction", javaDate, jodaDate); + assertSamePrinterOutput("hourMinuteSecondMillis", javaDate, jodaDate); + assertSamePrinterOutput("ordinalDate", javaDate, jodaDate); + assertSamePrinterOutput("ordinalDateTime", javaDate, jodaDate); + assertSamePrinterOutput("ordinalDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("time", javaDate, jodaDate); + assertSamePrinterOutput("timeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("tTime", javaDate, jodaDate); + assertSamePrinterOutput("tTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("weekDate", javaDate, jodaDate); + assertSamePrinterOutput("weekDateTime", javaDate, jodaDate); + assertSamePrinterOutput("weekDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("weekyear", javaDate, jodaDate); + assertSamePrinterOutput("weekyearWeek", javaDate, jodaDate); + assertSamePrinterOutput("weekyearWeekDay", javaDate, jodaDate); + assertSamePrinterOutput("year", javaDate, jodaDate); + assertSamePrinterOutput("yearMonth", javaDate, jodaDate); + assertSamePrinterOutput("yearMonthDay", javaDate, jodaDate); + assertSamePrinterOutput("epoch_second", javaDate, jodaDate); + assertSamePrinterOutput("epoch_millis", javaDate, jodaDate); + assertSamePrinterOutput("strictBasicWeekDate", javaDate, jodaDate); + assertSamePrinterOutput("strictBasicWeekDateTime", javaDate, jodaDate); + assertSamePrinterOutput("strictBasicWeekDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictDate", javaDate, jodaDate); + assertSamePrinterOutput("strictDateHour", javaDate, jodaDate); + assertSamePrinterOutput("strictDateHourMinute", javaDate, jodaDate); + assertSamePrinterOutput("strictDateHourMinuteSecond", javaDate, jodaDate); + assertSamePrinterOutput("strictDateHourMinuteSecondFraction", javaDate, jodaDate); + assertSamePrinterOutput("strictDateHourMinuteSecondMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictDateOptionalTime", javaDate, jodaDate); + assertSamePrinterOutput("strictDateTime", javaDate, jodaDate); + assertSamePrinterOutput("strictDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictHour", javaDate, jodaDate); + assertSamePrinterOutput("strictHourMinute", javaDate, jodaDate); + assertSamePrinterOutput("strictHourMinuteSecond", javaDate, jodaDate); + assertSamePrinterOutput("strictHourMinuteSecondFraction", javaDate, jodaDate); + assertSamePrinterOutput("strictHourMinuteSecondMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictOrdinalDate", javaDate, jodaDate); + assertSamePrinterOutput("strictOrdinalDateTime", javaDate, jodaDate); + assertSamePrinterOutput("strictOrdinalDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictTime", javaDate, jodaDate); + assertSamePrinterOutput("strictTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictTTime", javaDate, jodaDate); + assertSamePrinterOutput("strictTTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekDate", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekDateTime", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekDateTimeNoMillis", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekyear", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekyearWeek", javaDate, jodaDate); + assertSamePrinterOutput("strictWeekyearWeekDay", javaDate, jodaDate); + assertSamePrinterOutput("strictYear", javaDate, jodaDate); + assertSamePrinterOutput("strictYearMonth", javaDate, jodaDate); + assertSamePrinterOutput("strictYearMonthDay", javaDate, jodaDate); + } + public void testSeveralTimeFormats() { assertSameDate("2018-12-12", "year_month_day||ordinal_date"); assertSameDate("2018-128", "year_month_day||ordinal_date"); } + private void assertSamePrinterOutput(String format, ZonedDateTime javaDate, DateTime jodaDate) { + assertThat(jodaDate.getMillis(), is(javaDate.toEpochSecond() * 1000)); + String javaTimeOut = DateFormatters.forPattern("dateOptionalTime").format(javaDate); + String jodaTimeOut = Joda.forPattern("dateOptionalTime").printer().print(jodaDate); + assertThat(javaTimeOut, is(jodaTimeOut)); + } + private void assertSameDate(String input, String format) { FormatDateTimeFormatter jodaFormatter = Joda.forPattern(format); DateTime jodaDateTime = jodaFormatter.parser().parseDateTime(input); diff --git a/server/src/test/java/org/elasticsearch/explain/ExplainActionIT.java b/server/src/test/java/org/elasticsearch/explain/ExplainActionIT.java index 6d8e1a41c5b94..229cb99fbfbda 100644 --- a/server/src/test/java/org/elasticsearch/explain/ExplainActionIT.java +++ b/server/src/test/java/org/elasticsearch/explain/ExplainActionIT.java @@ -28,12 +28,12 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ESIntegTestCase; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.ISODateTimeFormat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -249,8 +249,9 @@ public void testExplainWithFilteredAliasFetchSource() throws Exception { public void testExplainDateRangeInQueryString() { createIndex("test"); - String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1)); - String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1)); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + String aMonthAgo = DateTimeFormatter.ISO_LOCAL_DATE.format(now.minusMonths(1)); + String aMonthFromNow = DateTimeFormatter.ISO_LOCAL_DATE.format(now.plusMonths(1)); client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get(); diff --git a/server/src/test/java/org/elasticsearch/indices/IndicesRequestCacheIT.java b/server/src/test/java/org/elasticsearch/indices/IndicesRequestCacheIT.java index 70a633f02f4dc..0f12305f23969 100644 --- a/server/src/test/java/org/elasticsearch/indices/IndicesRequestCacheIT.java +++ b/server/src/test/java/org/elasticsearch/indices/IndicesRequestCacheIT.java @@ -30,11 +30,11 @@ import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket; import org.elasticsearch.test.ESIntegTestCase; -import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.format.DateTimeFormat; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import java.util.List; import static org.elasticsearch.search.aggregations.AggregationBuilders.dateHistogram; @@ -255,7 +255,7 @@ public void testQueryRewriteDatesWithNow() throws Exception { .setSettings(settings).get()); assertAcked(client.admin().indices().prepareCreate("index-3").addMapping("type", "d", "type=date") .setSettings(settings).get()); - DateTime now = new DateTime(ISOChronology.getInstanceUTC()); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); indexRandom(true, client.prepareIndex("index-1", "type", "1").setSource("d", now), client.prepareIndex("index-1", "type", "2").setSource("d", now.minusDays(1)), client.prepareIndex("index-1", "type", "3").setSource("d", now.minusDays(2)), @@ -456,9 +456,9 @@ public void testCacheWithFilteredAlias() { .setSettings(settings) .addAlias(new Alias("last_week").filter(QueryBuilders.rangeQuery("created_at").gte("now-7d/d"))) .get()); - DateTime now = new DateTime(DateTimeZone.UTC); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); client.prepareIndex("index", "type", "1").setRouting("1").setSource("created_at", - DateTimeFormat.forPattern("YYYY-MM-dd").print(now)).get(); + DateTimeFormatter.ISO_LOCAL_DATE.format(now)).get(); refresh(); assertThat(client.admin().indices().prepareStats("index").setRequestCache(true).get().getTotal().getRequestCache().getHitCount(), diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/MinDocCountIT.java b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/MinDocCountIT.java index af1104879e92e..4a85c2c145329 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/bucket/MinDocCountIT.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/bucket/MinDocCountIT.java @@ -22,10 +22,10 @@ import com.carrotsearch.hppc.LongHashSet; import com.carrotsearch.hppc.LongSet; import com.carrotsearch.randomizedtesting.generators.RandomStrings; - import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; @@ -40,10 +40,9 @@ import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.test.ESIntegTestCase; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -123,8 +122,9 @@ public void setupSuiteScopeCluster() throws Exception { longTerm = randomInt(cardinality * 2); } while (!longTerms.add(longTerm)); double doubleTerm = longTerm * Math.PI; - String dateTerm = DateTimeFormat.forPattern("yyyy-MM-dd") - .print(new DateTime(2014, 1, ((int) longTerm % 20) + 1, 0, 0, DateTimeZone.UTC)); + + ZonedDateTime time = ZonedDateTime.of(2014, 1, ((int) longTerm % 20) + 1, 0, 0, 0, 0, ZoneOffset.UTC); + String dateTerm = DateFormatters.forPattern("yyyy-MM-dd").format(time); final int frequency = randomBoolean() ? 1 : randomIntBetween(2, 20); for (int j = 0; j < frequency; ++j) { indexRequests.add(client().prepareIndex("idx", "type").setSource(jsonBuilder() diff --git a/server/src/test/java/org/elasticsearch/search/fetch/subphase/highlight/HighlighterSearchIT.java b/server/src/test/java/org/elasticsearch/search/fetch/subphase/highlight/HighlighterSearchIT.java index 35c5a19cc2e8c..e5af22cd2ae65 100644 --- a/server/src/test/java/org/elasticsearch/search/fetch/subphase/highlight/HighlighterSearchIT.java +++ b/server/src/test/java/org/elasticsearch/search/fetch/subphase/highlight/HighlighterSearchIT.java @@ -63,10 +63,10 @@ import org.elasticsearch.test.MockKeywordPlugin; import org.hamcrest.Matcher; import org.hamcrest.Matchers; -import org.joda.time.DateTime; -import org.joda.time.chrono.ISOChronology; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -2865,7 +2865,7 @@ public void testHighlightQueryRewriteDatesWithNow() throws Exception { "field", "type=text,store=true,term_vector=with_positions_offsets") .setSettings(Settings.builder().put("index.number_of_replicas", 0).put("index.number_of_shards", 2)) .get()); - DateTime now = new DateTime(ISOChronology.getInstanceUTC()); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); indexRandom(true, client().prepareIndex("index-1", "type", "1").setSource("d", now, "field", "hello world"), client().prepareIndex("index-1", "type", "2").setSource("d", now.minusDays(1), "field", "hello"), client().prepareIndex("index-1", "type", "3").setSource("d", now.minusDays(2), "field", "world")); diff --git a/server/src/test/java/org/elasticsearch/search/fields/SearchFieldsIT.java b/server/src/test/java/org/elasticsearch/search/fields/SearchFieldsIT.java index ab5387b6e3f48..452c00b99060f 100644 --- a/server/src/test/java/org/elasticsearch/search/fields/SearchFieldsIT.java +++ b/server/src/test/java/org/elasticsearch/search/fields/SearchFieldsIT.java @@ -28,8 +28,8 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.document.DocumentField; -import org.elasticsearch.common.joda.Joda; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.time.DateFormatters; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.support.XContentMapValues; @@ -48,8 +48,9 @@ import org.elasticsearch.test.InternalSettingsPlugin; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.joda.time.ReadableDateTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -546,6 +547,7 @@ public void testStoredFieldsWithoutSource() throws Exception { client().admin().indices().preparePutMapping().setType("type1").setSource(mapping, XContentType.JSON).execute().actionGet(); + ZonedDateTime date = ZonedDateTime.of(2012, 3, 22, 0, 0, 0, 0, ZoneOffset.UTC); client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject() .field("byte_field", (byte) 1) .field("short_field", (short) 2) @@ -553,7 +555,7 @@ public void testStoredFieldsWithoutSource() throws Exception { .field("long_field", 4L) .field("float_field", 5.0f) .field("double_field", 6.0d) - .field("date_field", Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC))) + .field("date_field", DateFormatters.forPattern("dateOptionalTime").format(date)) .field("boolean_field", true) .field("binary_field", Base64.getEncoder().encodeToString("testing text".getBytes("UTF-8"))) .endObject()).execute().actionGet(); @@ -578,7 +580,6 @@ public void testStoredFieldsWithoutSource() throws Exception { assertThat(fields, equalTo(newHashSet("byte_field", "short_field", "integer_field", "long_field", "float_field", "double_field", "date_field", "boolean_field", "binary_field"))); - SearchHit searchHit = searchResponse.getHits().getAt(0); assertThat(searchHit.getFields().get("byte_field").getValue().toString(), equalTo("1")); assertThat(searchHit.getFields().get("short_field").getValue().toString(), equalTo("2")); @@ -586,7 +587,7 @@ public void testStoredFieldsWithoutSource() throws Exception { assertThat(searchHit.getFields().get("long_field").getValue(), equalTo((Object) 4L)); assertThat(searchHit.getFields().get("float_field").getValue(), equalTo((Object) 5.0f)); assertThat(searchHit.getFields().get("double_field").getValue(), equalTo((Object) 6.0d)); - String dateTime = Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC)); + String dateTime = DateFormatters.forPattern("dateOptionalTime").format(date); assertThat(searchHit.getFields().get("date_field").getValue(), equalTo((Object) dateTime)); assertThat(searchHit.getFields().get("boolean_field").getValue(), equalTo((Object) Boolean.TRUE)); assertThat(searchHit.getFields().get("binary_field").getValue(), equalTo(new BytesArray("testing text" .getBytes("UTF8")))); @@ -756,7 +757,7 @@ public void testDocValueFields() throws Exception { client().admin().indices().preparePutMapping().setType("type1").setSource(mapping, XContentType.JSON).execute().actionGet(); - ReadableDateTime date = new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC); + ZonedDateTime date = ZonedDateTime.of(2012, 3, 22, 0, 0, 0, 0, ZoneOffset.UTC); client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject() .field("text_field", "foo") .field("keyword_field", "foo") @@ -766,7 +767,7 @@ public void testDocValueFields() throws Exception { .field("long_field", 4L) .field("float_field", 5.0f) .field("double_field", 6.0d) - .field("date_field", Joda.forPattern("dateOptionalTime").printer().print(date)) + .field("date_field", DateFormatters.forPattern("dateOptionalTime").format(date)) .field("boolean_field", true) .field("binary_field", new byte[] {42, 100}) .field("ip_field", "::1") @@ -802,7 +803,8 @@ public void testDocValueFields() throws Exception { assertThat(searchResponse.getHits().getAt(0).getFields().get("long_field").getValue(), equalTo((Object) 4L)); assertThat(searchResponse.getHits().getAt(0).getFields().get("float_field").getValue(), equalTo((Object) 5.0)); assertThat(searchResponse.getHits().getAt(0).getFields().get("double_field").getValue(), equalTo((Object) 6.0d)); - assertThat(searchResponse.getHits().getAt(0).getFields().get("date_field").getValue(), equalTo(date)); + assertThat(searchResponse.getHits().getAt(0).getFields().get("date_field").getValue(), + equalTo(new DateTime(date.toInstant().toEpochMilli(), DateTimeZone.UTC))); assertThat(searchResponse.getHits().getAt(0).getFields().get("boolean_field").getValue(), equalTo((Object) true)); assertThat(searchResponse.getHits().getAt(0).getFields().get("text_field").getValue(), equalTo("foo")); assertThat(searchResponse.getHits().getAt(0).getFields().get("keyword_field").getValue(), equalTo("foo")); @@ -839,7 +841,7 @@ public void testDocValueFields() throws Exception { assertThat(searchResponse.getHits().getAt(0).getFields().get("float_field").getValue(), equalTo((Object) 5.0)); assertThat(searchResponse.getHits().getAt(0).getFields().get("double_field").getValue(), equalTo((Object) 6.0d)); assertThat(searchResponse.getHits().getAt(0).getFields().get("date_field").getValue(), - equalTo(Joda.forPattern("dateOptionalTime").printer().print(date))); + equalTo(DateFormatters.forPattern("dateOptionalTime").format(date))); assertThat(searchResponse.getHits().getAt(0).getFields().get("boolean_field").getValue(), equalTo((Object) true)); assertThat(searchResponse.getHits().getAt(0).getFields().get("text_field").getValue(), equalTo("foo")); assertThat(searchResponse.getHits().getAt(0).getFields().get("keyword_field").getValue(), equalTo("foo")); @@ -869,7 +871,7 @@ public void testDocValueFields() throws Exception { assertThat(searchResponse.getHits().getAt(0).getFields().get("float_field").getValue(), equalTo("5.0")); assertThat(searchResponse.getHits().getAt(0).getFields().get("double_field").getValue(), equalTo("6.0")); assertThat(searchResponse.getHits().getAt(0).getFields().get("date_field").getValue(), - equalTo(Joda.forPattern("epoch_millis").printer().print(date))); + equalTo(DateFormatters.forPattern("epoch_millis").format(date))); } public void testScriptFields() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreIT.java b/server/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreIT.java index d6acdf11cb2ab..a21893db3920f 100644 --- a/server/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreIT.java +++ b/server/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreIT.java @@ -43,9 +43,9 @@ import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import org.elasticsearch.test.VersionUtils; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -562,27 +562,27 @@ public void testValueMissingLin() throws Exception { } public void testDateWithoutOrigin() throws Exception { - DateTime dt = new DateTime(DateTimeZone.UTC); + ZonedDateTime dt = ZonedDateTime.now(ZoneOffset.UTC); assertAcked(prepareCreate("test").addMapping( "type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test").field("type", "text") .endObject().startObject("num1").field("type", "date").endObject().endObject().endObject().endObject())); - DateTime docDate = dt.minusDays(1); - String docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-" + ZonedDateTime docDate = dt.minusDays(1); + String docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthValue()) + "-" + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth()); client().index( indexRequest("test").type("type1").id("1") .source(jsonBuilder().startObject().field("test", "value").field("num1", docDateString).endObject())).actionGet(); docDate = dt.minusDays(2); - docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-" + docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthValue()) + "-" + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth()); client().index( indexRequest("test").type("type1").id("2") .source(jsonBuilder().startObject().field("test", "value").field("num1", docDateString).endObject())).actionGet(); docDate = dt.minusDays(3); - docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthOfYear()) + "-" + docDateString = docDate.getYear() + "-" + String.format(Locale.ROOT, "%02d", docDate.getMonthValue()) + "-" + String.format(Locale.ROOT, "%02d", docDate.getDayOfMonth()); client().index( indexRequest("test").type("type1").id("3") diff --git a/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java b/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java index eab3a6e9b4824..be71867edd2a0 100644 --- a/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java +++ b/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java @@ -52,6 +52,9 @@ import org.joda.time.format.ISODateTimeFormat; import java.io.IOException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Collections; import java.util.Random; @@ -480,8 +483,9 @@ public void testDateRangeInQueryString() { "type", "past", "type=date", "future", "type=date" )); - String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1)); - String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1)); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + String aMonthAgo = DateTimeFormatter.ISO_LOCAL_DATE.format(now.minusMonths(1)); + String aMonthFromNow = DateTimeFormatter.ISO_LOCAL_DATE.format(now.plusMonths(1)); client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get(); refresh(); diff --git a/server/src/test/java/org/elasticsearch/validate/SimpleValidateQueryIT.java b/server/src/test/java/org/elasticsearch/validate/SimpleValidateQueryIT.java index 8b3aff90e8d4c..cdbc2c702d8b1 100644 --- a/server/src/test/java/org/elasticsearch/validate/SimpleValidateQueryIT.java +++ b/server/src/test/java/org/elasticsearch/validate/SimpleValidateQueryIT.java @@ -35,12 +35,13 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.hamcrest.Matcher; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.ISODateTimeFormat; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.List; @@ -124,8 +125,9 @@ public void testExplainDateRangeInQueryString() { .put(indexSettings()) .put("index.number_of_shards", 1))); - String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1)); - String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1)); + ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); + String aMonthAgo = DateTimeFormatter.ISO_LOCAL_DATE.format(now.plus(1, ChronoUnit.MONTHS)); + String aMonthFromNow = DateTimeFormatter.ISO_LOCAL_DATE.format(now.minus(1, ChronoUnit.MONTHS)); client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get(); @@ -137,10 +139,10 @@ public void testExplainDateRangeInQueryString() { assertNoFailures(response); assertThat(response.getQueryExplanation().size(), equalTo(1)); assertThat(response.getQueryExplanation().get(0).getError(), nullValue()); - DateTime twoMonthsAgo = new DateTime(DateTimeZone.UTC).minusMonths(2).withTimeAtStartOfDay(); - DateTime now = new DateTime(DateTimeZone.UTC).plusDays(1).withTimeAtStartOfDay().minusMillis(1); - assertThat(response.getQueryExplanation().get(0).getExplanation(), - equalTo("past:[" + twoMonthsAgo.getMillis() + " TO " + now.getMillis() + "]")); + + long twoMonthsAgo = now.minus(2, ChronoUnit.MONTHS).truncatedTo(ChronoUnit.DAYS).toEpochSecond() * 1000; + long rangeEnd = (now.plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS).toEpochSecond() * 1000) - 1; + assertThat(response.getQueryExplanation().get(0).getExplanation(), equalTo("past:[" + twoMonthsAgo + " TO " + rangeEnd + "]")); assertThat(response.isValid(), equalTo(true)); }