View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.format.datetime;
18  
19  import java.util.Calendar;
20  import java.util.Collections;
21  import java.util.Date;
22  import java.util.HashSet;
23  import java.util.Set;
24  
25  import org.springframework.context.support.EmbeddedValueResolutionSupport;
26  import org.springframework.format.AnnotationFormatterFactory;
27  import org.springframework.format.Formatter;
28  import org.springframework.format.Parser;
29  import org.springframework.format.Printer;
30  import org.springframework.format.annotation.DateTimeFormat;
31  
32  /**
33   * Formats fields annotated with the {@link DateTimeFormat} annotation using
34   * a {@link DateFormatter}.
35   *
36   * @author Phillip Webb
37   * @since 3.2
38   * @see org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationFormatterFactory
39   */
40  public class DateTimeFormatAnnotationFormatterFactory  extends EmbeddedValueResolutionSupport
41  		implements AnnotationFormatterFactory<DateTimeFormat> {
42  
43  
44  	private static final Set<Class<?>> FIELD_TYPES;
45  
46  	static {
47  		Set<Class<?>> fieldTypes = new HashSet<Class<?>>(4);
48  		fieldTypes.add(Date.class);
49  		fieldTypes.add(Calendar.class);
50  		fieldTypes.add(Long.class);
51  		FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
52  	}
53  
54  
55  	@Override
56  	public Set<Class<?>> getFieldTypes() {
57  		return FIELD_TYPES;
58  	}
59  
60  	@Override
61  	public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
62  		return getFormatter(annotation, fieldType);
63  	}
64  
65  	@Override
66  	public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) {
67  		return getFormatter(annotation, fieldType);
68  	}
69  
70  	protected Formatter<Date> getFormatter(DateTimeFormat annotation, Class<?> fieldType) {
71  		DateFormatter formatter = new DateFormatter();
72  		formatter.setStylePattern(resolveEmbeddedValue(annotation.style()));
73  		formatter.setIso(annotation.iso());
74  		formatter.setPattern(resolveEmbeddedValue(annotation.pattern()));
75  		return formatter;
76  	}
77  
78  }