-
Notifications
You must be signed in to change notification settings - Fork 24.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Parse composite patterns using ClassicFormat.parseObject backport(#40100) #40503
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7a08082
Parse composite patterns using ClassicFormat.parseObject (#40100)
pgomulka 860d8e1
refactor tests to new messages/exceptiosn throw
pgomulka b06cdcd
code style
pgomulka f3b03bb
Merge branch '6.7' of github.com:elastic/elasticsearch into 6.7
pgomulka d040c4d
javadoc and cleanup
pgomulka 358d761
javadoc update
pgomulka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,14 +21,19 @@ | |
|
||
import org.elasticsearch.common.Strings; | ||
|
||
import java.text.ParsePosition; | ||
import java.time.ZoneId; | ||
import java.time.format.DateTimeFormatter; | ||
import java.time.format.DateTimeFormatterBuilder; | ||
import java.time.format.DateTimeParseException; | ||
import java.time.temporal.ChronoField; | ||
import java.time.temporal.TemporalAccessor; | ||
import java.time.temporal.TemporalField; | ||
import java.util.Arrays; | ||
import java.util.Collection; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Locale; | ||
import java.util.Map; | ||
import java.util.Objects; | ||
|
@@ -38,6 +43,7 @@ class JavaDateFormatter implements DateFormatter { | |
|
||
// base fields which should be used for default parsing, when we round up for date math | ||
private static final Map<TemporalField, Long> ROUND_UP_BASE_FIELDS = new HashMap<>(6); | ||
|
||
{ | ||
ROUND_UP_BASE_FIELDS.put(ChronoField.MONTH_OF_YEAR, 1L); | ||
ROUND_UP_BASE_FIELDS.put(ChronoField.DAY_OF_MONTH, 1L); | ||
|
@@ -49,22 +55,15 @@ class JavaDateFormatter implements DateFormatter { | |
|
||
private final String format; | ||
private final DateTimeFormatter printer; | ||
private final DateTimeFormatter parser; | ||
private final List<DateTimeFormatter> parsers; | ||
private final DateTimeFormatter roundupParser; | ||
|
||
private JavaDateFormatter(String format, DateTimeFormatter printer, DateTimeFormatter roundupParser, DateTimeFormatter parser) { | ||
this.format = "8" + format; | ||
this.printer = printer; | ||
this.roundupParser = roundupParser; | ||
this.parser = parser; | ||
} | ||
|
||
JavaDateFormatter(String format, DateTimeFormatter printer, DateTimeFormatter... parsers) { | ||
this(format, printer, builder -> ROUND_UP_BASE_FIELDS.forEach(builder::parseDefaulting), parsers); | ||
} | ||
|
||
JavaDateFormatter(String format, DateTimeFormatter printer, Consumer<DateTimeFormatterBuilder> roundupParserConsumer, | ||
DateTimeFormatter... parsers) { | ||
DateTimeFormatter... parsers) { | ||
if (printer == null) { | ||
throw new IllegalArgumentException("printer may not be null"); | ||
} | ||
|
@@ -76,28 +75,23 @@ private JavaDateFormatter(String format, DateTimeFormatter printer, DateTimeForm | |
if (distinctLocales > 1) { | ||
throw new IllegalArgumentException("formatters must have the same locale"); | ||
} | ||
this.printer = printer; | ||
this.format = "8" + format; | ||
|
||
if (parsers.length == 0) { | ||
this.parser = printer; | ||
} else if (parsers.length == 1) { | ||
this.parser = parsers[0]; | ||
this.parsers = Collections.singletonList(printer); | ||
} else { | ||
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); | ||
for (DateTimeFormatter parser : parsers) { | ||
builder.appendOptional(parser); | ||
} | ||
this.parser = builder.toFormatter(Locale.ROOT); | ||
this.parsers = Arrays.asList(parsers); | ||
} | ||
this.format = "8" + format; | ||
this.printer = printer; | ||
|
||
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); | ||
if (format.contains("||") == false) { | ||
builder.append(this.parser); | ||
builder.append(this.parsers.get(0)); | ||
} | ||
roundupParserConsumer.accept(builder); | ||
DateTimeFormatter roundupFormatter = builder.toFormatter(parser.getLocale()); | ||
DateTimeFormatter roundupFormatter = builder.toFormatter(locale()); | ||
if (printer.getZone() != null) { | ||
roundupFormatter = roundupFormatter.withZone(printer.getZone()); | ||
roundupFormatter = roundupFormatter.withZone(zone()); | ||
} | ||
this.roundupParser = roundupFormatter; | ||
} | ||
|
@@ -106,10 +100,6 @@ DateTimeFormatter getRoundupParser() { | |
return roundupParser; | ||
} | ||
|
||
DateTimeFormatter getParser() { | ||
return parser; | ||
} | ||
|
||
DateTimeFormatter getPrinter() { | ||
return printer; | ||
} | ||
|
@@ -119,27 +109,66 @@ public TemporalAccessor parse(String input) { | |
if (Strings.isNullOrEmpty(input)) { | ||
throw new IllegalArgumentException("cannot parse empty date"); | ||
} | ||
return parser.parse(input); | ||
|
||
try { | ||
return doParse(input); | ||
} catch (DateTimeParseException e) { | ||
throw new IllegalArgumentException("failed to parse date field [" + input + "] with format [" + format + "]", e); | ||
} | ||
} | ||
|
||
/** | ||
* Attempt parsing the input without throwing exception. If multiple parsers are provided, | ||
* it will continue iterating if the previous parser failed. The pattern must fully match, meaning whole input was used. | ||
* This also means that this method depends on <code>DateTimeFormatter.ClassicFormat.parseObject</code> | ||
* which does not throw exceptions when parsing failed. | ||
* | ||
* The approach with collection of parsers was taken because java-time requires ordering on optional (composite) | ||
* patterns. Joda does not suffer from this. | ||
* https://bugs.openjdk.java.net/browse/JDK-8188771 | ||
* | ||
* @param input An arbitrary string resembling the string representation of a date or time | ||
* @return a TemporalAccessor if parsing was successful. | ||
* @throws DateTimeParseException when unable to parse with any parsers | ||
*/ | ||
private TemporalAccessor doParse(String input) { | ||
if (parsers.size() > 1) { | ||
for (DateTimeFormatter formatter : parsers) { | ||
ParsePosition pos = new ParsePosition(0); | ||
Object object = formatter.toFormat().parseObject(input, pos); | ||
if (parsingSucceeded(object, input, pos) == true) { | ||
return (TemporalAccessor) object; | ||
} | ||
} | ||
throw new DateTimeParseException("Failed to parse with all enclosed parsers", input, 0); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because we iterate over parsers we would not know exact failure reason for each parsers. Tests that assert about the exact reason (like position where it failed) had to be changed |
||
} | ||
return this.parsers.get(0).parse(input); | ||
} | ||
|
||
private boolean parsingSucceeded(Object object, String input, ParsePosition pos) { | ||
return object != null && pos.getIndex() == input.length(); | ||
} | ||
|
||
@Override | ||
public DateFormatter withZone(ZoneId zoneId) { | ||
// shortcurt to not create new objects unnecessarily | ||
if (zoneId.equals(parser.getZone())) { | ||
if (zoneId.equals(zone())) { | ||
return this; | ||
} | ||
|
||
return new JavaDateFormatter(format, printer.withZone(zoneId), roundupParser.withZone(zoneId), parser.withZone(zoneId)); | ||
return new JavaDateFormatter(format, printer.withZone(zoneId), | ||
parsers.stream().map(p -> p.withZone(zoneId)).toArray(size -> new DateTimeFormatter[size])); | ||
} | ||
|
||
@Override | ||
public DateFormatter withLocale(Locale locale) { | ||
// shortcurt to not create new objects unnecessarily | ||
if (locale.equals(parser.getLocale())) { | ||
if (locale.equals(locale())) { | ||
return this; | ||
} | ||
|
||
return new JavaDateFormatter(format, printer.withLocale(locale), roundupParser.withLocale(locale), parser.withLocale(locale)); | ||
return new JavaDateFormatter(format, printer.withLocale(locale), | ||
parsers.stream().map(p -> p.withLocale(locale)).toArray(size -> new DateTimeFormatter[size])); | ||
} | ||
|
||
@Override | ||
|
@@ -164,7 +193,7 @@ public ZoneId zone() { | |
|
||
@Override | ||
public DateMathParser toDateMathParser() { | ||
return new JavaDateMathParser(format, parser, roundupParser); | ||
return new JavaDateMathParser(format, this, getRoundupParser()); | ||
} | ||
|
||
@Override | ||
|
@@ -180,12 +209,16 @@ public boolean equals(Object obj) { | |
JavaDateFormatter other = (JavaDateFormatter) obj; | ||
|
||
return Objects.equals(format, other.format) && | ||
Objects.equals(locale(), other.locale()) && | ||
Objects.equals(this.printer.getZone(), other.printer.getZone()); | ||
Objects.equals(locale(), other.locale()) && | ||
Objects.equals(this.printer.getZone(), other.printer.getZone()); | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return String.format(Locale.ROOT, "format[%s] locale[%s]", format, locale()); | ||
} | ||
|
||
Collection<DateTimeFormatter> getParsers() { | ||
return parsers; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This means that this method will never throw
DateTimeParseException
as mentioned in the Javadoc ofDateFormatter#parse
. Can you please update the Javadoc there to reflect this change?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually the javadoc for the interface could state RuntimeException to be absolutely correct, but it would be very imprecise.
JodaDateFormatter
can throwjava.time.DateTimeException
as well asUnsupportedOperationException
andIllegalArgumentException
JavaDateFormatter
onlyIllegalArgumentException
.NullPointerException
is stated in the underlying doc forFormat.parseObject
but I don't expect this to be thrown as we already check for input not being empty and provide the position of parsing.I will refactor the javadoc to state that
IllegalArgumentException
is expected to be thrown when parsing fails (that applies in both cases). But I wonder if we should ommit theDateTimeException
andUnsupportedOperationException
(thrown only by joda)This problem also exists in master
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think there is no point in digging through the complete implementation of Java time and Joda time in order to come up with a Javadoc that documents all possible exceptions but rather document the ones that a user can "reasonably" expect when a date cannot be parsed which is in our case
java.time.DateTimeException
fromJodaDateFormatter
andIllegalArgumentException
(from both) so they know how to deal with them.IMHO it is ok to document both of them on the interface. Although one of them is in fact thrown by only one of the implementations, the exception type itself is available in the JDK and thus generic enough and we should expect users to program against the interface.