1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.objectledge.utils;
29
30 import java.text.DateFormat;
31 import java.text.ParseException;
32 import java.text.SimpleDateFormat;
33 import java.util.Date;
34 import java.util.Locale;
35
36 import org.apache.commons.pool.BasePoolableObjectFactory;
37 import org.apache.commons.pool.ObjectPool;
38 import org.apache.commons.pool.impl.GenericObjectPool;
39
40 /***
41 * Date formatter component.
42 *
43 * @author <a href="mailto:rafal@caltha.pl">Rafal Krzewski</a>
44 * @version $Id: DateFormatter.java,v 1.2 2004/12/27 05:17:43 rafal Exp $
45 */
46 public class DateFormatter
47 {
48 private String pattern;
49
50 private Locale locale;
51
52 private ObjectPool dateFormatPool = new GenericObjectPool(new DateFormatFactory());
53
54 /***
55 * Constructs an instance of the date formatter.
56 *
57 * @param pattern the formatting pattern.
58 * @param locale the locale name.
59 */
60 public DateFormatter(String pattern, String locale)
61 {
62 this.pattern = pattern;
63 this.locale = StringUtils.getLocale(locale);
64 }
65
66 /***
67 * Format date to string according to defined pattern.
68 *
69 * @param date the date.
70 * @return the string representation of date.
71 */
72 public String format(Date date)
73 {
74 DateFormat df = getDateFormat();
75 try
76 {
77 return df.format(date);
78 }
79 finally
80 {
81 releaseDateForamt(df);
82 }
83 }
84
85 /***
86 * Parse date from string.
87 *
88 * @param source the string representation of date.
89 * @return the date.
90 * @throws ParseException if string format is invalid.
91 */
92 public Date parse(String source)
93 throws ParseException
94 {
95 DateFormat df = getDateFormat();
96 try
97 {
98 return df.parse(source);
99 }
100 finally
101 {
102 releaseDateForamt(df);
103 }
104 }
105
106 /***
107 * Acquired DateFormat object from the pool.
108 *
109 * @return DateFormat object.
110 */
111 private DateFormat getDateFormat()
112 {
113 try
114 {
115 return (DateFormat)dateFormatPool.borrowObject();
116 }
117
118 catch(Exception e)
119 {
120 throw (RuntimeException)new IllegalStateException("unexpected object pool failure").
121 initCause(e);
122 }
123
124 }
125
126 /***
127 * Releases DateFormat object into the pool.
128 *
129 * @param format DateFormat object.
130 */
131 private void releaseDateForamt(DateFormat format)
132 {
133 try
134 {
135 dateFormatPool.returnObject(format);
136 }
137
138 catch(Exception e)
139 {
140 throw (RuntimeException)new IllegalStateException("unexpected object pool failure").
141 initCause(e);
142 }
143
144 }
145
146 /***
147 * A factory of DateFormat objects.
148 */
149 private class DateFormatFactory
150 extends BasePoolableObjectFactory
151 {
152 /***
153 * {@inheritDoc}
154 */
155 public Object makeObject() throws Exception
156 {
157 return new SimpleDateFormat(pattern, locale);
158 }
159 }
160 }
161