KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > tags > html > FormatDate


1 /*
2  * Copyright 2004 The Apache Software Foundation.
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  * $Header:$
17  */

18 package org.apache.beehive.netui.tags.html;
19
20 import org.apache.beehive.netui.util.internal.InternalStringBuilder;
21
22 import org.apache.beehive.netui.util.Bundle;
23 import org.apache.beehive.netui.util.logging.Logger;
24
25 import javax.servlet.jsp.JspException JavaDoc;
26 import javax.servlet.jsp.tagext.JspTag JavaDoc;
27 import javax.servlet.jsp.tagext.SimpleTagSupport JavaDoc;
28 import java.text.DateFormat JavaDoc;
29 import java.text.ParsePosition JavaDoc;
30 import java.text.SimpleDateFormat JavaDoc;
31 import java.util.Locale JavaDoc;
32
33 //external imports
34

35 /**
36  * A formatter used to format dates. This formatter uses patterns that conform to
37  * <code>java.text.SimpleDateFormat</code> pattern syntax. Valid types for formatting are:
38  * <ul>
39  * <li>String</li>
40  * <li>java.sql.Date</li>
41  * <li>java.util.Date</li>
42  * <li>java.util.Calendar</li>
43  * </ul>
44  *
45  * <p>
46  * If the type is a String, we attempt to create a date out of the String. The
47  * String must be defined by a common format list below. If the string is
48  * equal the the empty string, it will be returned as the empty string. See
49  * java.text.SimpleDateFormat for more information.
50  * <p>
51  * The valid formats are:
52  * <ul>
53  * <li>MM/dd/yy</li>
54  * <li>yyyy-MM-dd</li>
55  * <li>MMddyy</li>
56  * <li>and the local default</li>
57  * </ul>
58  * @jsptagref.tagdescription A formatter used to format dates. This formatter uses patterns that conform to
59  * {@link java.text.SimpleDateFormat java.text.SimpleDateFormat} pattern syntax.
60  * Valid types for formatting are:
61  * <blockquote>
62  * <ul>
63  * <li>String</li>
64  * <li>java.sql.Date</li>
65  * <li>java.util.Date</li>
66  * <li>java.util.Calendar</li>
67  * </ul>
68  * </blockquote>
69  *
70  * <p>The &lt;netui:formatDate> tag formats the output of its parent tag. For example:
71  *
72  * <pre> &lt;netui:content value="${pageScope.euroDate}">
73  * &lt;netui:formatDate pattern="dd-MM-yyyy" />
74  * &lt;/netui:content></pre>
75  *
76  * <p>
77  * The following table summarizes the pattern letters that can be used.
78  * <table border=0 cellspacing=3 cellpadding=0>
79  * <tr bgcolor="#ccccff">
80  * <th align=left>Letter
81  * <th align=left>Date or Time Component
82  * <th align=left>Examples
83  * <tr>
84  * <td><code>G</code>
85  * <td>Era designator
86  * <td><code>AD</code>
87  * <tr bgcolor="#eeeeff">
88  * <td><code>y</code>
89  * <td>Year
90  * <td><code>1996</code>; <code>96</code>
91  * <tr>
92  * <td><code>M</code>
93  * <td>Month in year
94  * <td><code>July</code>; <code>Jul</code>; <code>07</code>
95  * <tr bgcolor="#eeeeff">
96  * <td><code>w</code>
97  * <td>Week in year
98  * <td><code>27</code>
99  * <tr>
100  * <td><code>W</code>
101  * <td>Week in month
102  * <td><code>2</code>
103  * <tr bgcolor="#eeeeff">
104  * <td><code>D</code>
105  * <td>Day in year
106  * <td><code>189</code>
107  * <tr>
108  * <td><code>d</code>
109  * <td>Day in month
110  * <td><code>10</code>
111  * <tr bgcolor="#eeeeff">
112  * <td><code>F</code>
113  * <td>Day of week in month
114  * <td><code>2</code>
115  * <tr>
116  * <td><code>E</code>
117  * <td>Day in week
118  * <td><code>Tuesday</code>; <code>Tue</code>
119  * <tr bgcolor="#eeeeff">
120  * <td><code>a</code>
121  * <td>Am/pm marker
122  * <td><code>PM</code>
123  * <tr>
124  * <td><code>H</code>
125  * <td>Hour in day (0-23)
126  * <td><code>0</code>
127  * <tr bgcolor="#eeeeff">
128  * <td><code>k</code>
129  * <td>Hour in day (1-24)
130  * <td><code>24</code>
131  * <tr>
132  * <td><code>K</code>
133  * <td>Hour in am/pm (0-11)
134  * <td><code>0</code>
135  * <tr bgcolor="#eeeeff">
136  * <td><code>h</code>
137  * <td>Hour in am/pm (1-12)
138  * <td><code>12</code>
139  * <tr>
140  * <td><code>m</code>
141  * <td>Minute in hour
142  * <td><code>30</code>
143  * <tr bgcolor="#eeeeff">
144  * <td><code>s</code>
145  * <td>Second in minute
146  * <td><code>55</code>
147  * <tr>
148  * <td><code>S</code>
149  * <td>Millisecond
150  * <td><code>978</code>
151  * <tr bgcolor="#eeeeff">
152  * <td><code>z</code>
153  * <td>Time zone
154  * <td><code>Pacific Standard Time</code>; <code>PST</code>; <code>GMT-08:00</code>
155  * <tr>
156  * <td><code>Z</code>
157  * <td>Time zone
158  * <td><code>-0800</code>
159  * </table>
160  * </p>
161  *
162  * The number of pattern letters used determines the final presentation. For example,
163  * yy specifies a 2 digit year, while yyyy specifies a four digit year. For detailed information see
164  * {@link java.text.SimpleDateFormat java.text.SimpleDateFormat}.
165  *
166  * <p>
167  * If the input type is a String, &lt;netui:formatDate> attempts to
168  * convert the String into a java.util.Date object before formatting.
169  * For the conversion to succeed, the
170  * String must conform to a format listed below.
171  * <p>
172  * The valid formats are:
173  * <blockquote>
174  * <ul>
175  * <li>MM/dd/yy</li>
176  * <li>yyyy-MM-dd</li>
177  * <li>MMddyy</li>
178  * <li>the local default</li>
179  * </ul>
180  * </blockquote>
181  * @example In this sample, the &lt;netui:span> tag's output will be formatted to something like 08/29/1957.
182  * <pre> &lt;netui:span value="${pageScope.today}">
183  * &lt;netui:formatDate pattern="MM/dd/yyyy" />
184  * &lt;/netui:span></pre>
185  * @netui:tag name="formatDate" body-content="empty" description="A formatter used to format dates."
186  */

187 public class FormatDate extends FormatTag
188 {
189     private static final Logger logger = Logger.getInstance(FormatDate.class);
190
191     private static final String JavaDoc[] commonFormats = {"MM/dd/yy", "yyyy-MM-dd", "MMddyy",
192                                                    null};
193
194     private String JavaDoc _stringInput;
195
196     /**
197      * Return the name of the Tag.
198      */

199     public String JavaDoc getTagName()
200     {
201         return "FormatDate";
202     }
203
204     /**
205      * Set the pattern to use to convert a String value into a date. This
206      * will be used before the common formats.
207      * @param inputPattern the pattern representing the string input
208      * @jsptagref.attributedescription The pattern used to convert a String value into a date.
209      * @jsptagref.databindable Read Only
210      * @jsptagref.attributesyntaxvalue <i>string_stringInputPattern</i>
211      * @netui:attribute required="false" rtexprvalue="true"
212      * description="The pattern used to convert a String value into a date."
213      */

214     public void setStringInputPattern(String JavaDoc inputPattern)
215             throws JspException JavaDoc
216     {
217         _stringInput = setRequiredValueAttribute(inputPattern, "stringInputPattern");
218     }
219
220     /**
221      * Create the internal Formatter instance and perform the formatting.
222      * @throws JspException if a JSP exception has occurred
223      */

224     public void doTag()
225             throws JspException JavaDoc
226     {
227         JspTag JavaDoc parentTag = SimpleTagSupport.findAncestorWithClass(this, IFormattable.class);
228
229         // if there are errors we need to either add these to the parent AbstractBastTag or report an error.
230
if (hasErrors()) {
231             if (parentTag instanceof IFormattable) {
232                 IFormattable parent = (IFormattable) parentTag;
233                 parent.formatterHasError();
234             }
235             reportErrors();
236             return;
237         }
238
239         if (parentTag instanceof IFormattable) {
240             IFormattable parent = (IFormattable) parentTag;
241             DateFormatter dateFmt = new DateFormatter();
242             dateFmt.setPattern(_pattern);
243             dateFmt.setLocale(getLocale());
244             dateFmt.setInputPattern(_stringInput);
245             parent.addFormatter(dateFmt);
246         }
247         else {
248             String JavaDoc s = Bundle.getString("Tags_FormattableParentRequired");
249             registerTagError(s, null);
250             reportErrors();
251         }
252     }
253
254     /**
255      * Internal FormatTag.Formatter which uses SimpleDateFormat.
256      */

257     public static class DateFormatter extends FormatTag.Formatter
258     {
259         private Locale JavaDoc locale;
260         private String JavaDoc inputPattern;
261
262         public void setLocale(Locale JavaDoc locale)
263         {
264             this.locale = locale;
265         }
266
267         public void setInputPattern(String JavaDoc pattern)
268         {
269             inputPattern = pattern;
270         }
271
272         public String JavaDoc format(Object JavaDoc dataToFormat) throws JspException JavaDoc
273         {
274             if (dataToFormat == null) {
275                 return null;
276             }
277             InternalStringBuilder formattedString = new InternalStringBuilder(32);
278
279             SimpleDateFormat JavaDoc dateFormat = null;
280             if (getPattern() != null) {
281                 try {
282                     if (locale != null) {
283                         dateFormat = new SimpleDateFormat JavaDoc(getPattern(), locale);
284                     }
285                     else {
286                         dateFormat = new SimpleDateFormat JavaDoc(getPattern());
287                     }
288                 }
289                 catch (IllegalArgumentException JavaDoc e) {
290                     String JavaDoc s = Bundle.getString("Tags_DateFormatPatternException", new Object JavaDoc[]{e.getMessage()});
291                     logger.warn(s);
292                     throw new JspException JavaDoc(s);
293                 }
294             }
295             else {
296                 dateFormat = new SimpleDateFormat JavaDoc();
297             }
298
299             if (dataToFormat instanceof java.sql.Date JavaDoc) {
300
301                 java.sql.Date JavaDoc date = (java.sql.Date JavaDoc) dataToFormat;
302                 formattedString.append(dateFormat.format(date));
303             }
304             else if (dataToFormat instanceof java.util.Date JavaDoc) {
305
306                 java.util.Date JavaDoc date = (java.util.Date JavaDoc) dataToFormat;
307                 formattedString.append(dateFormat.format(date));
308             }
309             else if (dataToFormat instanceof java.util.Calendar JavaDoc) {
310                 java.util.Calendar JavaDoc c = (java.util.Calendar JavaDoc) dataToFormat;
311                 java.util.Date JavaDoc date = new java.util.Date JavaDoc(c.getTimeInMillis());
312                 formattedString.append(dateFormat.format(date));
313             }
314             else if (dataToFormat instanceof String JavaDoc) {
315                 if (dataToFormat.equals("")) {
316                     return "";
317                 }
318
319                 DateFormat JavaDoc df = null;
320                 if (inputPattern != null) {
321                     try {
322                         df = new SimpleDateFormat JavaDoc(inputPattern);
323                     }
324                     catch (IllegalArgumentException JavaDoc e) {
325                         String JavaDoc s = Bundle.getString("Tags_formatDate_StringPatternError",
326                                 new Object JavaDoc[]{inputPattern, e.getMessage()});
327                         logger.warn(s);
328                         throw new JspException JavaDoc(s);
329                     }
330
331                     // let try and convert this to some type of date
332
java.util.Date JavaDoc date = df.parse((String JavaDoc) dataToFormat,
333                             new ParsePosition JavaDoc(0));
334                     if (date != null) {
335                         formattedString.append(dateFormat.format(date));
336                         return formattedString.toString();
337                     }
338                 }
339
340
341                 // this will loop through all of the formats and
342
// try to convert the date to one of them.
343
int i;
344                 for (i = 0; i < commonFormats.length; i++) {
345
346                     if (commonFormats[i] != null) {
347                         df = new SimpleDateFormat JavaDoc(commonFormats[i]);
348                     }
349                     else {
350                         df = new SimpleDateFormat JavaDoc();
351
352                     }
353
354                     // let try and convert this to some type of date
355
java.util.Date JavaDoc date = df.parse((String JavaDoc) dataToFormat,
356                             new ParsePosition JavaDoc(0));
357                     if (date != null) {
358                         formattedString.append(dateFormat.format(date));
359                         break;
360                     }
361                 }
362                 if (i == commonFormats.length) {
363                     String JavaDoc s = Bundle.getString("Tags_formatDate_String_Error",
364                             new Object JavaDoc[]{dataToFormat});
365                     logger.error(s);
366                     throw new JspException JavaDoc(s);
367                 }
368             }
369             else {
370                 String JavaDoc s = Bundle.getString("Tags_formatDate_Type_Error",
371                         new Object JavaDoc[]{dataToFormat.getClass().getName()});
372                 logger.error(s);
373                 throw new JspException JavaDoc(s);
374             }
375
376             return formattedString.toString();
377         }
378     }
379 }
380
Popular Tags