View Javadoc

1   package de.keepondreaming.xml;
2   
3   import java.lang.reflect.Method;
4   import java.text.ParseException;
5   import java.text.SimpleDateFormat;
6   import java.util.Date;
7   import java.util.HashMap;
8   import java.util.Map;
9   
10  import de.keepondreaming.xml.util.Util;
11  
12  /***
13   * Transforms Date strings to long values
14   * 
15   * 
16   * $Author: wintermond $
17   * $Date: 2005/07/10 18:39:24 $
18   * $Log: DateHandler.java,v $
19   * Revision 1.1  2005/07/10 18:39:24  wintermond
20   * initial
21   *
22   */
23  public class DateHandler
24  {
25  	/***
26  	 * {@link SimpleDateFormat} objects are costly to create, so cache them
27  	 */
28  	private Map<String, SimpleDateFormat> dateFormatersM = new HashMap<String, SimpleDateFormat>();
29  	
30  	/***
31  	 * Needed to obtain mapping informations
32  	 */
33  	private AnnotationStrategy parserStrategyM;
34  	
35  	/***
36  	 * Default constructor
37  	 * 
38  	 * @param parserStrategy
39  	 */
40  	public DateHandler(AnnotationStrategy parserStrategy)
41  	{
42  		parserStrategyM = parserStrategy;
43  	}
44  	
45  	
46  	/***
47  	 * Creates a {@link java.util.Date}, {@link java.sql.Date} or {@link java.sql.Timestamp} object
48  	 * based upon the <code>value</code>
49  	 * 
50  	 * @param method
51  	 * @param value
52  	 * 
53  	 * @return a {@link java.util.Date}, {@link java.sql.Date} or {@link java.sql.Timestamp} object
54  	 */
55  	public Date getDateString(Method method, String value) throws ParseException
56  	{
57  		Date result = null;
58  		String formatString = parserStrategyM.getDateFormatPattern(method);
59  		if(formatString != null)
60  		{
61  			formatString = formatString.trim();
62  			SimpleDateFormat formater = dateFormatersM.get(formatString);
63  			if(formater == null)
64  			{
65  				formater = new SimpleDateFormat(formatString);
66  				dateFormatersM.put(formatString, formater);				
67  				try
68  				{
69  					long valueAsLong = formater.parse(value).getTime();
70  					result = (Date) Util.createObject(method.getReturnType(), String.valueOf(valueAsLong));
71  				}
72  				catch (ParseException e)
73  				{
74  					System.err.println("Error while applying pattern [" + formatString + "] on value [" + value + "]");
75  					throw e;
76  				}
77  				
78  			}
79  		}
80  		else
81  		{
82  			result = (Date) Util.createObject(method.getReturnType(), value);
83  		}
84  		
85  		return result;
86  	}
87  }