001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.format.datetime; 018 019import java.util.Calendar; 020import java.util.Collections; 021import java.util.Date; 022import java.util.HashSet; 023import java.util.Set; 024 025import org.springframework.context.support.EmbeddedValueResolutionSupport; 026import org.springframework.format.AnnotationFormatterFactory; 027import org.springframework.format.Formatter; 028import org.springframework.format.Parser; 029import org.springframework.format.Printer; 030import org.springframework.format.annotation.DateTimeFormat; 031import org.springframework.util.StringUtils; 032 033/** 034 * Formats fields annotated with the {@link DateTimeFormat} annotation using a {@link DateFormatter}. 035 * 036 * @author Phillip Webb 037 * @since 3.2 038 * @see org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationFormatterFactory 039 */ 040public class DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport 041 implements AnnotationFormatterFactory<DateTimeFormat> { 042 043 private static final Set<Class<?>> FIELD_TYPES; 044 045 static { 046 Set<Class<?>> fieldTypes = new HashSet<>(4); 047 fieldTypes.add(Date.class); 048 fieldTypes.add(Calendar.class); 049 fieldTypes.add(Long.class); 050 FIELD_TYPES = Collections.unmodifiableSet(fieldTypes); 051 } 052 053 054 @Override 055 public Set<Class<?>> getFieldTypes() { 056 return FIELD_TYPES; 057 } 058 059 @Override 060 public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) { 061 return getFormatter(annotation, fieldType); 062 } 063 064 @Override 065 public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) { 066 return getFormatter(annotation, fieldType); 067 } 068 069 protected Formatter<Date> getFormatter(DateTimeFormat annotation, Class<?> fieldType) { 070 DateFormatter formatter = new DateFormatter(); 071 String style = resolveEmbeddedValue(annotation.style()); 072 if (StringUtils.hasLength(style)) { 073 formatter.setStylePattern(style); 074 } 075 formatter.setIso(annotation.iso()); 076 String pattern = resolveEmbeddedValue(annotation.pattern()); 077 if (StringUtils.hasLength(pattern)) { 078 formatter.setPattern(pattern); 079 } 080 return formatter; 081 } 082 083}