View Javadoc
1   /*
2    * Copyright 2012 Olivier Godineau
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at http://www.apache.org/licenses/LICENSE-2.0
7    * 
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11   * License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  package olg.csv.bean.formatter;
15  
16  import java.util.Date;
17  import java.util.Locale;
18  
19  /**
20   * Allows to represent an object as a String.
21   * 
22   * @author Olivier Godineau
23   * 
24   * @param <T>
25   *            the class the formatter is responsible to transform.
26   */
27  public class Formatter<T> {
28  
29  	/**
30  	 * Default implementation based on toString Method of the given t.
31  	 * 
32  	 * @param t
33  	 *            the value to format.
34  	 * @return the formatted value.
35  	 */
36  	public String toString(T t) { // NOPMD by olivier on 28/01/12 14:10
37  		return (t == null ? null : t.toString());
38  
39  	}
40  
41  	/**
42  	 * Returns a new instance of a formatter specialized in formatting Date as
43  	 * String.
44  	 * 
45  	 * @param pattern
46  	 *            pattern. Must be a not null and valid Date pattern.
47  	 * @param locale
48  	 *            the locale to used in date formatting.
49  	 * @return the Date formatter.
50  	 */
51  	public static Formatter<Date> getDateFormatter(String pattern, Locale locale) {
52  		if (pattern == null) {
53  			throw new IllegalArgumentException("Formatter#getDateFormatter pattern argument must be not null");
54  		}
55  		if (locale == null) {
56  			return new DateFormatter(pattern);
57  		} else {
58  			return new DateFormatter(pattern, locale);
59  		}
60  	}
61  }