Support multiple style of parsing/printing Durations

This commit introduces a notion of different styles for the formatting
of Duration.
The `@DurationFormat` annotation is added to ease selection of a style,
which are represented as DurationFormat.Style enum, as well as a
supported time unit represented as DurationFormat.Unit enum.

DurationFormatter has been retroffited to take such a Style,
optionally, at construction. The default is still the JDK style a.k.a.
ISO-8601.

This introduces the new SIMPLE style which uses a single number + a
short human-readable suffix. For instance "-3ms" or "2h".

This has the same semantics as the DurationStyle in Spring Boot and
is intended as a replacement for that feature, providing access to the
feature to projects that only depend on Spring Framework.

Finally, the `@Scheduled` annotation is improved by adding detection
of the style and parsing for the String versions of initial delay, fixed
delay and fixed rate.

See gh-22013
See gh-22474

Closes gh-30396
This commit is contained in:
Simon Baslé
2024-07-23 11:53:35 +02:00
committed by Brian Clozel
parent d219362eb1
commit c92e043bbc
13 changed files with 875 additions and 42 deletions

View File

@@ -53,6 +53,8 @@ import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.annotation.DurationFormat;
import org.springframework.format.annotation.DurationFormat.Style;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
@@ -484,6 +486,17 @@ class DateTimeFormattingTests {
assertThat(binder.getBindingResult().getFieldValue("duration").toString()).isEqualTo("PT8H6M12.345S");
}
@Test
void testBindDurationAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("styleDuration", "2ms");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getFieldValue("styleDuration"))
.isNotNull()
.isEqualTo("2000us");
assertThat(binder.getBindingResult().getAllErrors()).isEmpty();
}
@Test
void testBindYear() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
@@ -711,6 +724,9 @@ class DateTimeFormattingTests {
private Duration duration;
@DurationFormat(style = Style.SIMPLE, defaultUnit = DurationFormat.Unit.MICROS)
private Duration styleDuration;
private Year year;
private Month month;
@@ -870,6 +886,14 @@ class DateTimeFormattingTests {
this.duration = duration;
}
public Duration getStyleDuration() {
return this.styleDuration;
}
public void setStyleDuration(Duration styleDuration) {
this.styleDuration = styleDuration;
}
public Year getYear() {
return this.year;
}

View File

@@ -0,0 +1,297 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.datetime.standard;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.format.annotation.DurationFormat.Unit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.format.annotation.DurationFormat.Style.ISO8601;
import static org.springframework.format.annotation.DurationFormat.Style.SIMPLE;
/**
* Tests for {@link DurationFormatterUtils}.
*/
class DurationFormatterUtilsTests {
@Test
void parseSimpleWithUnits() {
Duration nanos = DurationFormatterUtils.parse("1ns", SIMPLE, Unit.SECONDS);
Duration micros = DurationFormatterUtils.parse("-2us", SIMPLE, Unit.SECONDS);
Duration millis = DurationFormatterUtils.parse("+3ms", SIMPLE, Unit.SECONDS);
Duration seconds = DurationFormatterUtils.parse("4s", SIMPLE, Unit.SECONDS);
Duration minutes = DurationFormatterUtils.parse("5m", SIMPLE, Unit.SECONDS);
Duration hours = DurationFormatterUtils.parse("6h", SIMPLE, Unit.SECONDS);
Duration days = DurationFormatterUtils.parse("-10d", SIMPLE, Unit.SECONDS);
assertThat(nanos).hasNanos(1);
assertThat(micros).hasNanos(-2 * 1000);
assertThat(millis).hasMillis(3);
assertThat(seconds).hasSeconds(4);
assertThat(minutes).hasMinutes(5);
assertThat(hours).hasHours(6);
assertThat(days).hasDays(-10);
}
@Test
void parseSimpleWithoutUnits() {
assertThat(DurationFormatterUtils.parse("-123", SIMPLE, Unit.SECONDS))
.hasSeconds(-123);
assertThat(DurationFormatterUtils.parse("456", SIMPLE, Unit.SECONDS))
.hasSeconds(456);
}
@Test
void parseNoChronoUnitSimpleWithoutUnitsDefaultsToMillis() {
assertThat(DurationFormatterUtils.parse("-123", SIMPLE))
.hasMillis(-123);
assertThat(DurationFormatterUtils.parse("456", SIMPLE))
.hasMillis(456);
}
@Test
void parseNullChronoUnitSimpleWithoutUnitsDefaultsToMillis() {
assertThat(DurationFormatterUtils.parse("-123", SIMPLE, null))
.hasMillis(-123);
assertThat(DurationFormatterUtils.parse("456", SIMPLE, null))
.hasMillis(456);
}
@Test
void parseSimpleThrows() {
assertThatIllegalArgumentException().isThrownBy(() -> DurationFormatterUtils.parse(";23s", SIMPLE))
.withMessage("';23s' is not a valid simple duration")
.withCause(new IllegalStateException("Does not match simple duration pattern"));
assertThatIllegalArgumentException().isThrownBy(() -> DurationFormatterUtils.parse("+23y", SIMPLE))
.withMessage("'+23y' is not a valid simple duration")
.withCause(new IllegalArgumentException("'y' is not a valid simple duration Unit"));
}
@Test
void parseIsoNoChronoUnit() {
//these are based on the examples given in Duration.parse
// "PT20.345S" -- parses as "20.345 seconds"
assertThat(DurationFormatterUtils.parse("PT20.345S", ISO8601))
.hasMillis(20345);
// "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
assertThat(DurationFormatterUtils.parse("PT15M", ISO8601))
.hasSeconds(15*60);
// "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
assertThat(DurationFormatterUtils.parse("PT10H", ISO8601))
.hasHours(10);
// "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
assertThat(DurationFormatterUtils.parse("P2D", ISO8601))
.hasDays(2);
// "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
assertThat(DurationFormatterUtils.parse("P2DT3H4M", ISO8601))
.isEqualTo(Duration.ofDays(2).plusHours(3).plusMinutes(4));
// "PT-6H3M" -- parses as "-6 hours and +3 minutes"
assertThat(DurationFormatterUtils.parse("PT-6H3M", ISO8601))
.isEqualTo(Duration.ofHours(-6).plusMinutes(3));
// "-PT6H3M" -- parses as "-6 hours and -3 minutes"
assertThat(DurationFormatterUtils.parse("-PT6H3M", ISO8601))
.isEqualTo(Duration.ofHours(-6).plusMinutes(-3));
// "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"
assertThat(DurationFormatterUtils.parse("-PT-6H+3M", ISO8601))
.isEqualTo(Duration.ofHours(6).plusMinutes(-3));
}
@Test
void parseIsoIgnoresFallbackChronoUnit() {
assertThat(DurationFormatterUtils.parse("P2DT3H4M", ISO8601, Unit.NANOS))
.isEqualTo(Duration.ofDays(2).plusHours(3).plusMinutes(4));
}
@Test
void parseIsoThrows() {
assertThatIllegalArgumentException().isThrownBy(() -> DurationFormatterUtils.parse("P2DWV3H-4M", ISO8601))
.withMessage("'P2DWV3H-4M' is not a valid ISO-8601 duration")
.withCause(new DateTimeParseException("Text cannot be parsed to a Duration", "", 0));
}
@Test
void printSimple() {
assertThat(DurationFormatterUtils.print(Duration.ofNanos(12345), SIMPLE, Unit.NANOS))
.isEqualTo("12345ns");
assertThat(DurationFormatterUtils.print(Duration.ofNanos(-12345), SIMPLE, Unit.MICROS))
.isEqualTo("-12us");
}
@Test
void printSimpleNoChronoUnit() {
assertThat(DurationFormatterUtils.print(Duration.ofNanos(12345), SIMPLE))
.isEqualTo("0ms");
assertThat(DurationFormatterUtils.print(Duration.ofSeconds(-3), SIMPLE))
.isEqualTo("-3000ms");
}
@Test
void printIsoNoChronoUnit() {
assertThat(DurationFormatterUtils.print(Duration.ofNanos(12345), ISO8601))
.isEqualTo("PT0.000012345S");
assertThat(DurationFormatterUtils.print(Duration.ofSeconds(-3), ISO8601))
.isEqualTo("PT-3S");
}
@Test
void printIsoIgnoresChronoUnit() {
assertThat(DurationFormatterUtils.print(Duration.ofNanos(12345), ISO8601, Unit.HOURS))
.isEqualTo("PT0.000012345S");
assertThat(DurationFormatterUtils.print(Duration.ofSeconds(-3), ISO8601, Unit.HOURS))
.isEqualTo("PT-3S");
}
@Test
void detectAndParse() {
assertThat(DurationFormatterUtils.detectAndParse("PT1.234S", Unit.NANOS))
.as("iso")
.isEqualTo(Duration.ofMillis(1234));
assertThat(DurationFormatterUtils.detectAndParse("1234ms", Unit.NANOS))
.as("simple with explicit unit")
.isEqualTo(Duration.ofMillis(1234));
assertThat(DurationFormatterUtils.detectAndParse("1234", Unit.NANOS))
.as("simple without suffix")
.isEqualTo(Duration.ofNanos(1234));
}
@Test
void detectAndParseNoChronoUnit() {
assertThat(DurationFormatterUtils.detectAndParse("PT1.234S"))
.as("iso")
.isEqualTo(Duration.ofMillis(1234));
assertThat(DurationFormatterUtils.detectAndParse("1234ms"))
.as("simple with explicit unit")
.isEqualTo(Duration.ofMillis(1234));
assertThat(DurationFormatterUtils.detectAndParse("1234"))
.as("simple without suffix")
.isEqualTo(Duration.ofMillis(1234));
}
@Test
void detect() {
assertThat(DurationFormatterUtils.detect("+3ms"))
.as("SIMPLE")
.isEqualTo(SIMPLE);
assertThat(DurationFormatterUtils.detect("-10y"))
.as("invalid yet matching SIMPLE pattern")
.isEqualTo(SIMPLE);
assertThat(DurationFormatterUtils.detect("P2DT3H-4M"))
.as("ISO8601")
.isEqualTo(ISO8601);
assertThat(DurationFormatterUtils.detect("P2DWV3H-4M"))
.as("invalid yet matching ISO8601 pattern")
.isEqualTo(ISO8601);
assertThatIllegalArgumentException().isThrownBy(() -> DurationFormatterUtils.detect("WPT2H-4M"))
.withMessage("'WPT2H-4M' is not a valid duration, cannot detect any known style")
.withNoCause();
}
@Nested
class DurationFormatUnit {
@Test
void longValueFromUnit() {
Duration nanos = Duration.ofSeconds(3).plusMillis(22).plusNanos(1111);
assertThat(Unit.NANOS.longValue(nanos))
.as("NANOS")
.isEqualTo(3022001111L);
assertThat(Unit.MICROS.longValue(nanos))
.as("MICROS")
.isEqualTo(3022001);
assertThat(Unit.MILLIS.longValue(nanos))
.as("MILLIS")
.isEqualTo(3022);
assertThat(Unit.SECONDS.longValue(nanos))
.as("SECONDS")
.isEqualTo(3);
Duration minutes = Duration.ofHours(1).plusMinutes(23);
assertThat(Unit.MINUTES.longValue(minutes))
.as("MINUTES")
.isEqualTo(83);
assertThat(Unit.HOURS.longValue(minutes))
.as("HOURS")
.isEqualTo(1);
Duration days = Duration.ofHours(48 + 5);
assertThat(Unit.HOURS.longValue(days))
.as("HOURS in days")
.isEqualTo(53);
assertThat(Unit.DAYS.longValue(days))
.as("DAYS")
.isEqualTo(2);
}
@Test
void unitFromSuffix() {
assertThat(Unit.fromSuffix("ns")).as("ns").isEqualTo(Unit.NANOS);
assertThat(Unit.fromSuffix("us")).as("us").isEqualTo(Unit.MICROS);
assertThat(Unit.fromSuffix("ms")).as("ms").isEqualTo(Unit.MILLIS);
assertThat(Unit.fromSuffix("s")).as("s").isEqualTo(Unit.SECONDS);
assertThat(Unit.fromSuffix("m")).as("m").isEqualTo(Unit.MINUTES);
assertThat(Unit.fromSuffix("h")).as("h").isEqualTo(Unit.HOURS);
assertThat(Unit.fromSuffix("d")).as("d").isEqualTo(Unit.DAYS);
assertThatIllegalArgumentException().isThrownBy(() -> Unit.fromSuffix("ws"))
.withMessage("'ws' is not a valid simple duration Unit");
}
@Test
void unitFromChronoUnit() {
assertThat(Unit.fromChronoUnit(ChronoUnit.NANOS)).as("ns").isEqualTo(Unit.NANOS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MICROS)).as("us").isEqualTo(Unit.MICROS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MILLIS)).as("ms").isEqualTo(Unit.MILLIS);
assertThat(Unit.fromChronoUnit(ChronoUnit.SECONDS)).as("s").isEqualTo(Unit.SECONDS);
assertThat(Unit.fromChronoUnit(ChronoUnit.MINUTES)).as("m").isEqualTo(Unit.MINUTES);
assertThat(Unit.fromChronoUnit(ChronoUnit.HOURS)).as("h").isEqualTo(Unit.HOURS);
assertThat(Unit.fromChronoUnit(ChronoUnit.DAYS)).as("d").isEqualTo(Unit.DAYS);
assertThatIllegalArgumentException().isThrownBy(() -> Unit.fromChronoUnit(ChronoUnit.CENTURIES))
.withMessage("No matching Unit for ChronoUnit.CENTURIES");
}
@Test
void unitSuffixSmokeTest() {
assertThat(Arrays.stream(Unit.values()).map(u -> u.name() + "->" + u.asSuffix()))
.containsExactly("NANOS->ns", "MICROS->us", "MILLIS->ms", "SECONDS->s",
"MINUTES->m", "HOURS->h", "DAYS->d");
}
@Test
void chronoUnitSmokeTest() {
assertThat(Arrays.stream(Unit.values()).map(Unit::asChronoUnit))
.containsExactly(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS);
}
}
}

View File

@@ -496,8 +496,10 @@ class ScheduledAnnotationBeanPostProcessorTests {
@CsvSource(textBlock = """
PropertyPlaceholderWithFixedDelay, 5000, 1000, 5_000, 1_000
PropertyPlaceholderWithFixedDelay, PT5S, PT1S, 5_000, 1_000
PropertyPlaceholderWithFixedDelay, 5400ms, 1s, 5_400, 1_000
PropertyPlaceholderWithFixedDelayInSeconds, 5000, 1000, 5_000_000, 1_000_000
PropertyPlaceholderWithFixedDelayInSeconds, PT5S, PT1S, 5_000, 1_000
PropertyPlaceholderWithFixedDelayInSeconds, 5400ms, 500ms, 5_400, 500
""")
void propertyPlaceholderWithFixedDelay(@NameToClass Class<?> beanClass, String fixedDelay, String initialDelay,
long expectedInterval, long expectedInitialDelay) {
@@ -536,8 +538,10 @@ class ScheduledAnnotationBeanPostProcessorTests {
@CsvSource(textBlock = """
PropertyPlaceholderWithFixedRate, 3000, 1000, 3_000, 1_000
PropertyPlaceholderWithFixedRate, PT3S, PT1S, 3_000, 1_000
PropertyPlaceholderWithFixedRate, 3200ms, 1s, 3_200, 1_000
PropertyPlaceholderWithFixedRateInSeconds, 3000, 1000, 3_000_000, 1_000_000
PropertyPlaceholderWithFixedRateInSeconds, PT3S, PT1S, 3_000, 1_000
PropertyPlaceholderWithFixedRateInSeconds, 3200ms, 500ms, 3_200, 500
""")
void propertyPlaceholderWithFixedRate(@NameToClass Class<?> beanClass, String fixedRate, String initialDelay,
long expectedInterval, long expectedInitialDelay) {