Remove Joda-Time support

Closes gh-27426
This commit is contained in:
Juergen Hoeller 2021-09-17 08:58:40 +02:00
parent b74e93807e
commit b7b078d26e
34 changed files with 126 additions and 3003 deletions

View File

@ -66,7 +66,6 @@ import java.lang.annotation.Target;
* @author Sam Brannen
* @since 3.0
* @see java.time.format.DateTimeFormatter
* @see org.joda.time.format.DateTimeFormat
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -38,7 +38,6 @@ import org.springframework.util.Assert;
* @author Phillip Webb
* @since 3.2
* @see org.springframework.format.datetime.standard.DateTimeFormatterRegistrar
* @see org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar
* @see FormatterRegistrar#registerFormatters
*/
public class DateFormatterRegistrar implements FormatterRegistrar {

View File

@ -38,7 +38,6 @@ import org.springframework.util.StringUtils;
* @author Phillip Webb
* @author Sam Brannen
* @since 3.2
* @see org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationFormatterFactory
*/
public class DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<DateTimeFormat> {

View File

@ -1,169 +0,0 @@
/*
* Copyright 2002-2017 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.joda;
import java.util.TimeZone;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Factory that creates a Joda-Time {@link DateTimeFormatter}.
*
* <p>Formatters will be created using the defined {@link #setPattern pattern},
* {@link #setIso ISO}, and {@link #setStyle style} methods (considered in that order).
*
* @author Phillip Webb
* @author Sam Brannen
* @since 3.2
* @see #createDateTimeFormatter()
* @see #createDateTimeFormatter(DateTimeFormatter)
* @see #setPattern
* @see #setStyle
* @see #setIso
* @see DateTimeFormatterFactoryBean
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public class DateTimeFormatterFactory {
@Nullable
private String pattern;
@Nullable
private ISO iso;
@Nullable
private String style;
@Nullable
private TimeZone timeZone;
/**
* Create a new {@code DateTimeFormatterFactory} instance.
*/
public DateTimeFormatterFactory() {
}
/**
* Create a new {@code DateTimeFormatterFactory} instance.
* @param pattern the pattern to use to format date values
*/
public DateTimeFormatterFactory(String pattern) {
this.pattern = pattern;
}
/**
* Set the pattern to use to format date values.
* @param pattern the format pattern
*/
public void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* Set the ISO format used to format date values.
* @param iso the ISO format
*/
public void setIso(ISO iso) {
this.iso = iso;
}
/**
* Set the two characters to use to format date values, in Joda-Time style.
* <p>The first character is used for the date style; the second is for
* the time style. Supported characters are:
* <ul>
* <li>'S' = Small</li>
* <li>'M' = Medium</li>
* <li>'L' = Long</li>
* <li>'F' = Full</li>
* <li>'-' = Omitted</li>
* </ul>
* @param style two characters from the set {"S", "M", "L", "F", "-"}
*/
public void setStyle(String style) {
this.style = style;
}
/**
* Set the {@code TimeZone} to normalize the date values into, if any.
* @param timeZone the time zone
*/
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
/**
* Create a new {@code DateTimeFormatter} using this factory.
* <p>If no specific pattern or style has been defined,
* {@link DateTimeFormat#mediumDateTime() medium date time format} will be used.
* @return a new date time formatter
* @see #createDateTimeFormatter(DateTimeFormatter)
*/
public DateTimeFormatter createDateTimeFormatter() {
return createDateTimeFormatter(DateTimeFormat.mediumDateTime());
}
/**
* Create a new {@code DateTimeFormatter} using this factory.
* <p>If no specific pattern or style has been defined,
* the supplied {@code fallbackFormatter} will be used.
* @param fallbackFormatter the fall-back formatter to use
* when no specific factory properties have been set
* @return a new date time formatter
*/
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
DateTimeFormatter dateTimeFormatter = null;
if (StringUtils.hasLength(this.pattern)) {
dateTimeFormatter = DateTimeFormat.forPattern(this.pattern);
}
else if (this.iso != null && this.iso != ISO.NONE) {
switch (this.iso) {
case DATE:
dateTimeFormatter = ISODateTimeFormat.date();
break;
case TIME:
dateTimeFormatter = ISODateTimeFormat.time();
break;
case DATE_TIME:
dateTimeFormatter = ISODateTimeFormat.dateTime();
break;
default:
throw new IllegalStateException("Unsupported ISO format: " + this.iso);
}
}
else if (StringUtils.hasLength(this.style)) {
dateTimeFormatter = DateTimeFormat.forStyle(this.style);
}
if (dateTimeFormatter != null && this.timeZone != null) {
dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
}
return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
}

View File

@ -1,67 +0,0 @@
/*
* Copyright 2002-2017 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.joda;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
/**
* {@link FactoryBean} that creates a Joda-Time {@link DateTimeFormatter}.
* See the {@link DateTimeFormatterFactory base class} for configuration details.
*
* @author Phillip Webb
* @author Sam Brannen
* @since 3.2
* @see #setPattern
* @see #setIso
* @see #setStyle
* @see DateTimeFormatterFactory
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public class DateTimeFormatterFactoryBean extends DateTimeFormatterFactory
implements FactoryBean<DateTimeFormatter>, InitializingBean {
@Nullable
private DateTimeFormatter dateTimeFormatter;
@Override
public void afterPropertiesSet() {
this.dateTimeFormatter = createDateTimeFormatter();
}
@Override
@Nullable
public DateTimeFormatter getObject() {
return this.dateTimeFormatter;
}
@Override
public Class<?> getObjectType() {
return DateTimeFormatter.class;
}
@Override
public boolean isSingleton() {
return true;
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Parser;
/**
* Parses Joda {@link DateTime} instances using a {@link DateTimeFormatter}.
*
* @author Keith Donald
* @since 3.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class DateTimeParser implements Parser<DateTime> {
private final DateTimeFormatter formatter;
/**
* Create a new DateTimeParser.
* @param formatter the Joda DateTimeFormatter instance
*/
public DateTimeParser(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public DateTime parse(String text, Locale locale) throws ParseException {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).parseDateTime(text);
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2002-2015 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.Duration;
import org.springframework.format.Formatter;
/**
* {@link Formatter} implementation for a Joda-Time {@link Duration},
* following Joda-Time's parsing rules for a Duration.
*
* @author Juergen Hoeller
* @since 4.2.4
* @see Duration#parse
*/
class DurationFormatter implements Formatter<Duration> {
@Override
public Duration parse(String text, Locale locale) throws ParseException {
return Duration.parse(text);
}
@Override
public String print(Duration object, Locale locale) {
return object.toString();
}
}

View File

@ -1,133 +0,0 @@
/*
* Copyright 2002-2017 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.joda;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.ReadableInstant;
import org.joda.time.ReadablePartial;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.support.EmbeddedValueResolutionSupport;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
/**
* Formats fields annotated with the {@link DateTimeFormat} annotation using Joda-Time.
*
* <p><b>NOTE:</b> Spring's Joda-Time support requires Joda-Time 2.x, as of Spring 4.0.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0
* @see DateTimeFormat
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public class JodaDateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<DateTimeFormat> {
private static final Set<Class<?>> FIELD_TYPES;
static {
// Create the set of field types that may be annotated with @DateTimeFormat.
// Note: the 3 ReadablePartial concrete types are registered explicitly since
// addFormatterForFieldType rules exist for each of these types
// (if we did not do this, the default byType rules for LocalDate, LocalTime,
// and LocalDateTime would take precedence over the annotation rule, which
// is not what we want)
Set<Class<?>> fieldTypes = new HashSet<>(8);
fieldTypes.add(ReadableInstant.class);
fieldTypes.add(LocalDate.class);
fieldTypes.add(LocalTime.class);
fieldTypes.add(LocalDateTime.class);
fieldTypes.add(Date.class);
fieldTypes.add(Calendar.class);
fieldTypes.add(Long.class);
FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
}
@Override
public final Set<Class<?>> getFieldTypes() {
return FIELD_TYPES;
}
@Override
public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
DateTimeFormatter formatter = getFormatter(annotation, fieldType);
if (ReadablePartial.class.isAssignableFrom(fieldType)) {
return new ReadablePartialPrinter(formatter);
}
else if (ReadableInstant.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) {
// assumes Calendar->ReadableInstant converter is registered
return new ReadableInstantPrinter(formatter);
}
else {
// assumes Date->Long converter is registered
return new MillisecondInstantPrinter(formatter);
}
}
@Override
public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) {
if (LocalDate.class == fieldType) {
return new LocalDateParser(getFormatter(annotation, fieldType));
}
else if (LocalTime.class == fieldType) {
return new LocalTimeParser(getFormatter(annotation, fieldType));
}
else if (LocalDateTime.class == fieldType) {
return new LocalDateTimeParser(getFormatter(annotation, fieldType));
}
else {
return new DateTimeParser(getFormatter(annotation, fieldType));
}
}
/**
* Factory method used to create a {@link DateTimeFormatter}.
* @param annotation the format annotation for the field
* @param fieldType the type of field
* @return a {@link DateTimeFormatter} instance
* @since 3.2
*/
protected DateTimeFormatter getFormatter(DateTimeFormat annotation, Class<?> fieldType) {
DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
String style = resolveEmbeddedValue(annotation.style());
if (StringUtils.hasLength(style)) {
factory.setStyle(style);
}
factory.setIso(annotation.iso());
String pattern = resolveEmbeddedValue(annotation.pattern());
if (StringUtils.hasLength(pattern)) {
factory.setPattern(pattern);
}
return factory.createDateTimeFormatter();
}
}

View File

@ -1,113 +0,0 @@
/*
* Copyright 2002-2017 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.joda;
import java.util.TimeZone;
import org.joda.time.Chronology;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.TimeZoneAwareLocaleContext;
import org.springframework.lang.Nullable;
/**
* A context that holds user-specific Joda-Time settings such as the user's
* Chronology (calendar system) and time zone.
*
* <p>A {@code null} property value indicate the user has not specified a setting.
*
* @author Keith Donald
* @since 3.0
* @see JodaTimeContextHolder
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public class JodaTimeContext {
@Nullable
private Chronology chronology;
@Nullable
private DateTimeZone timeZone;
/**
* Set the user's chronology (calendar system).
*/
public void setChronology(@Nullable Chronology chronology) {
this.chronology = chronology;
}
/**
* Return the user's chronology (calendar system), if any.
*/
@Nullable
public Chronology getChronology() {
return this.chronology;
}
/**
* Set the user's time zone.
* <p>Alternatively, set a {@link TimeZoneAwareLocaleContext} on
* {@link LocaleContextHolder}. This context class will fall back to
* checking the locale context if no setting has been provided here.
* @see org.springframework.context.i18n.LocaleContextHolder#getTimeZone()
* @see org.springframework.context.i18n.LocaleContextHolder#setLocaleContext
*/
public void setTimeZone(@Nullable DateTimeZone timeZone) {
this.timeZone = timeZone;
}
/**
* Return the user's time zone, if any.
*/
@Nullable
public DateTimeZone getTimeZone() {
return this.timeZone;
}
/**
* Get the DateTimeFormatter with the this context's settings
* applied to the base {@code formatter}.
* @param formatter the base formatter that establishes default
* formatting rules, generally context-independent
* @return the contextual DateTimeFormatter
*/
public DateTimeFormatter getFormatter(DateTimeFormatter formatter) {
if (this.chronology != null) {
formatter = formatter.withChronology(this.chronology);
}
if (this.timeZone != null) {
formatter = formatter.withZone(this.timeZone);
}
else {
LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
if (localeContext instanceof TimeZoneAwareLocaleContext) {
TimeZone timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
if (timeZone != null) {
formatter = formatter.withZone(DateTimeZone.forTimeZone(timeZone));
}
}
}
return formatter;
}
}

View File

@ -1,91 +0,0 @@
/*
* Copyright 2002-2018 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.joda;
import java.util.Locale;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;
/**
* A holder for a thread-local {@link JodaTimeContext}
* with user-specific Joda-Time settings.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.context.i18n.LocaleContextHolder
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class JodaTimeContextHolder {
private static final ThreadLocal<JodaTimeContext> jodaTimeContextHolder =
new NamedThreadLocal<>("JodaTimeContext");
private JodaTimeContextHolder() {
}
/**
* Reset the JodaTimeContext for the current thread.
*/
public static void resetJodaTimeContext() {
jodaTimeContextHolder.remove();
}
/**
* Associate the given JodaTimeContext with the current thread.
* @param jodaTimeContext the current JodaTimeContext,
* or {@code null} to reset the thread-bound context
*/
public static void setJodaTimeContext(@Nullable JodaTimeContext jodaTimeContext) {
if (jodaTimeContext == null) {
resetJodaTimeContext();
}
else {
jodaTimeContextHolder.set(jodaTimeContext);
}
}
/**
* Return the JodaTimeContext associated with the current thread, if any.
* @return the current JodaTimeContext, or {@code null} if none
*/
@Nullable
public static JodaTimeContext getJodaTimeContext() {
return jodaTimeContextHolder.get();
}
/**
* Obtain a DateTimeFormatter with user-specific settings applied to the given base Formatter.
* @param formatter the base formatter that establishes default formatting rules
* (generally user independent)
* @param locale the current user locale (may be {@code null} if not known)
* @return the user-specific DateTimeFormatter
*/
public static DateTimeFormatter getFormatter(DateTimeFormatter formatter, @Nullable Locale locale) {
DateTimeFormatter formatterToUse = (locale != null ? formatter.withLocale(locale) : formatter);
JodaTimeContext context = getJodaTimeContext();
return (context != null ? context.getFormatter(formatterToUse) : formatterToUse);
}
}

View File

@ -1,219 +0,0 @@
/*
* Copyright 2002-2018 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.joda;
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.MutableDateTime;
import org.joda.time.ReadableInstant;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.format.datetime.DateFormatterRegistrar;
/**
* Installs lower-level type converters required to integrate
* Joda-Time support into Spring's field formatting system.
*
* <p>Note: {@link JodaTimeFormatterRegistrar} installs these converters
* and relies on several of them for its formatters. Some additional
* converters are just being registered for custom conversion scenarios.
*
* @author Keith Donald
* @author Phillip Webb
* @author Juergen Hoeller
* @since 3.0
*/
final class JodaTimeConverters {
private JodaTimeConverters() {
}
/**
* Install the converters into the converter registry.
* @param registry the converter registry
*/
@SuppressWarnings("deprecation")
public static void registerConverters(ConverterRegistry registry) {
DateFormatterRegistrar.addDateConverters(registry);
registry.addConverter(new DateTimeToLocalDateConverter());
registry.addConverter(new DateTimeToLocalTimeConverter());
registry.addConverter(new DateTimeToLocalDateTimeConverter());
registry.addConverter(new DateTimeToDateMidnightConverter());
registry.addConverter(new DateTimeToMutableDateTimeConverter());
registry.addConverter(new DateTimeToInstantConverter());
registry.addConverter(new DateTimeToDateConverter());
registry.addConverter(new DateTimeToCalendarConverter());
registry.addConverter(new DateTimeToLongConverter());
registry.addConverter(new DateToReadableInstantConverter());
registry.addConverter(new CalendarToReadableInstantConverter());
registry.addConverter(new LongToReadableInstantConverter());
registry.addConverter(new LocalDateTimeToLocalDateConverter());
registry.addConverter(new LocalDateTimeToLocalTimeConverter());
}
private static class DateTimeToLocalDateConverter implements Converter<DateTime, LocalDate> {
@Override
public LocalDate convert(DateTime source) {
return source.toLocalDate();
}
}
private static class DateTimeToLocalTimeConverter implements Converter<DateTime, LocalTime> {
@Override
public LocalTime convert(DateTime source) {
return source.toLocalTime();
}
}
private static class DateTimeToLocalDateTimeConverter implements Converter<DateTime, LocalDateTime> {
@Override
public LocalDateTime convert(DateTime source) {
return source.toLocalDateTime();
}
}
@Deprecated
private static class DateTimeToDateMidnightConverter implements Converter<DateTime, org.joda.time.DateMidnight> {
@Override
public org.joda.time.DateMidnight convert(DateTime source) {
return source.toDateMidnight();
}
}
private static class DateTimeToMutableDateTimeConverter implements Converter<DateTime, MutableDateTime> {
@Override
public MutableDateTime convert(DateTime source) {
return source.toMutableDateTime();
}
}
private static class DateTimeToInstantConverter implements Converter<DateTime, Instant> {
@Override
public Instant convert(DateTime source) {
return source.toInstant();
}
}
private static class DateTimeToDateConverter implements Converter<DateTime, Date> {
@Override
public Date convert(DateTime source) {
return source.toDate();
}
}
private static class DateTimeToCalendarConverter implements Converter<DateTime, Calendar> {
@Override
public Calendar convert(DateTime source) {
return source.toGregorianCalendar();
}
}
private static class DateTimeToLongConverter implements Converter<DateTime, Long> {
@Override
public Long convert(DateTime source) {
return source.getMillis();
}
}
/**
* Used when printing a {@code java.util.Date} field with a ReadableInstantPrinter.
* @see MillisecondInstantPrinter
* @see JodaDateTimeFormatAnnotationFormatterFactory
*/
private static class DateToReadableInstantConverter implements Converter<Date, ReadableInstant> {
@Override
public ReadableInstant convert(Date source) {
return new DateTime(source);
}
}
/**
* Used when printing a {@code java.util.Calendar} field with a ReadableInstantPrinter.
* @see MillisecondInstantPrinter
* @see JodaDateTimeFormatAnnotationFormatterFactory
*/
private static class CalendarToReadableInstantConverter implements Converter<Calendar, ReadableInstant> {
@Override
public ReadableInstant convert(Calendar source) {
return new DateTime(source);
}
}
/**
* Used when printing a Long field with a ReadableInstantPrinter.
* @see MillisecondInstantPrinter
* @see JodaDateTimeFormatAnnotationFormatterFactory
*/
private static class LongToReadableInstantConverter implements Converter<Long, ReadableInstant> {
@Override
public ReadableInstant convert(Long source) {
return new DateTime(source.longValue());
}
}
private static class LocalDateTimeToLocalDateConverter implements Converter<LocalDateTime, LocalDate> {
@Override
public LocalDate convert(LocalDateTime source) {
return source.toLocalDate();
}
}
private static class LocalDateTimeToLocalTimeConverter implements Converter<LocalDateTime, LocalTime> {
@Override
public LocalTime convert(LocalDateTime source) {
return source.toLocalTime();
}
}
}

View File

@ -1,236 +0,0 @@
/*
* Copyright 2002-2017 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.joda;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.MonthDay;
import org.joda.time.Period;
import org.joda.time.ReadableInstant;
import org.joda.time.YearMonth;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
import org.springframework.format.annotation.DateTimeFormat.ISO;
/**
* Configures Joda-Time's formatting system for use with Spring.
*
* <p><b>NOTE:</b> Spring's Joda-Time support requires Joda-Time 2.x, as of Spring 4.0.
*
* @author Keith Donald
* @author Juergen Hoeller
* @author Phillip Webb
* @since 3.1
* @see #setDateStyle
* @see #setTimeStyle
* @see #setDateTimeStyle
* @see #setUseIsoFormat
* @see FormatterRegistrar#registerFormatters
* @see org.springframework.format.datetime.DateFormatterRegistrar
* @see DateTimeFormatterFactoryBean
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public class JodaTimeFormatterRegistrar implements FormatterRegistrar {
private enum Type {DATE, TIME, DATE_TIME}
/**
* User defined formatters.
*/
private final Map<Type, DateTimeFormatter> formatters = new EnumMap<>(Type.class);
/**
* Factories used when specific formatters have not been specified.
*/
private final Map<Type, DateTimeFormatterFactory> factories;
public JodaTimeFormatterRegistrar() {
this.factories = new EnumMap<>(Type.class);
for (Type type : Type.values()) {
this.factories.put(type, new DateTimeFormatterFactory());
}
}
/**
* Set whether standard ISO formatting should be applied to all date/time types.
* Default is "false" (no).
* <p>If set to "true", the "dateStyle", "timeStyle" and "dateTimeStyle"
* properties are effectively ignored.
*/
public void setUseIsoFormat(boolean useIsoFormat) {
this.factories.get(Type.DATE).setIso(useIsoFormat ? ISO.DATE : ISO.NONE);
this.factories.get(Type.TIME).setIso(useIsoFormat ? ISO.TIME : ISO.NONE);
this.factories.get(Type.DATE_TIME).setIso(useIsoFormat ? ISO.DATE_TIME : ISO.NONE);
}
/**
* Set the default format style of Joda {@link LocalDate} objects.
* Default is {@link DateTimeFormat#shortDate()}.
*/
public void setDateStyle(String dateStyle) {
this.factories.get(Type.DATE).setStyle(dateStyle + "-");
}
/**
* Set the default format style of Joda {@link LocalTime} objects.
* Default is {@link DateTimeFormat#shortTime()}.
*/
public void setTimeStyle(String timeStyle) {
this.factories.get(Type.TIME).setStyle("-" + timeStyle);
}
/**
* Set the default format style of Joda {@link LocalDateTime} and {@link DateTime} objects,
* as well as JDK {@link Date} and {@link Calendar} objects.
* Default is {@link DateTimeFormat#shortDateTime()}.
*/
public void setDateTimeStyle(String dateTimeStyle) {
this.factories.get(Type.DATE_TIME).setStyle(dateTimeStyle);
}
/**
* Set the formatter that will be used for objects representing date values.
* <p>This formatter will be used for the {@link LocalDate} type. When specified
* the {@link #setDateStyle(String) dateStyle} and
* {@link #setUseIsoFormat(boolean) useIsoFormat} properties will be ignored.
* @param formatter the formatter to use
* @since 3.2
* @see #setTimeFormatter
* @see #setDateTimeFormatter
*/
public void setDateFormatter(DateTimeFormatter formatter) {
this.formatters.put(Type.DATE, formatter);
}
/**
* Set the formatter that will be used for objects representing time values.
* <p>This formatter will be used for the {@link LocalTime} type. When specified
* the {@link #setTimeStyle(String) timeStyle} and
* {@link #setUseIsoFormat(boolean) useIsoFormat} properties will be ignored.
* @param formatter the formatter to use
* @since 3.2
* @see #setDateFormatter
* @see #setDateTimeFormatter
*/
public void setTimeFormatter(DateTimeFormatter formatter) {
this.formatters.put(Type.TIME, formatter);
}
/**
* Set the formatter that will be used for objects representing date and time values.
* <p>This formatter will be used for {@link LocalDateTime}, {@link ReadableInstant},
* {@link Date} and {@link Calendar} types. When specified
* the {@link #setDateTimeStyle(String) dateTimeStyle} and
* {@link #setUseIsoFormat(boolean) useIsoFormat} properties will be ignored.
* @param formatter the formatter to use
* @since 3.2
* @see #setDateFormatter
* @see #setTimeFormatter
*/
public void setDateTimeFormatter(DateTimeFormatter formatter) {
this.formatters.put(Type.DATE_TIME, formatter);
}
@Override
public void registerFormatters(FormatterRegistry registry) {
JodaTimeConverters.registerConverters(registry);
DateTimeFormatter dateFormatter = getFormatter(Type.DATE);
DateTimeFormatter timeFormatter = getFormatter(Type.TIME);
DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateFormatter),
new LocalDateParser(dateFormatter),
LocalDate.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(timeFormatter),
new LocalTimeParser(timeFormatter),
LocalTime.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateTimeFormatter),
new LocalDateTimeParser(dateTimeFormatter),
LocalDateTime.class);
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
ReadableInstant.class);
// In order to retain backwards compatibility we only register Date/Calendar
// types when a user defined formatter is specified (see SPR-10105)
if (this.formatters.containsKey(Type.DATE_TIME)) {
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
Date.class, Calendar.class);
}
registry.addFormatterForFieldType(Period.class, new PeriodFormatter());
registry.addFormatterForFieldType(Duration.class, new DurationFormatter());
registry.addFormatterForFieldType(YearMonth.class, new YearMonthFormatter());
registry.addFormatterForFieldType(MonthDay.class, new MonthDayFormatter());
registry.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
}
private DateTimeFormatter getFormatter(Type type) {
DateTimeFormatter formatter = this.formatters.get(type);
if (formatter != null) {
return formatter;
}
DateTimeFormatter fallbackFormatter = getFallbackFormatter(type);
return this.factories.get(type).createDateTimeFormatter(fallbackFormatter);
}
private DateTimeFormatter getFallbackFormatter(Type type) {
switch (type) {
case DATE: return DateTimeFormat.shortDate();
case TIME: return DateTimeFormat.shortTime();
default: return DateTimeFormat.shortDateTime();
}
}
private void addFormatterForFields(FormatterRegistry registry, Printer<?> printer,
Parser<?> parser, Class<?>... fieldTypes) {
for (Class<?> fieldType : fieldTypes) {
registry.addFormatterForFieldType(fieldType, printer, parser);
}
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Parser;
/**
* Parses Joda {@link org.joda.time.LocalDate} instances using a
* {@link org.joda.time.format.DateTimeFormatter}.
*
* @author Juergen Hoeller
* @since 4.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class LocalDateParser implements Parser<LocalDate> {
private final DateTimeFormatter formatter;
/**
* Create a new DateTimeParser.
* @param formatter the Joda DateTimeFormatter instance
*/
public LocalDateParser(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).parseLocalDate(text);
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Parser;
/**
* Parses Joda {@link org.joda.time.LocalDateTime} instances using a
* {@link org.joda.time.format.DateTimeFormatter}.
*
* @author Juergen Hoeller
* @since 4.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class LocalDateTimeParser implements Parser<LocalDateTime> {
private final DateTimeFormatter formatter;
/**
* Create a new DateTimeParser.
* @param formatter the Joda DateTimeFormatter instance
*/
public LocalDateTimeParser(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public LocalDateTime parse(String text, Locale locale) throws ParseException {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).parseLocalDateTime(text);
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Parser;
/**
* Parses Joda {@link org.joda.time.LocalTime} instances using a
* {@link org.joda.time.format.DateTimeFormatter}.
*
* @author Juergen Hoeller
* @since 4.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class LocalTimeParser implements Parser<LocalTime> {
private final DateTimeFormatter formatter;
/**
* Create a new DateTimeParser.
* @param formatter the Joda DateTimeFormatter instance
*/
public LocalTimeParser(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public LocalTime parse(String text, Locale locale) throws ParseException {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).parseLocalTime(text);
}
}

View File

@ -1,52 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.util.Locale;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Printer;
/**
* Prints Long instances using a Joda {@link DateTimeFormatter}.
*
* @author Keith Donald
* @since 3.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class MillisecondInstantPrinter implements Printer<Long> {
private final DateTimeFormatter formatter;
/**
* Create a new ReadableInstantPrinter.
* @param formatter the Joda DateTimeFormatter instance
*/
public MillisecondInstantPrinter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public String print(Long instant, Locale locale) {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).print(instant);
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2002-2015 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.MonthDay;
import org.springframework.format.Formatter;
/**
* {@link Formatter} implementation for a Joda-Time {@link MonthDay},
* following Joda-Time's parsing rules for a MonthDay.
*
* @author Juergen Hoeller
* @since 4.2.4
* @see MonthDay#parse
*/
class MonthDayFormatter implements Formatter<MonthDay> {
@Override
public MonthDay parse(String text, Locale locale) throws ParseException {
return MonthDay.parse(text);
}
@Override
public String print(MonthDay object, Locale locale) {
return object.toString();
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2002-2015 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.Period;
import org.springframework.format.Formatter;
/**
* {@link Formatter} implementation for a Joda-Time {@link Period},
* following Joda-Time's parsing rules for a Period.
*
* @author Juergen Hoeller
* @since 4.2.4
* @see Period#parse
*/
class PeriodFormatter implements Formatter<Period> {
@Override
public Period parse(String text, Locale locale) throws ParseException {
return Period.parse(text);
}
@Override
public String print(Period object, Locale locale) {
return object.toString();
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.util.Locale;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Printer;
/**
* Prints Joda-Time {@link ReadableInstant} instances using a {@link DateTimeFormatter}.
*
* @author Keith Donald
* @since 3.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class ReadableInstantPrinter implements Printer<ReadableInstant> {
private final DateTimeFormatter formatter;
/**
* Create a new ReadableInstantPrinter.
* @param formatter the Joda DateTimeFormatter instance
*/
public ReadableInstantPrinter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public String print(ReadableInstant instant, Locale locale) {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).print(instant);
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 2002-2013 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.joda;
import java.util.Locale;
import org.joda.time.ReadablePartial;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.Printer;
/**
* Prints Joda-Time {@link ReadablePartial} instances using a {@link DateTimeFormatter}.
*
* @author Keith Donald
* @since 3.0
* @deprecated as of 5.3, in favor of standard JSR-310 support
*/
@Deprecated
public final class ReadablePartialPrinter implements Printer<ReadablePartial> {
private final DateTimeFormatter formatter;
/**
* Create a new ReadableInstantPrinter.
* @param formatter the Joda DateTimeFormatter instance
*/
public ReadablePartialPrinter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public String print(ReadablePartial partial, Locale locale) {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).print(partial);
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2002-2015 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.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.YearMonth;
import org.springframework.format.Formatter;
/**
* {@link Formatter} implementation for a Joda-Time {@link YearMonth},
* following Joda-Time's parsing rules for a YearMonth.
*
* @author Juergen Hoeller
* @since 4.2.4
* @see YearMonth#parse
*/
class YearMonthFormatter implements Formatter<YearMonth> {
@Override
public YearMonth parse(String text, Locale locale) throws ParseException {
return YearMonth.parse(text);
}
@Override
public String print(YearMonth object, Locale locale) {
return object.toString();
}
}

View File

@ -1,9 +0,0 @@
/**
* Integration with Joda-Time for formatting Joda date and time types as well as standard JDK Date types.
*/
@NonNullApi
@NonNullFields
package org.springframework.format.datetime.joda;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@ -50,7 +50,6 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
* @see #setUseIsoFormat
* @see org.springframework.format.FormatterRegistrar#registerFormatters
* @see org.springframework.format.datetime.DateFormatterRegistrar
* @see org.springframework.format.datetime.joda.DateTimeFormatterFactoryBean
*/
public class DateTimeFormatterRegistrar implements FormatterRegistrar {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -48,12 +48,9 @@ public class DefaultFormattingConversionService extends FormattingConversionServ
private static final boolean jsr354Present;
private static final boolean jodaTimePresent;
static {
ClassLoader classLoader = DefaultFormattingConversionService.class.getClassLoader();
jsr354Present = ClassUtils.isPresent("javax.money.MonetaryAmount", classLoader);
jodaTimePresent = ClassUtils.isPresent("org.joda.time.YearMonth", classLoader);
}
/**
@ -104,7 +101,6 @@ public class DefaultFormattingConversionService extends FormattingConversionServ
* depending on the presence of the corresponding API on the classpath.
* @param formatterRegistry the service to register default formatters with
*/
@SuppressWarnings("deprecation")
public static void addDefaultFormatters(FormatterRegistry formatterRegistry) {
// Default handling of number values
formatterRegistry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
@ -121,14 +117,8 @@ public class DefaultFormattingConversionService extends FormattingConversionServ
// just handling JSR-310 specific date and time types
new DateTimeFormatterRegistrar().registerFormatters(formatterRegistry);
if (jodaTimePresent) {
// handles Joda-specific types as well as Date, Calendar, Long
new org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar().registerFormatters(formatterRegistry);
}
else {
// regular DateFormat-based Date, Calendar, Long converters
new DateFormatterRegistrar().registerFormatters(formatterRegistry);
}
// regular DateFormat-based Date, Calendar, Long converters
new DateFormatterRegistrar().registerFormatters(formatterRegistry);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -23,9 +23,6 @@ import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO;
@ -33,9 +30,6 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link DateFormatter}.
*
@ -137,40 +131,6 @@ public class DateFormatterTests {
assertThat(formatter.parse("2009-06-01T14:23:05.003Z", Locale.US)).isEqualTo(date);
}
@Test
public void shouldSupportJodaStylePatterns() throws Exception {
String[] chars = { "S", "M", "-" };
for (String d : chars) {
for (String t : chars) {
String style = d + t;
if (!style.equals("--")) {
Date date = getDate(2009, Calendar.JUNE, 10, 14, 23, 0, 0);
if (t.equals("-")) {
date = getDate(2009, Calendar.JUNE, 10);
}
else if (d.equals("-")) {
date = getDate(1970, Calendar.JANUARY, 1, 14, 23, 0, 0);
}
testJodaStylePatterns(style, Locale.US, date);
}
}
}
}
private void testJodaStylePatterns(String style, Locale locale, Date date) throws Exception {
DateFormatter formatter = new DateFormatter();
formatter.setTimeZone(UTC);
formatter.setStylePattern(style);
DateTimeFormatter jodaFormatter = DateTimeFormat.forStyle(style).withLocale(locale).withZone(DateTimeZone.UTC);
String jodaPrinted = jodaFormatter.print(date.getTime());
assertThat(formatter.print(date, locale))
.as("Unable to print style pattern " + style)
.isEqualTo(jodaPrinted);
assertThat(formatter.parse(jodaPrinted, locale))
.as("Unable to parse style pattern " + style)
.isEqualTo(date);
}
@Test
public void shouldThrowOnUnsupportedStylePattern() throws Exception {
DateFormatter formatter = new DateFormatter();

View File

@ -1,63 +0,0 @@
/*
* Copyright 2002-2019 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.joda;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Phillip Webb
* @author Sam Brannen
*/
public class DateTimeFormatterFactoryBeanTests {
private final DateTimeFormatterFactoryBean factory = new DateTimeFormatterFactoryBean();
@Test
public void isSingleton() {
assertThat(factory.isSingleton()).isTrue();
}
@Test
public void getObjectType() {
assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class);
}
@Test
public void getObject() {
factory.afterPropertiesSet();
assertThat(factory.getObject()).isEqualTo(DateTimeFormat.mediumDateTime());
}
@Test
public void getObjectIsAlwaysSingleton() {
factory.afterPropertiesSet();
DateTimeFormatter formatter = factory.getObject();
assertThat(formatter).isEqualTo(DateTimeFormat.mediumDateTime());
factory.setStyle("LL");
assertThat(factory.getObject()).isSameAs(formatter);
}
}

View File

@ -1,104 +0,0 @@
/*
* Copyright 2002-2019 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.joda;
import java.util.Locale;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Phillip Webb
* @author Sam Brannen
*/
public class DateTimeFormatterFactoryTests {
// Potential test timezone, both have daylight savings on October 21st
private static final TimeZone ZURICH = TimeZone.getTimeZone("Europe/Zurich");
private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
// Ensure that we are testing against a timezone other than the default.
private static final TimeZone TEST_TIMEZONE = ZURICH.equals(TimeZone.getDefault()) ? NEW_YORK : ZURICH;
private DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
private DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00);
@Test
public void createDateTimeFormatter() {
assertThat(factory.createDateTimeFormatter()).isEqualTo(DateTimeFormat.mediumDateTime());
}
@Test
public void createDateTimeFormatterWithPattern() {
factory = new DateTimeFormatterFactory("yyyyMMddHHmmss");
DateTimeFormatter formatter = factory.createDateTimeFormatter();
assertThat(formatter.print(dateTime)).isEqualTo("20091021121000");
}
@Test
public void createDateTimeFormatterWithNullFallback() {
DateTimeFormatter formatter = factory.createDateTimeFormatter(null);
assertThat(formatter).isNull();
}
@Test
public void createDateTimeFormatterWithFallback() {
DateTimeFormatter fallback = DateTimeFormat.forStyle("LL");
DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
assertThat(formatter).isSameAs(fallback);
}
@Test
public void createDateTimeFormatterInOrderOfPropertyPriority() {
factory.setStyle("SS");
String value = applyLocale(factory.createDateTimeFormatter()).print(dateTime);
assertThat(value.startsWith("10/21/09")).isTrue();
assertThat(value.endsWith("12:10 PM")).isTrue();
factory.setIso(ISO.DATE);
assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime)).isEqualTo("2009-10-21");
factory.setPattern("yyyyMMddHHmmss");
assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000");
}
@Test
public void createDateTimeFormatterWithTimeZone() {
factory.setPattern("yyyyMMddHHmmss Z");
factory.setTimeZone(TEST_TIMEZONE);
DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TEST_TIMEZONE);
DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200");
assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000 " + offset);
}
private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {
return dateTimeFormatter.withLocale(Locale.US);
}
}

View File

@ -1,770 +0,0 @@
/*
* Copyright 2002-2019 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.joda;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.MonthDay;
import org.joda.time.Period;
import org.joda.time.YearMonth;
import org.joda.time.chrono.ISOChronology;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.validation.DataBinder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Keith Donald
* @author Juergen Hoeller
* @author Phillip Webb
*/
public class JodaTimeFormattingTests {
private FormattingConversionService conversionService;
private DataBinder binder;
@BeforeEach
public void setup() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
setup(registrar);
}
private void setup(JodaTimeFormatterRegistrar registrar) {
conversionService = new FormattingConversionService();
DefaultConversionService.addDefaultConverters(conversionService);
registrar.registerFormatters(conversionService);
JodaTimeBean bean = new JodaTimeBean();
bean.getChildren().add(new JodaTimeBean());
binder = new DataBinder(bean);
binder.setConversionService(conversionService);
LocaleContextHolder.setLocale(Locale.US);
JodaTimeContext context = new JodaTimeContext();
context.setTimeZone(DateTimeZone.forID("-05:00"));
JodaTimeContextHolder.setJodaTimeContext(context);
}
@AfterEach
public void cleanup() {
LocaleContextHolder.setLocale(null);
JodaTimeContextHolder.setJodaTimeContext(null);
}
@Test
public void testJodaTimePatternsForStyle() {
System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("SS", LocaleContextHolder.getLocale()));
System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("LL", LocaleContextHolder.getLocale()));
System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("FF", LocaleContextHolder.getLocale()));
}
@Test
public void testBindLocalDate() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDate", "10/31/09");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("10/31/09");
}
@Test
public void testBindLocalDateWithSpecificStyle() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setDateStyle("L");
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDate", "October 31, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("October 31, 2009");
}
@Test
public void testBindLocalDateWithSpecificFormatter() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setDateFormatter(org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd"));
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDate", "20091031");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("20091031");
}
@Test
public void testBindLocalDateArray() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDate", new String[]{"10/31/09"});
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
}
@Test
public void testBindLocalDateAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateAnnotated", "Oct 31, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009");
}
@Test
public void testBindLocalDateAnnotatedWithError() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateAnnotated", "Oct 031, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 031, 2009");
}
@Test
public void testBindNestedLocalDateAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("children[0].localDateAnnotated", "Oct 31, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("children[0].localDateAnnotated")).isEqualTo("Oct 31, 2009");
}
@Test
public void testBindLocalDateAnnotatedWithDirectFieldAccess() {
binder.initDirectFieldAccess();
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateAnnotated", "Oct 31, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009");
}
@Test
public void testBindLocalDateAnnotatedWithDirectFieldAccessAndError() {
binder.initDirectFieldAccess();
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateAnnotated", "Oct 031, 2009");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 031, 2009");
}
@Test
public void testBindLocalTime() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localTime", "12:00 PM");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00 PM");
}
@Test
public void testBindLocalTimeWithSpecificStyle() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setTimeStyle("M");
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localTime", "12:00:00 PM");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00:00 PM");
}
@Test
public void testBindLocalTimeWithSpecificFormatter() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setTimeFormatter(org.joda.time.format.DateTimeFormat.forPattern("HHmmss"));
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localTime", "130000");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("130000");
}
@Test
public void testBindLocalTimeAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localTimeAnnotated", "12:00:00 PM");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("localTimeAnnotated")).isEqualTo("12:00:00 PM");
}
@Test
public void testBindLocalDateTime() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateTime", new LocalDateTime(2009, 10, 31, 12, 0));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("localDateTime").toString();
assertThat(value.startsWith("10/31/09")).isTrue();
assertThat(value.endsWith("12:00 PM")).isTrue();
}
@Test
public void testBindLocalDateTimeAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateTimeAnnotated", new LocalDateTime(2009, 10, 31, 12, 0));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("localDateTimeAnnotated").toString();
assertThat(value.startsWith("Oct 31, 2009")).isTrue();
assertThat(value.endsWith("12:00 PM")).isTrue();
}
@Test
public void testBindDateTime() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTime", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC()));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("dateTime").toString();
assertThat(value.startsWith("10/31/09")).isTrue();
}
@Test
public void testBindDateTimeWithSpecificStyle() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setDateTimeStyle("MM");
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("localDateTime", new LocalDateTime(2009, 10, 31, 12, 0));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("localDateTime").toString();
assertThat(value.startsWith("Oct 31, 2009")).isTrue();
assertThat(value.endsWith("12:00:00 PM")).isTrue();
}
@Test
public void testBindDateTimeISO() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTime", "2009-10-31T12:00:00.000Z");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("dateTime")).isEqualTo("2009-10-31T07:00:00.000-05:00");
}
@Test
public void testBindDateTimeWithSpecificFormatter() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.forPattern("yyyyMMddHHmmss"));
setup(registrar);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTime", "20091031130000");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("dateTime")).isEqualTo("20091031130000");
}
@Test
public void testBindDateTimeAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTimeAnnotated", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC()));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("dateTimeAnnotated").toString();
assertThat(value.startsWith("Oct 31, 2009")).isTrue();
}
@Test
public void testBindDateTimeAnnotatedPattern() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTimeAnnotatedPattern", "10/31/09 12:00 PM");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern")).isEqualTo("10/31/09 12:00 PM");
}
@Test
public void testBindDateTimeOverflow() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTimeAnnotatedPattern", "02/29/09 12:00 PM");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1);
}
@Test
public void testBindDateTimeAnnotatedDefault() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateTimeAnnotatedDefault", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC()));
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
String value = binder.getBindingResult().getFieldValue("dateTimeAnnotatedDefault").toString();
assertThat(value.startsWith("10/31/09")).isTrue();
}
@Test
public void testBindDateWithErrorAvoidingDateConstructor() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("date", "Sat, 12 Aug 1995 13:30:00 GMT");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("date")).isEqualTo("Sat, 12 Aug 1995 13:30:00 GMT");
}
@Test
public void testBindDateWithoutErrorFallingBackToDateConstructor() {
DataBinder binder = new DataBinder(new JodaTimeBean());
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("date", "Sat, 12 Aug 1995 13:30:00 GMT");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
}
@Test
public void testBindDateAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("dateAnnotated", "10/31/09");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("dateAnnotated")).isEqualTo("10/31/09");
}
@Test
public void testBindCalendarAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("calendarAnnotated", "10/31/09");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("calendarAnnotated")).isEqualTo("10/31/09");
}
@Test
public void testBindLong() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("millis", "1256961600");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("millis")).isEqualTo("1256961600");
}
@Test
public void testBindLongAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("millisAnnotated", "10/31/09");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("millisAnnotated")).isEqualTo("10/31/09");
}
@Test
public void testBindISODate() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("isoDate", "2009-10-31");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("isoDate")).isEqualTo("2009-10-31");
}
@Test
public void testBindISOTime() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("isoTime", "12:00:00.000-05:00");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("isoTime")).isEqualTo("12:00:00.000");
}
@Test
public void testBindISODateTime() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000Z");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("isoDateTime")).isEqualTo("2009-10-31T07:00:00.000-05:00");
}
@Test
public void testBindInstantAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("instantAnnotated", "2009-10-31T12:00:00.000Z");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("instantAnnotated")).isEqualTo("2009-10-31T07:00:00.000-05:00");
}
@Test
public void testBindMutableDateTimeAnnotated() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("mutableDateTimeAnnotated", "2009-10-31T12:00:00.000Z");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("mutableDateTimeAnnotated")).isEqualTo("2009-10-31T07:00:00.000-05:00");
}
@Test
public void dateToStringWithFormat() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.shortDateTime());
setup(registrar);
Date date = new Date();
Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class));
String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date));
assertThat(actual).isEqualTo(expected);
}
@Test // SPR-10105
@SuppressWarnings("deprecation")
public void stringToDateWithoutGlobalFormat() {
String string = "Sat, 12 Aug 1995 13:30:00 GM";
Date date = this.conversionService.convert(string, Date.class);
assertThat(date).isEqualTo(new Date(string));
}
@Test // SPR-10105
public void stringToDateWithGlobalFormat() {
JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
factory.setIso(ISO.DATE_TIME);
registrar.setDateTimeFormatter(factory.createDateTimeFormatter());
setup(registrar);
// This is a format that cannot be parsed by new Date(String)
String string = "2009-10-31T07:00:00.000-05:00";
Date date = this.conversionService.convert(string, Date.class);
assertThat(date).isNotNull();
}
@Test
public void testBindPeriod() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("period", "P6Y3M1D");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")).isTrue();
}
@Test
public void testBindDuration() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("duration", "PT72.345S");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("duration").toString().equals("PT72.345S")).isTrue();
}
@Test
public void testBindYearMonth() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("yearMonth", "2007-12");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")).isTrue();
}
@Test
public void testBindMonthDay() {
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("monthDay", "--12-03");
binder.bind(propertyValues);
assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0);
assertThat(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")).isTrue();
}
@SuppressWarnings("unused")
private static class JodaTimeBean {
private LocalDate localDate;
@DateTimeFormat(style="M-")
private LocalDate localDateAnnotated;
private LocalTime localTime;
@DateTimeFormat(style="-M")
private LocalTime localTimeAnnotated;
private LocalDateTime localDateTime;
@DateTimeFormat(style="MS")
private LocalDateTime localDateTimeAnnotated;
private DateTime dateTime;
@DateTimeFormat(style="MS")
private DateTime dateTimeAnnotated;
@DateTimeFormat
private Date date;
@DateTimeFormat(style="S-")
private Date dateAnnotated;
@DateTimeFormat(style="S-")
private Calendar calendarAnnotated;
private Long millis;
@DateTimeFormat
private DateTime dateTimeAnnotatedDefault;
private Long millisAnnotated;
@DateTimeFormat(pattern="M/d/yy h:mm a")
private DateTime dateTimeAnnotatedPattern;
@DateTimeFormat(iso=ISO.DATE)
private LocalDate isoDate;
@DateTimeFormat(iso=ISO.TIME)
private LocalTime isoTime;
@DateTimeFormat(iso=ISO.DATE_TIME)
private DateTime isoDateTime;
@DateTimeFormat(iso=ISO.DATE_TIME)
private Instant instantAnnotated;
@DateTimeFormat(iso=ISO.DATE_TIME)
private Instant mutableDateTimeAnnotated;
private Period period;
private Duration duration;
private YearMonth yearMonth;
private MonthDay monthDay;
private final List<JodaTimeBean> children = new ArrayList<>();
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public LocalDate getLocalDateAnnotated() {
return localDateAnnotated;
}
public void setLocalDateAnnotated(LocalDate localDateAnnotated) {
this.localDateAnnotated = localDateAnnotated;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public LocalTime getLocalTimeAnnotated() {
return localTimeAnnotated;
}
public void setLocalTimeAnnotated(LocalTime localTimeAnnotated) {
this.localTimeAnnotated = localTimeAnnotated;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public LocalDateTime getLocalDateTimeAnnotated() {
return localDateTimeAnnotated;
}
public void setLocalDateTimeAnnotated(LocalDateTime localDateTimeAnnotated) {
this.localDateTimeAnnotated = localDateTimeAnnotated;
}
public DateTime getDateTime() {
return dateTime;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public DateTime getDateTimeAnnotated() {
return dateTimeAnnotated;
}
public void setDateTimeAnnotated(DateTime dateTimeAnnotated) {
this.dateTimeAnnotated = dateTimeAnnotated;
}
public DateTime getDateTimeAnnotatedPattern() {
return dateTimeAnnotatedPattern;
}
public void setDateTimeAnnotatedPattern(DateTime dateTimeAnnotatedPattern) {
this.dateTimeAnnotatedPattern = dateTimeAnnotatedPattern;
}
public DateTime getDateTimeAnnotatedDefault() {
return dateTimeAnnotatedDefault;
}
public void setDateTimeAnnotatedDefault(DateTime dateTimeAnnotatedDefault) {
this.dateTimeAnnotatedDefault = dateTimeAnnotatedDefault;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDateAnnotated() {
return dateAnnotated;
}
public void setDateAnnotated(Date dateAnnotated) {
this.dateAnnotated = dateAnnotated;
}
public Calendar getCalendarAnnotated() {
return calendarAnnotated;
}
public void setCalendarAnnotated(Calendar calendarAnnotated) {
this.calendarAnnotated = calendarAnnotated;
}
public Long getMillis() {
return millis;
}
public void setMillis(Long millis) {
this.millis = millis;
}
@DateTimeFormat(style="S-")
public Long getMillisAnnotated() {
return millisAnnotated;
}
public void setMillisAnnotated(@DateTimeFormat(style="S-") Long millisAnnotated) {
this.millisAnnotated = millisAnnotated;
}
public LocalDate getIsoDate() {
return isoDate;
}
public void setIsoDate(LocalDate isoDate) {
this.isoDate = isoDate;
}
public LocalTime getIsoTime() {
return isoTime;
}
public void setIsoTime(LocalTime isoTime) {
this.isoTime = isoTime;
}
public DateTime getIsoDateTime() {
return isoDateTime;
}
public void setIsoDateTime(DateTime isoDateTime) {
this.isoDateTime = isoDateTime;
}
public Instant getInstantAnnotated() {
return instantAnnotated;
}
public void setInstantAnnotated(Instant instantAnnotated) {
this.instantAnnotated = instantAnnotated;
}
public Instant getMutableDateTimeAnnotated() {
return mutableDateTimeAnnotated;
}
public void setMutableDateTimeAnnotated(Instant mutableDateTimeAnnotated) {
this.mutableDateTimeAnnotated = mutableDateTimeAnnotated;
}
public Period getPeriod() {
return period;
}
public void setPeriod(Period period) {
this.period = period;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public YearMonth getYearMonth() {
return yearMonth;
}
public void setYearMonth(YearMonth yearMonth) {
this.yearMonth = yearMonth;
}
public MonthDay getMonthDay() {
return monthDay;
}
public void setMonthDay(MonthDay monthDay) {
this.monthDay = monthDay;
}
public List<JodaTimeBean> getChildren() {
return children;
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -18,40 +18,24 @@ package org.springframework.format.support;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.ConfigurablePropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.Formatter;
import org.springframework.format.Printer;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.datetime.joda.DateTimeParser;
import org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationFormatterFactory;
import org.springframework.format.datetime.joda.ReadablePartialPrinter;
import org.springframework.format.number.NumberStyleFormatter;
import static org.assertj.core.api.Assertions.assertThat;
@ -90,155 +74,6 @@ public class FormattingConversionServiceTests {
assertThat(i).isEqualTo(3);
}
@Test
public void formatFieldForTypeWithPrinterParserWithCoercion() {
formattingService.addConverter(new Converter<DateTime, LocalDate>() {
@Override
public LocalDate convert(DateTime source) {
return source.toLocalDate();
}
});
formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat
.shortDate()), new DateTimeParser(DateTimeFormat.shortDate()));
String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class);
assertThat(formatted).isEqualTo("10/31/09");
LocalDate date = formattingService.convert("10/31/09", LocalDate.class);
assertThat(date).isEqualTo(new LocalDate(2009, 10, 31));
}
@Test
@SuppressWarnings("resource")
public void formatFieldForValueInjection() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.registerBeanDefinition("valueBean", new RootBeanDefinition(ValueBean.class));
ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
ac.refresh();
ValueBean valueBean = ac.getBean(ValueBean.class);
assertThat(new LocalDate(valueBean.date)).isEqualTo(new LocalDate(2009, 10, 31));
}
@Test
@SuppressWarnings("resource")
public void formatFieldForValueInjectionUsingMetaAnnotations() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(MetaValueBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
ac.registerBeanDefinition("valueBean", bd);
ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
ac.registerBeanDefinition("ppc", new RootBeanDefinition(PropertyPlaceholderConfigurer.class));
ac.refresh();
System.setProperty("myDate", "10-31-09");
System.setProperty("myNumber", "99.99%");
try {
MetaValueBean valueBean = ac.getBean(MetaValueBean.class);
assertThat(new LocalDate(valueBean.date)).isEqualTo(new LocalDate(2009, 10, 31));
assertThat(valueBean.number).isEqualTo(Double.valueOf(0.9999));
}
finally {
System.clearProperty("myDate");
System.clearProperty("myNumber");
}
}
@Test
public void formatFieldForAnnotation() throws Exception {
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
doTestFormatFieldForAnnotation(Model.class, false);
}
@Test
public void formatFieldForAnnotationWithDirectFieldAccess() throws Exception {
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
doTestFormatFieldForAnnotation(Model.class, true);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholders() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
context.getBeanFactory().initializeBean(formattingService, "formattingService");
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholdersAndFactoryBean() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.registerBeanDefinition("formattingService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
formattingService = context.getBean("formattingService", FormattingConversionService.class);
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@SuppressWarnings("unchecked")
private void doTestFormatFieldForAnnotation(Class<?> modelClass, boolean directFieldAccess) throws Exception {
formattingService.addConverter(new Converter<Date, Long>() {
@Override
public Long convert(Date source) {
return source.getTime();
}
});
formattingService.addConverter(new Converter<DateTime, Date>() {
@Override
public Date convert(DateTime source) {
return source.toDate();
}
});
String formatted = (String) formattingService.convert(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime()
.toDate(), new TypeDescriptor(modelClass.getField("date")), TypeDescriptor.valueOf(String.class));
assertThat(formatted).isEqualTo("10/31/09");
LocalDate date = new LocalDate(formattingService.convert("10/31/09", TypeDescriptor.valueOf(String.class),
new TypeDescriptor(modelClass.getField("date"))));
assertThat(date).isEqualTo(new LocalDate(2009, 10, 31));
List<Date> dates = new ArrayList<>();
dates.add(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime().toDate());
dates.add(new LocalDate(2009, 11, 1).toDateTimeAtCurrentTime().toDate());
dates.add(new LocalDate(2009, 11, 2).toDateTimeAtCurrentTime().toDate());
formatted = (String) formattingService.convert(dates,
new TypeDescriptor(modelClass.getField("dates")), TypeDescriptor.valueOf(String.class));
assertThat(formatted).isEqualTo("10-31-09,11-1-09,11-2-09");
dates = (List<Date>) formattingService.convert("10-31-09,11-1-09,11-2-09",
TypeDescriptor.valueOf(String.class), new TypeDescriptor(modelClass.getField("dates")));
assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 31));
assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 11, 1));
assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 11, 2));
Object model = modelClass.newInstance();
ConfigurablePropertyAccessor accessor = directFieldAccess ? PropertyAccessorFactory.forDirectFieldAccess(model) :
PropertyAccessorFactory.forBeanPropertyAccess(model);
accessor.setConversionService(formattingService);
accessor.setPropertyValue("dates", "10-31-09,11-1-09,11-2-09");
dates = (List<Date>) accessor.getPropertyValue("dates");
assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 31));
assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 11, 1));
assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 11, 2));
if (!directFieldAccess) {
accessor.setPropertyValue("dates[0]", "10-30-09");
accessor.setPropertyValue("dates[1]", "10-1-09");
accessor.setPropertyValue("dates[2]", "10-2-09");
dates = (List<Date>) accessor.getPropertyValue("dates");
assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 30));
assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 10, 1));
assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 10, 2));
}
}
@Test
public void printNull() {
formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
@ -295,32 +130,6 @@ public class FormattingConversionServiceTests {
assertThat(formattingService.convert("", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull();
}
@Test
public void formatFieldForAnnotationWithSubclassAsFieldType() throws Exception {
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory() {
@Override
public Printer<?> getPrinter(org.springframework.format.annotation.DateTimeFormat annotation, Class<?> fieldType) {
assertThat(fieldType).isEqualTo(MyDate.class);
return super.getPrinter(annotation, fieldType);
}
});
formattingService.addConverter(new Converter<MyDate, Long>() {
@Override
public Long convert(MyDate source) {
return source.getTime();
}
});
formattingService.addConverter(new Converter<MyDate, Date>() {
@Override
public Date convert(MyDate source) {
return source;
}
});
formattingService.convert(new MyDate(), new TypeDescriptor(ModelWithSubclassField.class.getField("date")),
TypeDescriptor.valueOf(String.class));
}
@Test
public void registerDefaultValueViaFormatter() {
registerDefaultValue(Date.class, new Date());

View File

@ -26,7 +26,6 @@ import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.stream.Stream;
import org.joda.time.LocalDateTime;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@ -49,25 +48,25 @@ class CronTriggerTests {
private final Calendar calendar = new GregorianCalendar();
private void setUp(LocalDateTime localDateTime, TimeZone timeZone) {
private void setup(Date localDateTime, TimeZone timeZone) {
this.calendar.setTime(localDateTime);
this.calendar.setTimeZone(timeZone);
this.calendar.setTime(localDateTime.toDate());
roundup(this.calendar);
}
@ParameterizedCronTriggerTest
void matchAll(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void matchAll(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * * * *", timeZone);
TriggerContext context = getTriggerContext(localDateTime.toDate());
TriggerContext context = getTriggerContext(localDateTime);
assertThat(trigger.nextExecutionTime(context)).isEqualTo(this.calendar.getTime());
}
@ParameterizedCronTriggerTest
void matchLastSecond(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void matchLastSecond(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * * * *", timeZone);
GregorianCalendar calendar = new GregorianCalendar();
@ -76,8 +75,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void matchSpecificSecond(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void matchSpecificSecond(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("10 * * * * *", timeZone);
GregorianCalendar calendar = new GregorianCalendar();
@ -86,8 +85,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementSecondByOne(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementSecondByOne(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("11 * * * * *", timeZone);
this.calendar.set(Calendar.SECOND, 10);
@ -98,8 +97,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementSecondWithPreviousExecutionTooEarly(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementSecondWithPreviousExecutionTooEarly(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("11 * * * * *", timeZone);
this.calendar.set(Calendar.SECOND, 11);
@ -111,8 +110,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementSecondAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementSecondAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("10 * * * * *", timeZone);
this.calendar.set(Calendar.SECOND, 11);
@ -123,8 +122,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void secondRange(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void secondRange(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("10-15 * * * * *", timeZone);
this.calendar.set(Calendar.SECOND, 9);
@ -134,8 +133,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementMinute(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementMinute(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 * * * * *", timeZone);
this.calendar.set(Calendar.MINUTE, 10);
@ -152,8 +151,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementMinuteByOne(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementMinuteByOne(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 11 * * * *", timeZone);
this.calendar.set(Calendar.MINUTE, 10);
@ -164,8 +163,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementMinuteAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementMinuteAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 10 * * * *", timeZone);
this.calendar.set(Calendar.MINUTE, 11);
@ -177,8 +176,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementHour(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementHour(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 * * * *", timeZone);
this.calendar.set(Calendar.MONTH, 9);
@ -198,8 +197,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementHourAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementHourAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 * * * *", timeZone);
this.calendar.set(Calendar.MONTH, 9);
@ -220,8 +219,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementDayOfMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementDayOfMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 * * *", timeZone);
this.calendar.set(Calendar.DAY_OF_MONTH, 1);
@ -242,8 +241,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementDayOfMonthByOne(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementDayOfMonthByOne(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * 10 * *", timeZone);
this.calendar.set(Calendar.DAY_OF_MONTH, 9);
@ -257,8 +256,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementDayOfMonthAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementDayOfMonthAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * 10 * *", timeZone);
this.calendar.set(Calendar.DAY_OF_MONTH, 11);
@ -273,8 +272,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void dailyTriggerInShortMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dailyTriggerInShortMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 * * *", timeZone);
this.calendar.set(Calendar.MONTH, 8); // September: 30 days
@ -294,8 +293,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void dailyTriggerInLongMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dailyTriggerInLongMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 * * *", timeZone);
this.calendar.set(Calendar.MONTH, 7); // August: 31 days and not a daylight saving boundary
@ -315,8 +314,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void dailyTriggerOnDaylightSavingBoundary(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dailyTriggerOnDaylightSavingBoundary(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 * * *", timeZone);
this.calendar.set(Calendar.MONTH, 9); // October: 31 days and a daylight saving boundary in CET
@ -336,8 +335,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 1 * *", timeZone);
this.calendar.set(Calendar.MONTH, 9);
@ -357,8 +356,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementMonthAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementMonthAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 1 * *", timeZone);
this.calendar.set(Calendar.MONTH, 11);
@ -380,8 +379,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void monthlyTriggerInLongMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthlyTriggerInLongMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 31 * *", timeZone);
this.calendar.set(Calendar.MONTH, 9);
@ -396,8 +395,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void monthlyTriggerInShortMonth(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthlyTriggerInShortMonth(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 1 * *", timeZone);
this.calendar.set(Calendar.MONTH, 9);
@ -413,8 +412,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementDayOfWeekByOne(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementDayOfWeekByOne(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * * * 2", timeZone);
this.calendar.set(Calendar.DAY_OF_WEEK, 2);
@ -429,8 +428,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void incrementDayOfWeekAndRollover(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void incrementDayOfWeekAndRollover(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * * * 2", timeZone);
this.calendar.set(Calendar.DAY_OF_WEEK, 4);
@ -445,8 +444,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void specificMinuteSecond(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void specificMinuteSecond(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("55 5 * * * *", timeZone);
this.calendar.set(Calendar.MINUTE, 4);
@ -464,8 +463,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void specificHourSecond(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void specificHourSecond(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("55 * 10 * * *", timeZone);
this.calendar.set(Calendar.HOUR_OF_DAY, 9);
@ -484,8 +483,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void specificMinuteHour(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void specificMinuteHour(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* 5 10 * * *", timeZone);
this.calendar.set(Calendar.MINUTE, 4);
@ -505,8 +504,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void specificDayOfMonthSecond(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void specificDayOfMonthSecond(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("55 * * 3 * *", timeZone);
this.calendar.set(Calendar.DAY_OF_MONTH, 2);
@ -526,8 +525,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void specificDate(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void specificDate(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("* * * 3 11 *", timeZone);
this.calendar.set(Calendar.DAY_OF_MONTH, 2);
@ -548,8 +547,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void nonExistentSpecificDate(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void nonExistentSpecificDate(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
// TODO: maybe try and detect this as a special case in parser?
CronTrigger trigger = new CronTrigger("0 0 0 31 6 *", timeZone);
@ -561,8 +560,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void leapYearSpecificDate(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void leapYearSpecificDate(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 0 29 2 *", timeZone);
this.calendar.set(Calendar.YEAR, 2007);
@ -584,8 +583,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void weekDaySequence(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void weekDaySequence(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 0 7 ? * MON-FRI", timeZone);
// This is a Saturday
@ -612,8 +611,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void dayOfWeekIndifferent(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dayOfWeekIndifferent(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * 2 * *", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * 2 * ?", timeZone);
@ -621,8 +620,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void secondIncrementer(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void secondIncrementer(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("57,59 * * * * *", timeZone);
CronTrigger trigger2 = new CronTrigger("57/2 * * * * *", timeZone);
@ -630,8 +629,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void secondIncrementerWithRange(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void secondIncrementerWithRange(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("1,3,5 * * * * *", timeZone);
CronTrigger trigger2 = new CronTrigger("1-6/2 * * * * *", timeZone);
@ -639,8 +638,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void hourIncrementer(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void hourIncrementer(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * 4,8,12,16,20 * * *", timeZone);
CronTrigger trigger2 = new CronTrigger("* * 4/4 * * *", timeZone);
@ -648,8 +647,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void dayNames(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dayNames(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * * 0-6", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * * TUE,WED,THU,FRI,SAT,SUN,MON", timeZone);
@ -657,8 +656,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void sundayIsZero(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void sundayIsZero(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * * 0", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * * SUN", timeZone);
@ -666,8 +665,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void sundaySynonym(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void sundaySynonym(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * * 0", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * * 7", timeZone);
@ -675,8 +674,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void monthNames(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthNames(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * 1-12 *", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * FEB,JAN,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC *", timeZone);
@ -684,8 +683,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void monthNamesMixedCase(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthNamesMixedCase(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * 2 *", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * Feb *", timeZone);
@ -693,92 +692,92 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void secondInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void secondInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("77 * * * * *", timeZone));
}
@ParameterizedCronTriggerTest
void secondRangeInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void secondRangeInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("44-77 * * * * *", timeZone));
}
@ParameterizedCronTriggerTest
void minuteInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void minuteInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* 77 * * * *", timeZone));
}
@ParameterizedCronTriggerTest
void minuteRangeInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void minuteRangeInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* 44-77 * * * *", timeZone));
}
@ParameterizedCronTriggerTest
void hourInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void hourInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* * 27 * * *", timeZone));
}
@ParameterizedCronTriggerTest
void hourRangeInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void hourRangeInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* * 23-28 * * *", timeZone));
}
@ParameterizedCronTriggerTest
void dayInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dayInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* * * 45 * *", timeZone));
}
@ParameterizedCronTriggerTest
void dayRangeInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dayRangeInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* * * 28-45 * *", timeZone));
}
@ParameterizedCronTriggerTest
void monthInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("0 0 0 25 13 ?", timeZone));
}
@ParameterizedCronTriggerTest
void monthInvalidTooSmall(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthInvalidTooSmall(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("0 0 0 25 0 ?", timeZone));
}
@ParameterizedCronTriggerTest
void dayOfMonthInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void dayOfMonthInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("0 0 0 32 12 ?", timeZone));
}
@ParameterizedCronTriggerTest
void monthRangeInvalid(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthRangeInvalid(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
assertThatIllegalArgumentException().isThrownBy(() -> new CronTrigger("* * * * 11-13 *", timeZone));
}
@ParameterizedCronTriggerTest
void whitespace(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void whitespace(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger1 = new CronTrigger("* * * * 1 *", timeZone);
CronTrigger trigger2 = new CronTrigger("* * * * 1 *", timeZone);
@ -786,8 +785,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void monthSequence(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void monthSequence(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
CronTrigger trigger = new CronTrigger("0 30 23 30 1/3 ?", timeZone);
this.calendar.set(2010, 11, 30);
@ -813,8 +812,8 @@ class CronTriggerTests {
}
@ParameterizedCronTriggerTest
void daylightSavingMissingHour(LocalDateTime localDateTime, TimeZone timeZone) {
setUp(localDateTime, timeZone);
void daylightSavingMissingHour(Date localDateTime, TimeZone timeZone) {
setup(localDateTime, timeZone);
// This trigger has to be somewhere between 2:00 AM and 3:00 AM, so we
// use a cron expression for 2:10 AM every day.
@ -876,8 +875,8 @@ class CronTriggerTests {
static Stream<Arguments> parameters() {
return Stream.of(
arguments(LocalDateTime.now(), TimeZone.getTimeZone("PST")),
arguments(LocalDateTime.now(), TimeZone.getTimeZone("CET"))
arguments(new Date(), TimeZone.getTimeZone("PST")),
arguments(new Date(), TimeZone.getTimeZone("CET"))
);
}

View File

@ -84,8 +84,6 @@ import org.springframework.util.xml.StaxUtils;
* support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
* support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
* support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
* support for Kotlin classes and data classes</li>
* </ul>
@ -836,19 +834,6 @@ public class Jackson2ObjectMapperBuilder {
// jackson-datatype-jsr310 not available
}
// Joda-Time 2.x present?
if (ClassUtils.isPresent("org.joda.time.YearMonth", this.moduleClassLoader)) {
try {
Class<? extends Module> jodaModuleClass = (Class<? extends Module>)
ClassUtils.forName("com.fasterxml.jackson.datatype.joda.JodaModule", this.moduleClassLoader);
Module jodaModule = BeanUtils.instantiateClass(jodaModuleClass);
modulesToRegister.set(jodaModule.getTypeId(), jodaModule);
}
catch (ClassNotFoundException ex) {
// jackson-datatype-joda not available
}
}
// Kotlin present?
if (KotlinDetector.isKotlinPresent()) {
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -120,8 +120,6 @@ import org.springframework.lang.Nullable;
* support for other Java 8 types like {@link java.util.Optional}</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-jsr310">jackson-datatype-jsr310</a>:
* support for Java 8 Date & Time API types</li>
* <li><a href="https://github.com/FasterXML/jackson-datatype-joda">jackson-datatype-joda</a>:
* support for Joda-Time types</li>
* <li><a href="https://github.com/FasterXML/jackson-module-kotlin">jackson-module-kotlin</a>:
* support for Kotlin classes and data classes</li>
* </ul>

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -79,8 +79,6 @@ import com.fasterxml.jackson.dataformat.xml.XmlFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import kotlin.ranges.IntRange;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.jupiter.api.Test;
import org.springframework.beans.FatalBeanException;
@ -263,10 +261,6 @@ class Jackson2ObjectMapperBuilderTests {
void wellKnownModules() throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
Long timestamp = 1322903730000L;
DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo(timestamp.toString());
Path file = Paths.get("foo");
assertThat(new String(objectMapper.writeValueAsBytes(file), "UTF-8").endsWith("foo\"")).isTrue();
@ -278,41 +272,6 @@ class Jackson2ObjectMapperBuilderTests {
assertThat(new String(objectMapper.writeValueAsBytes(range), "UTF-8")).isEqualTo("{\"start\":1,\"end\":3}");
}
@Test // SPR-12634
void customizeWellKnownModulesWithModule()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(new CustomIntegerModule())
.build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000");
assertThat(new String(objectMapper.writeValueAsBytes(4), "UTF-8")).contains("customid");
}
@Test // SPR-12634
void customizeWellKnownModulesWithModuleClass()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modulesToInstall(CustomIntegerModule.class)
.build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000");
assertThat(new String(objectMapper.writeValueAsBytes(4), "UTF-8")).contains("customid");
}
@Test // SPR-12634
void customizeWellKnownModulesWithSerializer()
throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.serializerByType(Integer.class, new CustomIntegerSerializer()).build();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000");
assertThat(new String(objectMapper.writeValueAsBytes(4), "UTF-8")).contains("customid");
}
@Test // gh-22576
void overrideWellKnownModuleWithModule() throws IOException {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -17,7 +17,6 @@
package org.springframework.http.converter.json;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
@ -58,8 +57,6 @@ import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import com.fasterxml.jackson.databind.type.SimpleType;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.jupiter.api.Test;
import org.springframework.beans.FatalBeanException;
@ -202,41 +199,6 @@ public class Jackson2ObjectMapperFactoryBeanTests {
assertThat(serializers.findSerializer(null, SimpleType.construct(Integer.class), null)).isSameAs(serializer);
}
@Test
public void defaultModules() throws JsonProcessingException, UnsupportedEncodingException {
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
Long timestamp = 1322903730000L;
DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo(timestamp.toString());
}
@Test // SPR-12634
public void customizeDefaultModulesWithModuleClass() throws JsonProcessingException, UnsupportedEncodingException {
this.factory.setModulesToInstall(CustomIntegerModule.class);
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000");
assertThat(new String(objectMapper.writeValueAsBytes(4), "UTF-8")).contains("customid");
}
@Test // SPR-12634
public void customizeDefaultModulesWithSerializer() throws JsonProcessingException, UnsupportedEncodingException {
Map<Class<?>, JsonSerializer<?>> serializers = new HashMap<>();
serializers.put(Integer.class, new CustomIntegerSerializer());
this.factory.setSerializersByType(serializers);
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000");
assertThat(new String(objectMapper.writeValueAsBytes(4), "UTF-8")).contains("customid");
}
@Test
public void simpleSetup() {
this.factory.afterPropertiesSet();