Skip to content

Commit 15b997a

Browse files
committed
Core: Don't rely on java time for epoch seconds formatting (#34086)
In order to be compatible with joda time, this adds an epoch seconds formatter, that is able to parse floating point values. However joda time discards the floating point values, but still parses the data, where as this one is able to parse the whole value including milliseconds.
1 parent d3ff18f commit 15b997a

File tree

4 files changed

+126
-13
lines changed

4 files changed

+126
-13
lines changed

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

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -890,17 +890,6 @@ public class DateFormatters {
890890
private static final DateFormatter YEAR = new JavaDateFormatter("year",
891891
new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR).toFormatter(Locale.ROOT));
892892

893-
/*
894-
* Returns a formatter for parsing the seconds since the epoch
895-
*/
896-
private static final DateFormatter EPOCH_SECOND = new JavaDateFormatter("epoch_second",
897-
new DateTimeFormatterBuilder().appendValue(ChronoField.INSTANT_SECONDS).toFormatter(Locale.ROOT));
898-
899-
/*
900-
* Parses the milliseconds since/before the epoch
901-
*/
902-
private static final DateFormatter EPOCH_MILLIS = EpochMillisDateFormatter.INSTANCE;
903-
904893
/*
905894
* Returns a formatter that combines a full date and two digit hour of
906895
* day. (yyyy-MM-dd'T'HH)
@@ -1375,9 +1364,9 @@ public static DateFormatter forPattern(String input, Locale locale) {
13751364
} else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
13761365
return YEAR_MONTH_DAY;
13771366
} else if ("epoch_second".equals(input)) {
1378-
return EPOCH_SECOND;
1367+
return EpochSecondsDateFormatter.INSTANCE;
13791368
} else if ("epoch_millis".equals(input)) {
1380-
return EPOCH_MILLIS;
1369+
return EpochMillisDateFormatter.INSTANCE;
13811370
// strict date formats here, must be at least 4 digits for year and two for months and two for day
13821371
} else if ("strictBasicWeekDate".equals(input) || "strict_basic_week_date".equals(input)) {
13831372
return STRICT_BASIC_WEEK_DATE;
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.common.time;
21+
22+
import java.math.BigDecimal;
23+
import java.time.Instant;
24+
import java.time.ZoneId;
25+
import java.time.ZoneOffset;
26+
import java.time.format.DateTimeParseException;
27+
import java.time.temporal.TemporalAccessor;
28+
import java.time.temporal.TemporalField;
29+
import java.util.Map;
30+
import java.util.regex.Pattern;
31+
32+
public class EpochSecondsDateFormatter implements DateFormatter {
33+
34+
public static DateFormatter INSTANCE = new EpochSecondsDateFormatter();
35+
private static final Pattern SPLIT_BY_DOT_PATTERN = Pattern.compile("\\.");
36+
37+
private EpochSecondsDateFormatter() {}
38+
39+
@Override
40+
public TemporalAccessor parse(String input) {
41+
try {
42+
if (input.contains(".")) {
43+
String[] inputs = SPLIT_BY_DOT_PATTERN.split(input, 2);
44+
Long seconds = Long.valueOf(inputs[0]);
45+
if (inputs[1].length() == 0) {
46+
// this is BWC compatible to joda time, nothing after the dot is allowed
47+
return Instant.ofEpochSecond(seconds, 0).atZone(ZoneOffset.UTC);
48+
}
49+
if (inputs[1].length() > 9) {
50+
throw new DateTimeParseException("too much granularity after dot [" + input + "]", input, 0);
51+
}
52+
Long nanos = new BigDecimal(inputs[1]).movePointRight(9 - inputs[1].length()).longValueExact();
53+
return Instant.ofEpochSecond(seconds, nanos).atZone(ZoneOffset.UTC);
54+
} else {
55+
return Instant.ofEpochSecond(Long.valueOf(input)).atZone(ZoneOffset.UTC);
56+
}
57+
} catch (NumberFormatException e) {
58+
throw new DateTimeParseException("invalid number [" + input + "]", input, 0, e);
59+
}
60+
}
61+
62+
@Override
63+
public DateFormatter withZone(ZoneId zoneId) {
64+
return this;
65+
}
66+
67+
@Override
68+
public String format(TemporalAccessor accessor) {
69+
Instant instant = Instant.from(accessor);
70+
if (instant.getNano() != 0) {
71+
return String.valueOf(instant.getEpochSecond()) + "." + String.valueOf(instant.getNano()).replaceAll("0*$", "");
72+
}
73+
return String.valueOf(instant.getEpochSecond());
74+
}
75+
76+
@Override
77+
public String pattern() {
78+
return "epoch_seconds";
79+
}
80+
81+
@Override
82+
public DateFormatter parseDefaulting(Map<TemporalField, Long> fields) {
83+
return this;
84+
}
85+
}

server/src/test/java/org/elasticsearch/common/joda/JavaJodaTimeDuellingTests.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ public void testCustomTimeFormats() {
7171

7272
public void testDuellingFormatsValidParsing() {
7373
assertSameDate("1522332219", "epoch_second");
74+
assertSameDate("1522332219.", "epoch_second");
75+
assertSameDate("1522332219.0", "epoch_second");
7476
assertSameDate("0", "epoch_second");
7577
assertSameDate("1", "epoch_second");
7678
assertSameDate("-1", "epoch_second");

server/src/test/java/org/elasticsearch/common/time/DateFormattersTests.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import org.elasticsearch.test.ESTestCase;
2323

24+
import java.time.Instant;
2425
import java.time.ZoneId;
2526
import java.time.ZonedDateTime;
2627
import java.time.format.DateTimeParseException;
@@ -56,6 +57,42 @@ public void testEpochMilliParser() {
5657
assertSameFormat(formatter, 1);
5758
}
5859

60+
// this is not in the duelling tests, because the epoch second parser in joda time drops the milliseconds after the comma
61+
// but is able to parse the rest
62+
// as this feature is supported it also makes sense to make it exact
63+
public void testEpochSecondParser() {
64+
DateFormatter formatter = DateFormatters.forPattern("epoch_second");
65+
66+
assertThat(Instant.from(formatter.parse("1234.567")).toEpochMilli(), is(1234567L));
67+
assertThat(Instant.from(formatter.parse("1234.")).getNano(), is(0));
68+
assertThat(Instant.from(formatter.parse("1234.")).getEpochSecond(), is(1234L));
69+
assertThat(Instant.from(formatter.parse("1234.1")).getNano(), is(100_000_000));
70+
assertThat(Instant.from(formatter.parse("1234.12")).getNano(), is(120_000_000));
71+
assertThat(Instant.from(formatter.parse("1234.123")).getNano(), is(123_000_000));
72+
assertThat(Instant.from(formatter.parse("1234.1234")).getNano(), is(123_400_000));
73+
assertThat(Instant.from(formatter.parse("1234.12345")).getNano(), is(123_450_000));
74+
assertThat(Instant.from(formatter.parse("1234.123456")).getNano(), is(123_456_000));
75+
assertThat(Instant.from(formatter.parse("1234.1234567")).getNano(), is(123_456_700));
76+
assertThat(Instant.from(formatter.parse("1234.12345678")).getNano(), is(123_456_780));
77+
assertThat(Instant.from(formatter.parse("1234.123456789")).getNano(), is(123_456_789));
78+
DateTimeParseException e = expectThrows(DateTimeParseException.class, () -> formatter.parse("1234.1234567890"));
79+
assertThat(e.getMessage(), is("too much granularity after dot [1234.1234567890]"));
80+
e = expectThrows(DateTimeParseException.class, () -> formatter.parse("1234.123456789013221"));
81+
assertThat(e.getMessage(), is("too much granularity after dot [1234.123456789013221]"));
82+
e = expectThrows(DateTimeParseException.class, () -> formatter.parse("abc"));
83+
assertThat(e.getMessage(), is("invalid number [abc]"));
84+
e = expectThrows(DateTimeParseException.class, () -> formatter.parse("1234.abc"));
85+
assertThat(e.getMessage(), is("invalid number [1234.abc]"));
86+
87+
// different zone, should still yield the same output, as epoch is time zone independent
88+
ZoneId zoneId = randomZone();
89+
DateFormatter zonedFormatter = formatter.withZone(zoneId);
90+
91+
assertThatSameDateTime(formatter, zonedFormatter, randomLongBetween(-100_000_000, 100_000_000));
92+
assertSameFormat(formatter, randomLongBetween(-100_000_000, 100_000_000));
93+
assertThat(formatter.format(Instant.ofEpochSecond(1234, 567_000_000)), is("1234.567"));
94+
}
95+
5996
public void testEpochMilliParsersWithDifferentFormatters() {
6097
DateFormatter formatter = DateFormatters.forPattern("strict_date_optional_time||epoch_millis");
6198
TemporalAccessor accessor = formatter.parse("123");

0 commit comments

Comments
 (0)