From dc4d71f91edae5266526e87869a0665127930102 Mon Sep 17 00:00:00 2001 From: Grubhart Date: Sat, 25 Apr 2020 11:40:40 -0500 Subject: [PATCH 1/2] Add Period converter support Add converter support for `javax.time.Period` including: String -> Period Number -> Period Period -> String Period to Number conversion is not supported since `Period` has no ability to deduce the number of calendar days in the period. See gh-21136 --- .../javac/JavaCompilerFieldValuesParser.java | 19 +- .../AbstractFieldValuesProcessorTests.java | 7 +- .../fieldvalues/FieldValues.java | 13 +- .../convert/ApplicationConversionService.java | 5 +- .../boot/convert/NumberToPeriodConverter.java | 51 ++++ .../boot/convert/PeriodFormat.java | 45 +++ .../boot/convert/PeriodStyle.java | 258 ++++++++++++++++++ .../boot/convert/PeriodToStringConverter.java | 67 +++++ .../boot/convert/PeriodUnit.java | 46 ++++ .../boot/convert/StringToPeriodConverter.java | 68 +++++ .../convert/MockPeriodTypeDescriptor.java | 59 ++++ .../convert/NumberToPeriodConverterTests.java | 76 ++++++ .../boot/convert/PeriodStyleTests.java | 198 ++++++++++++++ .../convert/PeriodToStringConverterTests.java | 63 +++++ .../convert/StringToPeriodConverterTest.java | 101 +++++++ 15 files changed, 1072 insertions(+), 4 deletions(-) create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToPeriodConverter.java create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodFormat.java create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodToStringConverter.java create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodUnit.java create mode 100644 spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToPeriodConverter.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToPeriodConverterTest.java diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java index 5c15c4f6b6..0311eafe72 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -130,6 +130,19 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { DATA_SIZE_SUFFIX = Collections.unmodifiableMap(values); } + private static final String PERIOD_OF = "Period.of"; + + private static final Map PERIOD_SUFFIX; + + static { + Map values = new HashMap<>(); + values.put("Days", "d"); + values.put("Weeks", "w"); + values.put("Months", "m"); + values.put("Years", "y"); + PERIOD_SUFFIX = Collections.unmodifiableMap(values); + } + private final Map fieldValues = new HashMap<>(); private final Map staticFinals = new HashMap<>(); @@ -194,6 +207,10 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { if (dataSizeValue != null) { return dataSizeValue; } + Object periodValue = getFactoryValue(expression, factoryValue, PERIOD_OF, PERIOD_SUFFIX); + if (periodValue != null) { + return periodValue; + } return factoryValue; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 29ba8dccd6..da4c0cf5d1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -100,6 +100,11 @@ public abstract class AbstractFieldValuesProcessorTests { assertThat(values.get("dataSizeMegabytes")).isEqualTo("20MB"); assertThat(values.get("dataSizeGigabytes")).isEqualTo("30GB"); assertThat(values.get("dataSizeTerabytes")).isEqualTo("40TB"); + assertThat(values.get("periodNone")).isNull(); + assertThat(values.get("periodDays")).isEqualTo("3d"); + assertThat(values.get("periodWeeks")).isEqualTo("2w"); + assertThat(values.get("periodMonths")).isEqualTo("10m"); + assertThat(values.get("periodYears")).isEqualTo("15y"); } @SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" }) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/fieldvalues/FieldValues.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/fieldvalues/FieldValues.java index 7dbdc96de1..e6cd231366 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/fieldvalues/FieldValues.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/fieldvalues/FieldValues.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -19,6 +19,7 @@ package org.springframework.boot.configurationsample.fieldvalues; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Period; import org.springframework.boot.configurationsample.ConfigurationProperties; import org.springframework.util.MimeType; @@ -136,4 +137,14 @@ public class FieldValues { private DataSize dataSizeTerabytes = DataSize.ofTerabytes(40); + private Period periodNone; + + private Period periodDays = Period.ofDays(3); + + private Period periodWeeks = Period.ofWeeks(2); + + private Period periodMonths = Period.ofMonths(10); + + private Period periodYears = Period.ofYears(15); + } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java index 2de3a5bde2..ad59ba3c1e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -110,8 +110,11 @@ public class ApplicationConversionService extends FormattingConversionService { public static void addApplicationConverters(ConverterRegistry registry) { addDelimitedStringConverters(registry); registry.addConverter(new StringToDurationConverter()); + registry.addConverter(new StringToPeriodConverter()); registry.addConverter(new DurationToStringConverter()); + registry.addConverter(new PeriodToStringConverter()); registry.addConverter(new NumberToDurationConverter()); + registry.addConverter(new NumberToPeriodConverter()); registry.addConverter(new DurationToNumberConverter()); registry.addConverter(new StringToDataSizeConverter()); registry.addConverter(new NumberToDataSizeConverter()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToPeriodConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToPeriodConverter.java new file mode 100644 index 0000000000..db7bb7c707 --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/NumberToPeriodConverter.java @@ -0,0 +1,51 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.util.Collections; +import java.util.Set; + +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.GenericConverter; + +/** + * {@link Converter} to convert from a {@link Number} to a {@link Period}. Supports + * {@link Period#parse(CharSequence)} as well a more readable {@code 10m} form. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @see PeriodFormat + * @see PeriodUnit + */ +final class NumberToPeriodConverter implements GenericConverter { + + private final StringToPeriodConverter delegate = new StringToPeriodConverter(); + + @Override + public Set getConvertibleTypes() { + return Collections.singleton(new ConvertiblePair(Number.class, Period.class)); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + return this.delegate.convert((source != null) ? source.toString() : null, TypeDescriptor.valueOf(String.class), + targetType); + } + +} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodFormat.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodFormat.java new file mode 100644 index 0000000000..45d45183b8 --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodFormat.java @@ -0,0 +1,45 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.time.Period; + +/** + * Annotation that can be used to indicate the format to use when converting a + * {@link Period}. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @since 2.3.0 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PeriodFormat { + + /** + * The {@link Period} format style. + * @return the period format style. + */ + PeriodStyle value(); + +} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java new file mode 100644 index 0000000000..c1e2dfc1fe --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java @@ -0,0 +1,258 @@ +/* + * Copyright 2002-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * A standard set of {@link Period} units. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @since 2.3.0 + * @see Period + */ +public enum PeriodStyle { + + /** + * Simple formatting, for example '1d'. + */ + SIMPLE("^([\\+\\-]?\\d+)([a-zA-Z]{0,2})$") { + + @Override + public Period parse(String value, ChronoUnit unit) { + try { + Matcher matcher = matcher(value); + Assert.state(matcher.matches(), "Does not match simple period pattern"); + String suffix = matcher.group(2); + return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) : Unit.fromChronoUnit(unit)) + .parse(matcher.group(1)); + } + catch (Exception ex) { + throw new IllegalArgumentException("'" + value + "' is not a valid simple period", ex); + } + } + + @Override + public String print(Period value, ChronoUnit unit) { + return Unit.fromChronoUnit(unit).print(value); + } + + }, + + /** + * ISO-8601 formatting. + */ + ISO8601("^[\\+\\-]?P.*$") { + + @Override + public Period parse(String value, ChronoUnit unit) { + try { + return Period.parse(value); + } + catch (Exception ex) { + throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 period", ex); + } + } + + @Override + public String print(Period value, ChronoUnit unit) { + return value.toString(); + } + + }; + + private final Pattern pattern; + + PeriodStyle(String pattern) { + this.pattern = Pattern.compile(pattern); + } + + protected final boolean matches(String value) { + return this.pattern.matcher(value).matches(); + } + + protected final Matcher matcher(String value) { + return this.pattern.matcher(value); + } + + /** + * Parse the given value to a Period. + * @param value the value to parse + * @return a period + */ + public Period parse(String value) { + return parse(value, null); + } + + /** + * Parse the given value to a period. + * @param value the value to parse + * @param unit the period unit to use if the value doesn't specify one ({@code null} + * will default to d) + * @return a period + */ + public abstract Period parse(String value, ChronoUnit unit); + + /** + * Print the specified period. + * @param value the value to print + * @return the printed result + */ + public String print(Period value) { + return print(value, null); + } + + /** + * Print the specified period using the given unit. + * @param value the value to print + * @param unit the value to use for printing + * @return the printed result + */ + public abstract String print(Period value, ChronoUnit unit); + + /** + * Detect the style then parse the value to return a period. + * @param value the value to parse + * @return the parsed period + * @throws IllegalStateException if the value is not a known style or cannot be parsed + */ + public static Period detectAndParse(String value) { + return detectAndParse(value, null); + } + + /** + * Detect the style then parse the value to return a period. + * @param value the value to parse + * @param unit the period unit to use if the value doesn't specify one ({@code null} + * will default to ms) + * @return the parsed period + * @throws IllegalStateException if the value is not a known style or cannot be parsed + */ + public static Period detectAndParse(String value, ChronoUnit unit) { + return detect(value).parse(value, unit); + } + + /** + * Detect the style from the given source value. + * @param value the source value + * @return the period style + * @throws IllegalStateException if the value is not a known style + */ + public static PeriodStyle detect(String value) { + Assert.notNull(value, "Value must not be null"); + for (PeriodStyle candidate : values()) { + if (candidate.matches(value)) { + return candidate; + } + } + throw new IllegalArgumentException("'" + value + "' is not a valid period"); + } + + enum Unit { + + /** + * Days, represented by suffix {@code d}. + */ + DAYS(ChronoUnit.DAYS, "d", Period::getDays), + + /** + * Months, represented by suffix {@code m}. + */ + MONTHS(ChronoUnit.MONTHS, "m", Period::getMonths), + + /** + * Years, represented by suffix {@code y}. + */ + YEARS(ChronoUnit.YEARS, "y", Period::getYears); + + private final ChronoUnit chronoUnit; + + private final String suffix; + + private final Function intValue; + + Unit(ChronoUnit chronoUnit, String suffix, Function intValue) { + this.chronoUnit = chronoUnit; + this.suffix = suffix; + this.intValue = intValue; + } + + /** + * Return the {@link Unit} matching the specified {@code suffix}. + * @param suffix one of the standard suffixes + * @return the {@link Unit} matching the specified {@code suffix} + * @throws IllegalArgumentException if the suffix does not match the suffix of any + * of this enum's constants + */ + public static Unit fromSuffix(String suffix) { + for (Unit candidate : values()) { + if (candidate.suffix.equalsIgnoreCase(suffix)) { + return candidate; + } + } + throw new IllegalArgumentException("Unknown unit suffix '" + suffix + "'"); + } + + public Period parse(String value) { + int intValue = Integer.parseInt(value); + + if (ChronoUnit.DAYS == this.chronoUnit) { + return Period.ofDays(intValue); + } + else if (ChronoUnit.WEEKS == this.chronoUnit) { + return Period.ofWeeks(intValue); + } + else if (ChronoUnit.MONTHS == this.chronoUnit) { + return Period.ofMonths(intValue); + } + else if (ChronoUnit.YEARS == this.chronoUnit) { + return Period.ofYears(intValue); + } + throw new IllegalArgumentException("Unknow unit '" + this.chronoUnit + "'"); + } + + public String print(Period value) { + return longValue(value) + this.suffix; + } + + public long longValue(Period value) { + return this.intValue.apply(value); + } + + public static Unit fromChronoUnit(ChronoUnit chronoUnit) { + if (chronoUnit == null) { + return Unit.DAYS; + } + for (Unit candidate : values()) { + if (candidate.chronoUnit == chronoUnit) { + return candidate; + } + } + throw new IllegalArgumentException("Unknown unit " + chronoUnit); + } + + } + +} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodToStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodToStringConverter.java new file mode 100644 index 0000000000..c157c05cd7 --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodToStringConverter.java @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.Set; + +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.util.ObjectUtils; + +/** + * {@link Converter} to convert from a {@link Period} to a {@link String}. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @since 2.3.0 + * @see Period + */ +public class PeriodToStringConverter implements GenericConverter { + + @Override + public Set getConvertibleTypes() { + return Collections.singleton(new ConvertiblePair(Period.class, String.class)); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (ObjectUtils.isEmpty(source)) { + return null; + } + return convert((Period) source, getPeriodStyle(sourceType), getPeriodUnit(sourceType)); + } + + private PeriodStyle getPeriodStyle(TypeDescriptor sourceType) { + PeriodFormat annotation = sourceType.getAnnotation(PeriodFormat.class); + return (annotation != null) ? annotation.value() : null; + } + + private String convert(Period source, PeriodStyle style, ChronoUnit unit) { + style = (style != null) ? style : PeriodStyle.ISO8601; + return style.print(source, unit); + } + + private ChronoUnit getPeriodUnit(TypeDescriptor sourceType) { + PeriodUnit annotation = sourceType.getAnnotation(PeriodUnit.class); + return (annotation != null) ? annotation.value() : null; + } + +} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodUnit.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodUnit.java new file mode 100644 index 0000000000..e34c43948a --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodUnit.java @@ -0,0 +1,46 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.time.Period; +import java.time.temporal.ChronoUnit; + +/** + * Annotation that can be used to change the default unit used when converting a + * {@link Period}. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @since 2.3.0 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PeriodUnit { + + /** + * The Period unit to use if one is not specified. + * @return the Period unit + */ + ChronoUnit value(); + +} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToPeriodConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToPeriodConverter.java new file mode 100644 index 0000000000..e15bfd2946 --- /dev/null +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToPeriodConverter.java @@ -0,0 +1,68 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.Set; + +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.util.ObjectUtils; + +/** + * {@link Converter} to convert from a {@link String} to a {@link Period}. Supports + * {@link Period#parse(CharSequence)} as well a more readable form. + * + * @author Eddú Meléndez + * @author Edson Chávez + * @since 2.3.0 + * @see PeriodUnit + */ +public class StringToPeriodConverter implements GenericConverter { + + @Override + public Set getConvertibleTypes() { + return Collections.singleton(new GenericConverter.ConvertiblePair(String.class, Period.class)); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (ObjectUtils.isEmpty(source)) { + return null; + } + return convert(source.toString(), getStyle(targetType), getPeriodUnit(targetType)); + } + + private PeriodStyle getStyle(TypeDescriptor targetType) { + PeriodFormat annotation = targetType.getAnnotation(PeriodFormat.class); + return (annotation != null) ? annotation.value() : null; + } + + private ChronoUnit getPeriodUnit(TypeDescriptor targetType) { + PeriodUnit annotation = targetType.getAnnotation(PeriodUnit.class); + return (annotation != null) ? annotation.value() : null; + } + + private Period convert(String source, PeriodStyle style, ChronoUnit unit) { + style = (style != null) ? style : PeriodStyle.detect(source); + return style.parse(source, unit); + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java new file mode 100644 index 0000000000..599adffe8a --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java @@ -0,0 +1,59 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.Collections; + +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.convert.TypeDescriptor; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Create a mock {@link TypeDescriptor} with optional {@link PeriodUnit @PeriodUnit} and + * {@link PeriodFormat @PeriodFormat} annotations. + * + * @author Eddú Meléndez + * @author Edson Chávez + */ +public final class MockPeriodTypeDescriptor { + + private MockPeriodTypeDescriptor() { + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static TypeDescriptor get(ChronoUnit unit, PeriodStyle style) { + TypeDescriptor descriptor = mock(TypeDescriptor.class); + if (unit != null) { + PeriodUnit unitAnnotation = AnnotationUtils.synthesizeAnnotation(Collections.singletonMap("value", unit), + PeriodUnit.class, null); + given(descriptor.getAnnotation(PeriodUnit.class)).willReturn(unitAnnotation); + } + if (style != null) { + PeriodFormat formatAnnotation = AnnotationUtils + .synthesizeAnnotation(Collections.singletonMap("value", style), PeriodFormat.class, null); + given(descriptor.getAnnotation(PeriodFormat.class)).willReturn(formatAnnotation); + } + given(descriptor.getType()).willReturn((Class) Period.class); + given(descriptor.getObjectType()).willReturn((Class) Period.class); + return descriptor; + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java new file mode 100644 index 0000000000..045715d3a7 --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.stream.Stream; + +import org.junit.jupiter.params.provider.Arguments; + +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.TypeDescriptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * Tests for {@link NumberToPeriodConverter}. + * + * @author Eddú Meléndez + * @author Edson Chávez + */ +class NumberToPeriodConverterTests { + + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, 10)).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, +10)).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, -10)).isEqualTo(Period.ofDays(-10)); + } + + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, 10, ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, +10, ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, -10, ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(-10)); + } + + private Period convert(ConversionService conversionService, Integer source) { + return conversionService.convert(source, Period.class); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Period convert(ConversionService conversionService, Integer source, ChronoUnit defaultUnit) { + TypeDescriptor targetType = mock(TypeDescriptor.class); + if (defaultUnit != null) { + PeriodUnit unitAnnotation = AnnotationUtils + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), PeriodUnit.class, null); + given(targetType.getAnnotation(PeriodUnit.class)).willReturn(unitAnnotation); + } + given(targetType.getType()).willReturn((Class) Period.class); + return (Period) conversionService.convert(source, TypeDescriptor.forObject(source), targetType); + } + + static Stream conversionServices() { + return ConversionServiceArguments.with(new NumberToPeriodConverter()); + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java new file mode 100644 index 0000000000..0e9c08d2e4 --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java @@ -0,0 +1,198 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +/** + * Tests for {@link PeriodStyle}. + * + * @author Eddú Meléndez + * @author Edson Chávez + */ +class PeriodStyleTests { + + @Test + void detectAndParseWhenValueIsNullShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse(null)) + .withMessageContaining("Value must not be null"); + } + + @Test + void detectAndParseWhenIso8601ShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("P15M")).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.detectAndParse("-P15M")).isEqualTo(Period.parse("P-15M")); + assertThat(PeriodStyle.detectAndParse("+P15M")).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.detectAndParse("P2D")).isEqualTo(Period.parse("P2D")); + assertThat(PeriodStyle.detectAndParse("-P20Y")).isEqualTo(Period.parse("P-20Y")); + + } + + @Test + void detectAndParseWhenSimpleDaysShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10d")).isEqualTo(Period.ofDays(10)); + assertThat(PeriodStyle.detectAndParse("10D")).isEqualTo(Period.ofDays(10)); + assertThat(PeriodStyle.detectAndParse("+10d")).isEqualTo(Period.ofDays(10)); + assertThat(PeriodStyle.detectAndParse("-10D")).isEqualTo(Period.ofDays(-10)); + } + + @Test + void detectAndParseWhenSimpleMonthsShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10m")).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.detectAndParse("10M")).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.detectAndParse("+10m")).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.detectAndParse("-10M")).isEqualTo(Period.ofMonths(-10)); + } + + @Test + void detectAndParseWhenSimpleYearsShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10y")).isEqualTo(Period.ofYears(10)); + assertThat(PeriodStyle.detectAndParse("10Y")).isEqualTo(Period.ofYears(10)); + assertThat(PeriodStyle.detectAndParse("+10y")).isEqualTo(Period.ofYears(10)); + assertThat(PeriodStyle.detectAndParse("-10Y")).isEqualTo(Period.ofYears(-10)); + } + + @Test + void detectAndParseWhenSimpleWithoutSuffixShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10")).isEqualTo(Period.ofDays(10)); + assertThat(PeriodStyle.detectAndParse("+10")).isEqualTo(Period.ofDays(10)); + assertThat(PeriodStyle.detectAndParse("-10")).isEqualTo(Period.ofDays(-10)); + } + + @Test + void detectAndParseWhenSimpleWithoutSuffixButWithChronoUnitShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10", ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.detectAndParse("+10", ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.detectAndParse("-10", ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(-10)); + } + + @Test + void detectAndParseWhenBadFormatShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse("10foo")) + .withMessageContaining("'10foo' is not a valid period"); + } + + @Test + void detectWhenSimpleShouldReturnSimple() { + assertThat(PeriodStyle.detect("10")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("+10")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("-10")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("10m")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("10y")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("10d")).isEqualTo(PeriodStyle.SIMPLE); + assertThat(PeriodStyle.detect("10D")).isEqualTo(PeriodStyle.SIMPLE); + } + + @Test + void detectWhenIso8601ShouldReturnIso8601() { + assertThat(PeriodStyle.detect("P20")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("-P15M")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("+P15M")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("P10Y")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("P2D")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("-P6")).isEqualTo(PeriodStyle.ISO8601); + assertThat(PeriodStyle.detect("-P-6M")).isEqualTo(PeriodStyle.ISO8601); + } + + @Test + void detectWhenUnknownShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detect("bad")) + .withMessageContaining("'bad' is not a valid period"); + } + + @Test + void parseIso8601ShouldParse() { + assertThat(PeriodStyle.ISO8601.parse("P20D")).isEqualTo(Period.parse("P20D")); + assertThat(PeriodStyle.ISO8601.parse("P15M")).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.ISO8601.parse("+P15M")).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.ISO8601.parse("P10Y")).isEqualTo(Period.parse("P10Y")); + assertThat(PeriodStyle.ISO8601.parse("P2D")).isEqualTo(Period.parse("P2D")); + assertThat(PeriodStyle.ISO8601.parse("-P6D")).isEqualTo(Period.parse("-P6D")); + assertThat(PeriodStyle.ISO8601.parse("-P-6Y+3M")).isEqualTo(Period.parse("-P-6Y+3M")); + } + + @Test + void parseIso8601WithUnitShouldIgnoreUnit() { + assertThat(PeriodStyle.ISO8601.parse("P20D", ChronoUnit.SECONDS)).isEqualTo(Period.parse("P20D")); + assertThat(PeriodStyle.ISO8601.parse("P15M", ChronoUnit.SECONDS)).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.ISO8601.parse("+P15M", ChronoUnit.SECONDS)).isEqualTo(Period.parse("P15M")); + assertThat(PeriodStyle.ISO8601.parse("P10Y", ChronoUnit.SECONDS)).isEqualTo(Period.parse("P10Y")); + assertThat(PeriodStyle.ISO8601.parse("P2D", ChronoUnit.SECONDS)).isEqualTo(Period.parse("P2D")); + assertThat(PeriodStyle.ISO8601.parse("-P6D", ChronoUnit.SECONDS)).isEqualTo(Period.parse("-P6D")); + assertThat(PeriodStyle.ISO8601.parse("-P-6Y+3M", ChronoUnit.SECONDS)).isEqualTo(Period.parse("-P-6Y+3M")); + } + + @Test + void parseIso8601WhenSimpleShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.ISO8601.parse("10d")) + .withMessageContaining("'10d' is not a valid ISO-8601 period"); + } + + @Test + void parseSimpleShouldParse() { + assertThat(PeriodStyle.SIMPLE.parse("10m")).isEqualTo(Period.ofMonths(10)); + } + + @Test + void parseSimpleWithUnitShouldUseUnitAsFallback() { + assertThat(PeriodStyle.SIMPLE.parse("10m", ChronoUnit.DAYS)).isEqualTo(Period.ofMonths(10)); + assertThat(PeriodStyle.SIMPLE.parse("10", ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(10)); + } + + @Test + void parseSimpleWhenUnknownUnitShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10mb")) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit suffix 'mb'")); + } + + @Test + void parseSimpleWhenIso8601ShouldThrowException() { + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("PT10H")) + .withMessageContaining("'PT10H' is not a valid simple period"); + } + + @Test + void printIso8601ShouldPrint() { + Period period = Period.parse("-P-6M+3D"); + assertThat(PeriodStyle.ISO8601.print(period)).isEqualTo("P6M-3D"); + } + + @Test + void printIso8601ShouldIgnoreUnit() { + Period period = Period.parse("-P3Y"); + assertThat(PeriodStyle.ISO8601.print(period, ChronoUnit.DAYS)).isEqualTo("P-3Y"); + } + + @Test + void printSimpleWithoutUnitShouldPrintInDays() { + Period period = Period.ofMonths(1); + assertThat(PeriodStyle.SIMPLE.print(period)).isEqualTo("0d"); + } + + @Test + void printSimpleWithUnitShouldPrintInUnit() { + Period period = Period.ofYears(1000); + assertThat(PeriodStyle.SIMPLE.print(period, ChronoUnit.YEARS)).isEqualTo("1000y"); + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java new file mode 100644 index 0000000000..78ec476011 --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java @@ -0,0 +1,63 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; + +import org.junit.jupiter.params.provider.Arguments; + +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.TypeDescriptor; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for {@link PeriodToStringConverter}. + * + * @author Eddú Melendez + * @author Edson Chávez + */ +class PeriodToStringConverterTests { + + @ConversionServiceTest + void convertWithoutStyleShouldReturnIso8601(ConversionService conversionService) { + String converted = conversionService.convert(Period.ofDays(1), String.class); + assertThat(converted).isEqualTo(Period.ofDays(1).toString()); + } + + @ConversionServiceTest + void convertWithFormatShouldUseFormatAndDays(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.ofMonths(1), + MockPeriodTypeDescriptor.get(null, PeriodStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("0d"); + } + + @ConversionServiceTest + void convertWithFormatAndUnitShouldUseFormatAndUnit(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.ofYears(1), + MockPeriodTypeDescriptor.get(ChronoUnit.YEARS, PeriodStyle.SIMPLE), + TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("1y"); + } + + static Stream conversionServices() throws Exception { + return ConversionServiceArguments.with(new PeriodToStringConverter()); + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToPeriodConverterTest.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToPeriodConverterTest.java new file mode 100644 index 0000000000..62373c6c57 --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToPeriodConverterTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2012-2020 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.boot.convert; + +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; + +import org.junit.jupiter.params.provider.Arguments; + +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.TypeDescriptor; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for {@link StringToPeriodConverter}. + * + * @author Eddú Meléndez + * @author Edson Chávez + */ +public class StringToPeriodConverterTest { + + @ConversionServiceTest + void convertWhenIso8601ShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "P2Y")).isEqualTo(Period.parse("P2Y")); + assertThat(convert(conversionService, "P3M")).isEqualTo(Period.parse("P3M")); + assertThat(convert(conversionService, "P4W")).isEqualTo(Period.parse("P4W")); + assertThat(convert(conversionService, "P5D")).isEqualTo(Period.parse("P5D")); + assertThat(convert(conversionService, "P1Y2M3D")).isEqualTo(Period.parse("P1Y2M3D")); + assertThat(convert(conversionService, "P1Y2M3W4D")).isEqualTo(Period.parse("P1Y2M3W4D")); + assertThat(convert(conversionService, "P-1Y2M")).isEqualTo(Period.parse("P-1Y2M")); + assertThat(convert(conversionService, "-P1Y2M")).isEqualTo(Period.parse("-P1Y2M")); + } + + @ConversionServiceTest + void convertWhenSimpleDaysShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "10d")).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, "10D")).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, "+10d")).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, "-10D")).isEqualTo(Period.ofDays(-10)); + } + + @ConversionServiceTest + void convertWhenSimpleMonthsShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "10m")).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, "10M")).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, "+10m")).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, "-10M")).isEqualTo(Period.ofMonths(-10)); + } + + @ConversionServiceTest + void convertWhenSimpleYearsShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "10y")).isEqualTo(Period.ofYears(10)); + assertThat(convert(conversionService, "10Y")).isEqualTo(Period.ofYears(10)); + assertThat(convert(conversionService, "+10y")).isEqualTo(Period.ofYears(10)); + assertThat(convert(conversionService, "-10Y")).isEqualTo(Period.ofYears(-10)); + } + + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "10")).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, "+10")).isEqualTo(Period.ofDays(10)); + assertThat(convert(conversionService, "-10")).isEqualTo(Period.ofDays(-10)); + } + + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnPeriod(ConversionService conversionService) { + assertThat(convert(conversionService, "10", ChronoUnit.MONTHS, null)).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, "+10", ChronoUnit.MONTHS, null)).isEqualTo(Period.ofMonths(10)); + assertThat(convert(conversionService, "-10", ChronoUnit.MONTHS, null)).isEqualTo(Period.ofMonths(-10)); + } + + private Period convert(ConversionService conversionService, String source) { + return conversionService.convert(source, Period.class); + } + + private Period convert(ConversionService conversionService, String source, ChronoUnit unit, PeriodStyle style) { + return (Period) conversionService.convert(source, TypeDescriptor.forObject(source), + MockPeriodTypeDescriptor.get(unit, style)); + } + + static Stream conversionServices() { + return ConversionServiceArguments.with(new StringToPeriodConverter()); + } + +} From 5ae623c43ad5d3be2e19135c38dbfd62e83abc92 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 5 May 2020 22:09:32 -0700 Subject: [PATCH 2/2] Polish 'Add Period converter support' Polish period converter support, primarily by changing `PeriodStyle` to parse and print periods that include more than one unit. See gh-21136 --- .../docs/asciidoc/spring-boot-features.adoc | 20 +++ .../javac/JavaCompilerFieldValuesParser.java | 26 ++-- .../convert/ApplicationConversionService.java | 6 +- .../boot/convert/PeriodStyle.java | 114 ++++++++++-------- .../boot/convert/PeriodStyleTests.java | 38 ++++-- .../convert/PeriodToStringConverterTests.java | 25 +++- 6 files changed, 153 insertions(+), 76 deletions(-) diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/spring-boot-features.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/spring-boot-features.adoc index b382eea08f..7ec3c1aa9a 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/spring-boot-features.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/spring-boot-features.adoc @@ -1450,6 +1450,26 @@ Doing so gives a transparent upgrade path while supporting a much richer format. +[[boot-features-external-config-conversion-period]] +===== Converting periods +In addition to durations, Spring Boot can also work with `java.time.Period` type. +The following formats can be used in application properties: + +* An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) +* The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] +* A simpler format where the value and the unit pairs are coupled (e.g. `1y3d` means 1 year and 3 days) + +The following units are supported with the simple format: + +* `y` for years +* `m` for months +* `w` for weeks +* `d` for days + +NOTE: The `java.time.Period` type never actually stores the number of weeks, it is simply a shortcut that means "`7 days`". + + + [[boot-features-external-config-conversion-datasize]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java index 0311eafe72..64fd29dad6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesParser.java @@ -116,6 +116,19 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { DURATION_SUFFIX = Collections.unmodifiableMap(values); } + private static final String PERIOD_OF = "Period.of"; + + private static final Map PERIOD_SUFFIX; + + static { + Map values = new HashMap<>(); + values.put("Days", "d"); + values.put("Weeks", "w"); + values.put("Months", "m"); + values.put("Years", "y"); + PERIOD_SUFFIX = Collections.unmodifiableMap(values); + } + private static final String DATA_SIZE_OF = "DataSize.of"; private static final Map DATA_SIZE_SUFFIX; @@ -130,19 +143,6 @@ public class JavaCompilerFieldValuesParser implements FieldValuesParser { DATA_SIZE_SUFFIX = Collections.unmodifiableMap(values); } - private static final String PERIOD_OF = "Period.of"; - - private static final Map PERIOD_SUFFIX; - - static { - Map values = new HashMap<>(); - values.put("Days", "d"); - values.put("Weeks", "w"); - values.put("Months", "m"); - values.put("Years", "y"); - PERIOD_SUFFIX = Collections.unmodifiableMap(values); - } - private final Map fieldValues = new HashMap<>(); private final Map staticFinals = new HashMap<>(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java index ad59ba3c1e..e3db0c096e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java @@ -110,12 +110,12 @@ public class ApplicationConversionService extends FormattingConversionService { public static void addApplicationConverters(ConverterRegistry registry) { addDelimitedStringConverters(registry); registry.addConverter(new StringToDurationConverter()); - registry.addConverter(new StringToPeriodConverter()); registry.addConverter(new DurationToStringConverter()); - registry.addConverter(new PeriodToStringConverter()); registry.addConverter(new NumberToDurationConverter()); - registry.addConverter(new NumberToPeriodConverter()); registry.addConverter(new DurationToNumberConverter()); + registry.addConverter(new StringToPeriodConverter()); + registry.addConverter(new PeriodToStringConverter()); + registry.addConverter(new NumberToPeriodConverter()); registry.addConverter(new StringToDataSizeConverter()); registry.addConverter(new NumberToDataSizeConverter()); registry.addConverter(new StringToFileConverter()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java index c1e2dfc1fe..78e61cb729 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/PeriodStyle.java @@ -23,7 +23,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; /** * A standard set of {@link Period} units. @@ -38,25 +37,64 @@ public enum PeriodStyle { /** * Simple formatting, for example '1d'. */ - SIMPLE("^([\\+\\-]?\\d+)([a-zA-Z]{0,2})$") { + SIMPLE("^" + "(?:([-+]?[0-9]+)Y)?" + "(?:([-+]?[0-9]+)M)?" + "(?:([-+]?[0-9]+)W)?" + "(?:([-+]?[0-9]+)D)?" + "$", + Pattern.CASE_INSENSITIVE) { @Override public Period parse(String value, ChronoUnit unit) { try { + if (NUMERIC.matcher(value).matches()) { + return Unit.fromChronoUnit(unit).parse(value); + } Matcher matcher = matcher(value); Assert.state(matcher.matches(), "Does not match simple period pattern"); - String suffix = matcher.group(2); - return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) : Unit.fromChronoUnit(unit)) - .parse(matcher.group(1)); + Assert.isTrue(hasAtLeastOneGroupValue(matcher), "'" + value + "' is not a valid simple period"); + int years = parseInt(matcher, 1); + int months = parseInt(matcher, 2); + int weeks = parseInt(matcher, 3); + int days = parseInt(matcher, 4); + return Period.of(years, months, Math.addExact(Math.multiplyExact(weeks, 7), days)); } catch (Exception ex) { throw new IllegalArgumentException("'" + value + "' is not a valid simple period", ex); } } + boolean hasAtLeastOneGroupValue(Matcher matcher) { + for (int i = 0; i < matcher.groupCount(); i++) { + if (matcher.group(i + 1) != null) { + return true; + } + } + return false; + } + + private int parseInt(Matcher matcher, int group) { + String value = matcher.group(group); + return (value != null) ? Integer.parseInt(value) : 0; + } + + @Override + protected boolean matches(String value) { + return NUMERIC.matcher(value).matches() || matcher(value).matches(); + } + @Override public String print(Period value, ChronoUnit unit) { - return Unit.fromChronoUnit(unit).print(value); + if (value.isZero()) { + return Unit.fromChronoUnit(unit).print(value); + } + StringBuilder result = new StringBuilder(); + append(result, value, Unit.YEARS); + append(result, value, Unit.MONTHS); + append(result, value, Unit.DAYS); + return result.toString(); + } + + private void append(StringBuilder result, Period value, Unit unit) { + if (!unit.isZero(value)) { + result.append(unit.print(value)); + } } }, @@ -64,7 +102,7 @@ public enum PeriodStyle { /** * ISO-8601 formatting. */ - ISO8601("^[\\+\\-]?P.*$") { + ISO8601("^[\\+\\-]?P.*$", 0) { @Override public Period parse(String value, ChronoUnit unit) { @@ -83,13 +121,15 @@ public enum PeriodStyle { }; + private static final Pattern NUMERIC = Pattern.compile("^[-+]?[0-9]+$"); + private final Pattern pattern; - PeriodStyle(String pattern) { - this.pattern = Pattern.compile(pattern); + PeriodStyle(String pattern, int flags) { + this.pattern = Pattern.compile(pattern, flags); } - protected final boolean matches(String value) { + protected boolean matches(String value) { return this.pattern.matcher(value).matches(); } @@ -175,17 +215,17 @@ public enum PeriodStyle { /** * Days, represented by suffix {@code d}. */ - DAYS(ChronoUnit.DAYS, "d", Period::getDays), + DAYS(ChronoUnit.DAYS, "d", Period::getDays, Period::ofDays), /** * Months, represented by suffix {@code m}. */ - MONTHS(ChronoUnit.MONTHS, "m", Period::getMonths), + MONTHS(ChronoUnit.MONTHS, "m", Period::getMonths, Period::ofMonths), /** * Years, represented by suffix {@code y}. */ - YEARS(ChronoUnit.YEARS, "y", Period::getYears); + YEARS(ChronoUnit.YEARS, "y", Period::getYears, Period::ofYears); private final ChronoUnit chronoUnit; @@ -193,51 +233,29 @@ public enum PeriodStyle { private final Function intValue; - Unit(ChronoUnit chronoUnit, String suffix, Function intValue) { + private final Function factory; + + Unit(ChronoUnit chronoUnit, String suffix, Function intValue, + Function factory) { this.chronoUnit = chronoUnit; this.suffix = suffix; this.intValue = intValue; + this.factory = factory; } - /** - * Return the {@link Unit} matching the specified {@code suffix}. - * @param suffix one of the standard suffixes - * @return the {@link Unit} matching the specified {@code suffix} - * @throws IllegalArgumentException if the suffix does not match the suffix of any - * of this enum's constants - */ - public static Unit fromSuffix(String suffix) { - for (Unit candidate : values()) { - if (candidate.suffix.equalsIgnoreCase(suffix)) { - return candidate; - } - } - throw new IllegalArgumentException("Unknown unit suffix '" + suffix + "'"); + private Period parse(String value) { + return this.factory.apply(Integer.parseInt(value)); } - public Period parse(String value) { - int intValue = Integer.parseInt(value); - - if (ChronoUnit.DAYS == this.chronoUnit) { - return Period.ofDays(intValue); - } - else if (ChronoUnit.WEEKS == this.chronoUnit) { - return Period.ofWeeks(intValue); - } - else if (ChronoUnit.MONTHS == this.chronoUnit) { - return Period.ofMonths(intValue); - } - else if (ChronoUnit.YEARS == this.chronoUnit) { - return Period.ofYears(intValue); - } - throw new IllegalArgumentException("Unknow unit '" + this.chronoUnit + "'"); + private String print(Period value) { + return intValue(value) + this.suffix; } - public String print(Period value) { - return longValue(value) + this.suffix; + public boolean isZero(Period value) { + return intValue(value) == 0; } - public long longValue(Period value) { + public int intValue(Period value) { return this.intValue.apply(value); } @@ -250,7 +268,7 @@ public enum PeriodStyle { return candidate; } } - throw new IllegalArgumentException("Unknown unit " + chronoUnit); + throw new IllegalArgumentException("Unsupported unit " + chronoUnit); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java index 0e9c08d2e4..7dfc401240 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java @@ -56,6 +56,14 @@ class PeriodStyleTests { assertThat(PeriodStyle.detectAndParse("-10D")).isEqualTo(Period.ofDays(-10)); } + @Test + void detectAndParseWhenSimpleWeeksShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("10w")).isEqualTo(Period.ofWeeks(10)); + assertThat(PeriodStyle.detectAndParse("10W")).isEqualTo(Period.ofWeeks(10)); + assertThat(PeriodStyle.detectAndParse("+10w")).isEqualTo(Period.ofWeeks(10)); + assertThat(PeriodStyle.detectAndParse("-10W")).isEqualTo(Period.ofWeeks(-10)); + } + @Test void detectAndParseWhenSimpleMonthsShouldReturnPeriod() { assertThat(PeriodStyle.detectAndParse("10m")).isEqualTo(Period.ofMonths(10)); @@ -86,6 +94,16 @@ class PeriodStyleTests { assertThat(PeriodStyle.detectAndParse("-10", ChronoUnit.MONTHS)).isEqualTo(Period.ofMonths(-10)); } + @Test + void detectAndParseWhenComplexShouldReturnPeriod() { + assertThat(PeriodStyle.detectAndParse("1y2m")).isEqualTo(Period.of(1, 2, 0)); + assertThat(PeriodStyle.detectAndParse("1y2m3d")).isEqualTo(Period.of(1, 2, 3)); + assertThat(PeriodStyle.detectAndParse("2m3d")).isEqualTo(Period.of(0, 2, 3)); + assertThat(PeriodStyle.detectAndParse("1y3d")).isEqualTo(Period.of(1, 0, 3)); + assertThat(PeriodStyle.detectAndParse("-1y3d")).isEqualTo(Period.of(-1, 0, 3)); + assertThat(PeriodStyle.detectAndParse("-1y-3d")).isEqualTo(Period.of(-1, 0, -3)); + } + @Test void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse("10foo")) @@ -161,8 +179,8 @@ class PeriodStyleTests { @Test void parseSimpleWhenUnknownUnitShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10mb")) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit suffix 'mb'")); + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10x")).satisfies( + (ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Does not match simple period pattern")); } @Test @@ -184,15 +202,21 @@ class PeriodStyleTests { } @Test - void printSimpleWithoutUnitShouldPrintInDays() { - Period period = Period.ofMonths(1); + void printSimpleWhenZeroWithoutUnitShouldPrintInDays() { + Period period = Period.ofMonths(0); assertThat(PeriodStyle.SIMPLE.print(period)).isEqualTo("0d"); } @Test - void printSimpleWithUnitShouldPrintInUnit() { - Period period = Period.ofYears(1000); - assertThat(PeriodStyle.SIMPLE.print(period, ChronoUnit.YEARS)).isEqualTo("1000y"); + void printSimpleWhenZeroWithUnitShouldPrintInUnit() { + Period period = Period.ofYears(0); + assertThat(PeriodStyle.SIMPLE.print(period, ChronoUnit.YEARS)).isEqualTo("0y"); + } + + @Test + void printSimpleWhenNonZeroShouldIgnoreUnit() { + Period period = Period.of(1, 2, 3); + assertThat(PeriodStyle.SIMPLE.print(period, ChronoUnit.YEARS)).isEqualTo("1y2m3d"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java index 78ec476011..5eb142058d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodToStringConverterTests.java @@ -42,18 +42,33 @@ class PeriodToStringConverterTests { } @ConversionServiceTest - void convertWithFormatShouldUseFormatAndDays(ConversionService conversionService) { - String converted = (String) conversionService.convert(Period.ofMonths(1), + void convertWithFormatWhenZeroShouldUseFormatAndDays(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.ofMonths(0), MockPeriodTypeDescriptor.get(null, PeriodStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("0d"); } @ConversionServiceTest - void convertWithFormatAndUnitShouldUseFormatAndUnit(ConversionService conversionService) { - String converted = (String) conversionService.convert(Period.ofYears(1), + void convertWithFormatShouldUseFormat(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.of(1, 2, 3), + MockPeriodTypeDescriptor.get(null, PeriodStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("1y2m3d"); + } + + @ConversionServiceTest + void convertWithFormatAndUnitWhenZeroShouldUseFormatAndUnit(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.ofYears(0), + MockPeriodTypeDescriptor.get(ChronoUnit.YEARS, PeriodStyle.SIMPLE), + TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("0y"); + } + + @ConversionServiceTest + void convertWithFormatAndUnitWhenNonZeroShouldUseFormatAndIgnoreUnit(ConversionService conversionService) { + String converted = (String) conversionService.convert(Period.of(1, 0, 3), MockPeriodTypeDescriptor.get(ChronoUnit.YEARS, PeriodStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); - assertThat(converted).isEqualTo("1y"); + assertThat(converted).isEqualTo("1y3d"); } static Stream conversionServices() throws Exception {