This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-cli.git
The following commit(s) were added to refs/heads/master by this push:
new 8010193e reject invalid dates in Converter.DATE (#430)
8010193e is described below
commit 8010193eec848982cb4618a0a31487aca76851a2
Author: Naveed Khan <[email protected]>
AuthorDate: Sat Jul 11 19:00:50 2026 +0000
reject invalid dates in Converter.DATE (#430)
---
src/main/java/org/apache/commons/cli/Converter.java | 9 +++++++--
src/test/java/org/apache/commons/cli/ConverterTests.java | 8 ++++++++
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/src/main/java/org/apache/commons/cli/Converter.java
b/src/main/java/org/apache/commons/cli/Converter.java
index a984ad04..fcb9c43b 100644
--- a/src/main/java/org/apache/commons/cli/Converter.java
+++ b/src/main/java/org/apache/commons/cli/Converter.java
@@ -79,12 +79,17 @@ public interface Converter<T, E extends Exception> {
*/
Converter<Date, java.text.ParseException> DATE = s -> {
final String pattern = "EEE MMM dd HH:mm:ss zzz yyyy";
+ final SimpleDateFormat format = new SimpleDateFormat(pattern);
+ // reject out-of-range fields (for example "Feb 30") instead of
silently rolling them over.
+ format.setLenient(false);
try {
- return new SimpleDateFormat(pattern).parse(s);
+ return format.parse(s);
} catch (final java.text.ParseException e) {
// Date.toString() always emits English month/day names, so fall
back to Locale.ENGLISH
// when the default locale rejects the documented format.
- return new SimpleDateFormat(pattern, Locale.ENGLISH).parse(s);
+ final SimpleDateFormat englishFormat = new
SimpleDateFormat(pattern, Locale.ENGLISH);
+ englishFormat.setLenient(false);
+ return englishFormat.parse(s);
}
};
diff --git a/src/test/java/org/apache/commons/cli/ConverterTests.java
b/src/test/java/org/apache/commons/cli/ConverterTests.java
index a92a1355..1f5efad5 100644
--- a/src/test/java/org/apache/commons/cli/ConverterTests.java
+++ b/src/test/java/org/apache/commons/cli/ConverterTests.java
@@ -104,6 +104,14 @@ public class ConverterTests {
assertEquals(expected, Converter.DATE.apply(formatted));
}
+ @Test
+ void testDateRejectsInvalid() {
+ // A lenient SimpleDateFormat rolls "Feb 30" over to March 1; the
converter must reject
+ // out-of-range fields instead of silently returning a wrong Date.
+ assertThrows(java.text.ParseException.class, () ->
Converter.DATE.apply("Fri Feb 30 12:00:00 UTC 2024"));
+ assertThrows(java.text.ParseException.class, () ->
Converter.DATE.apply("Mon Jan 32 00:00:00 UTC 2024"));
+ }
+
@Test
void testFile() throws Exception {
final URL url =
this.getClass().getClassLoader().getResource("./org/apache/commons/cli/existing-readable.file");