KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > myfaces > custom > date > HtmlDateRenderer


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 package org.apache.myfaces.custom.date;
17
18 import java.io.IOException JavaDoc;
19 import java.text.DateFormatSymbols JavaDoc;
20 import java.text.ParseException JavaDoc;
21 import java.util.Calendar JavaDoc;
22 import java.util.Locale JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import javax.faces.application.FacesMessage;
26 import javax.faces.component.UIComponent;
27 import javax.faces.context.FacesContext;
28 import javax.faces.context.ResponseWriter;
29 import javax.faces.convert.ConverterException;
30
31 import org.apache.myfaces.component.UserRoleUtils;
32 import org.apache.myfaces.custom.calendar.HtmlCalendarRenderer;
33 import org.apache.myfaces.custom.calendar.HtmlCalendarRenderer.CalendarDateTimeConverter;
34 import org.apache.myfaces.custom.date.HtmlInputDate.UserData;
35 import org.apache.myfaces.renderkit.RendererUtils;
36 import org.apache.myfaces.renderkit.html.HTML;
37 import org.apache.myfaces.renderkit.html.HtmlRenderer;
38 import org.apache.myfaces.renderkit.html.HtmlRendererUtils;
39 import org.apache.myfaces.util.MessageUtils;
40
41 /**
42  * $Log: HtmlDateRenderer.java,v $
43  * Revision 1.14 2004/12/27 04:11:11 mmarinschek
44  * Data Table stores the state of facets of children; script tag is rendered with type attribute instead of language attribute, popup works better as a column in a data table
45  *
46  * Revision 1.13 2004/12/24 13:21:51 matzew
47  * organized imports
48  *
49  * Revision 1.12 2004/12/10 02:15:19 svieujot
50  * New popupCalendar attribute, and implements UserRoleAware.
51  *
52  * Revision 1.11 2004/12/09 12:54:26 svieujot
53  * Changes to check for submitted-value first
54  *
55  * Revision 1.10 2004/12/09 05:13:02 svieujot
56  * Mark potential bugs where we use the backing bean's value, and do not check for submitted value
57  *
58  * Revision 1.9 2004/10/13 11:50:57 matze
59  * renamed packages to org.apache
60  *
61  * Revision 1.8 2004/10/04 17:47:55 svieujot
62  * Bugfix for bug 1039797 (Missing setter in HtmlInputDateTag), and add User Role support to InputDate.
63  *
64  * Revision 1.7 2004/07/30 13:09:04 svieujot
65  * Render numbers as 2 digits
66  *
67  * Revision 1.6 2004/07/30 02:59:00 svieujot
68  * Enable disabled attribute
69  *
70  * Revision 1.5 2004/07/26 02:00:05 svieujot
71  * Change structure to keep the data entered by the user even if they can't be converted
72  *
73  * Revision 1.4 2004/07/21 20:34:13 svieujot
74  * Add error handling
75  *
76  * Revision 1.3 2004/07/18 03:08:23 svieujot
77  * inputDate : add a type="date|time|both" similar as f:convertDateTime
78  *
79  * Revision 1.2 2004/07/17 21:03:05 svieujot
80  * Clean code
81  *
82  * Revision 1.1 2004/07/17 20:52:53 svieujot
83  * First version of an x:inputDate component
84  *
85  *
86  * @author Sylvain Vieujot (latest modification by $Author: mmarinschek $)
87  * @version $Revision: 1.14 $ $Date: 2004/12/27 04:11:11 $
88  */

89 public class HtmlDateRenderer extends HtmlRenderer {
90     /**
91      * <p>The message identifier of the {@link FacesMessage} to be created if
92      * the creditcard check fails.</p>
93      */

94     public static final String JavaDoc DATE_MESSAGE_ID = "org.apache.myfaces.Date.INVALID";
95     
96     private static final String JavaDoc ID_DAY_POSTFIX = ".day";
97     private static final String JavaDoc ID_MONTH_POSTFIX = ".month";
98     private static final String JavaDoc ID_YEAR_POSTFIX = ".year";
99     private static final String JavaDoc ID_HOURS_POSTFIX = ".hours";
100     private static final String JavaDoc ID_MINUTES_POSTFIX = ".minutes";
101     private static final String JavaDoc ID_SECONDS_POSTFIX = ".seconds";
102     
103     protected boolean isDisabled(FacesContext facesContext, UIComponent uiComponent) {
104         if( !UserRoleUtils.isEnabledOnUserRole(uiComponent) )
105             return false;
106
107         return ((HtmlInputDate)uiComponent).isDisabled();
108     }
109     
110     public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException JavaDoc {
111         RendererUtils.checkParamValidity(facesContext, uiComponent, HtmlInputDate.class);
112
113         HtmlInputDate inputDate = (HtmlInputDate) uiComponent;
114         Locale JavaDoc currentLocale = facesContext.getViewRoot().getLocale();
115         UserData userData = (UserData) inputDate.getSubmittedValue();
116         if( userData == null )
117             userData = inputDate.getUserData(currentLocale);
118         String JavaDoc type = inputDate.getType();
119         String JavaDoc clientId = uiComponent.getClientId(facesContext);
120
121         boolean disabled = isDisabled(facesContext, uiComponent);
122
123         ResponseWriter writer = facesContext.getResponseWriter();
124
125         HtmlRendererUtils.writePrettyLineSeparator(facesContext);
126
127         if( ! type.equals("time")){
128             encodeInputDay(uiComponent, writer, clientId, userData, disabled);
129             encodeInputMonth(uiComponent, writer, clientId, userData, currentLocale, disabled);
130             encodeInputYear(uiComponent, writer, clientId, userData, disabled);
131             
132             if( inputDate.isPopupCalendar() && ! disabled )
133                 encodePopupCalendarButton(facesContext, writer, clientId, currentLocale);
134         }
135         if( type.equals("both") ){
136             writer.write(" ");
137         }
138         if( ! type.equals("date")){
139             encodeInputHours(uiComponent, writer, clientId, userData, disabled);
140             writer.write(":");
141             encodeInputMinutes(uiComponent, writer, clientId, userData, disabled);
142             writer.write(":");
143             encodeInputSeconds(uiComponent, writer, clientId, userData, disabled);
144         }
145     }
146     
147     private static void encodeInputField(UIComponent uiComponent, ResponseWriter writer, String JavaDoc id, String JavaDoc value, int size, boolean disabled) throws IOException JavaDoc {
148         writer.startElement(HTML.INPUT_ELEM, uiComponent);
149         HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.UNIVERSAL_ATTRIBUTES);
150         HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.EVENT_HANDLER_ATTRIBUTES);
151         HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_ATTRIBUTES);
152
153         if (disabled) {
154             writer.writeAttribute(HTML.DISABLED_ATTR, Boolean.TRUE, null);
155         }
156
157         writer.writeAttribute(HTML.ID_ATTR, id, null);
158         writer.writeAttribute(HTML.NAME_ATTR, id, null);
159         writer.writeAttribute(HTML.SIZE_ATTR, Integer.toString(size), null);
160         writer.writeAttribute(HTML.MAXLENGTH_ATTR, Integer.toString(size), null);
161         if (value != null) {
162             writer.writeAttribute(HTML.VALUE_ATTR, value, null);
163         }
164         writer.endElement(HTML.INPUT_ELEM);
165     }
166     
167     private static void encodeInputDay(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, boolean disabled)
168             throws IOException JavaDoc {
169         encodeInputField(uiComponent, writer, clientId + ID_DAY_POSTFIX, userData.getDay(), 2, disabled);
170     }
171
172     private static void encodeInputMonth(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, Locale JavaDoc currentLocale,
173             boolean disabled) throws IOException JavaDoc {
174         writer.startElement(HTML.SELECT_ELEM, uiComponent);
175         writer.writeAttribute(HTML.ID_ATTR, clientId + ID_MONTH_POSTFIX, null);
176         writer.writeAttribute(HTML.NAME_ATTR, clientId + ID_MONTH_POSTFIX, null);
177         writer.writeAttribute(HTML.SIZE_ATTR, "1", null);
178         HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.UNIVERSAL_ATTRIBUTES);
179         HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.EVENT_HANDLER_ATTRIBUTES);
180
181         if (disabled) {
182             writer.writeAttribute(HTML.DISABLED_ATTR, Boolean.TRUE, null);
183         }
184
185         int selectedMonth = userData.getMonth() == null ? -1 : Integer.parseInt(userData.getMonth())-1;
186
187         String JavaDoc[] months = HtmlCalendarRenderer.mapMonths(new DateFormatSymbols JavaDoc(currentLocale));
188         for (int i = 0; i < months.length; i++) {
189             String JavaDoc monthName = months[i];
190             String JavaDoc monthNumber = Integer.toString(i+1);
191
192             writer.write("\t\t");
193             writer.startElement(HTML.OPTION_ELEM, null);
194             writer.writeAttribute(HTML.VALUE_ATTR, monthNumber, null);
195
196             if (i == selectedMonth)
197                 writer.writeAttribute(HTML.SELECTED_ATTR, HTML.SELECTED_ATTR, null);
198
199             writer.writeText(monthName, null);
200
201             writer.endElement(HTML.OPTION_ELEM);
202         }
203
204         // bug #970747: force separate end tag
205
writer.writeText("", null);
206         writer.endElement(HTML.SELECT_ELEM);
207     }
208
209     private static void encodeInputYear(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, boolean disabled) throws IOException JavaDoc {
210         encodeInputField(uiComponent, writer, clientId + ID_YEAR_POSTFIX, userData.getYear(), 4, disabled);
211     }
212     
213     private static void encodeInputHours(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, boolean disabled) throws IOException JavaDoc {
214         encodeInputField(uiComponent, writer, clientId + ID_HOURS_POSTFIX, userData.getHours(), 2, disabled);
215     }
216     
217     private static void encodeInputMinutes(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, boolean disabled) throws IOException JavaDoc {
218         encodeInputField(uiComponent, writer, clientId + ID_MINUTES_POSTFIX, userData.getMinutes(), 2, disabled);
219     }
220     
221     private static void encodeInputSeconds(UIComponent uiComponent, ResponseWriter writer, String JavaDoc clientId, UserData userData, boolean disabled) throws IOException JavaDoc {
222         encodeInputField(uiComponent, writer, clientId + ID_SECONDS_POSTFIX, userData.getSeconds(), 2, disabled);
223     }
224     
225     private void encodePopupCalendarButton(FacesContext facesContext, ResponseWriter writer, String JavaDoc clientId, Locale JavaDoc currentLocale) throws IOException JavaDoc{
226         HtmlCalendarRenderer.addScriptAndCSSResources(facesContext);
227         
228         DateFormatSymbols JavaDoc symbols = new DateFormatSymbols JavaDoc(currentLocale);
229
230         String JavaDoc localizedLanguageScript = HtmlCalendarRenderer.getLocalizedLanguageScript(
231                                             symbols,
232                                             HtmlCalendarRenderer.mapMonths(symbols),
233                                             Calendar.getInstance(currentLocale).getFirstDayOfWeek(),
234                                             null);
235         
236         writer.startElement(HTML.SCRIPT_ELEM,null);
237         writer.writeAttribute(HTML.SCRIPT_TYPE_ATTR,HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT,null);
238             writer.write(localizedLanguageScript);
239             //writer.write("if (!document.layers) {\n");
240
//writer.write("document.write(\"<input type='button' onclick='jscalendarPopUpCalendarForInputDate(\\\""+clientId+"\\\")' value='...'/>\");");
241
//writer.write("\n}");
242

243         writer.endElement(HTML.SCRIPT_ELEM);
244         
245         String JavaDoc dateFormat = CalendarDateTimeConverter.createJSPopupFormat(facesContext, null);
246         writer.write("<input type='button' onclick='jscalendarPopUpCalendarForInputDate(\""+clientId+"\",\""+dateFormat+"\")' value='...'/>");
247     }
248
249     public void decode(FacesContext facesContext, UIComponent uiComponent) {
250         RendererUtils.checkParamValidity(facesContext, uiComponent, HtmlInputDate.class);
251         
252         if( isDisabled(facesContext, uiComponent) ) // For safety, do not set the submited value if the component is disabled.
253
return;
254
255         HtmlInputDate inputDate = (HtmlInputDate) uiComponent;
256         Locale JavaDoc currentLocale = facesContext.getViewRoot().getLocale();
257         UserData userData = (UserData) inputDate.getSubmittedValue();
258         if( userData == null )
259             userData = inputDate.getUserData(currentLocale);
260         String JavaDoc clientId = inputDate.getClientId(facesContext);
261         String JavaDoc type = inputDate.getType();
262         Map JavaDoc requestMap = facesContext.getExternalContext().getRequestParameterMap();
263
264         if( ! type.equals( "time" ) ){
265             userData.setDay( (String JavaDoc) requestMap.get(clientId + ID_DAY_POSTFIX) );
266             userData.setMonth( (String JavaDoc) requestMap.get(clientId + ID_MONTH_POSTFIX) );
267             userData.setYear( (String JavaDoc) requestMap.get(clientId + ID_YEAR_POSTFIX) );
268         }
269         
270         if( ! type.equals( "date" ) ){
271             userData.setHours( (String JavaDoc) requestMap.get(clientId + ID_HOURS_POSTFIX) );
272             userData.setMinutes( (String JavaDoc) requestMap.get(clientId + ID_MINUTES_POSTFIX) );
273             userData.setSeconds( (String JavaDoc) requestMap.get(clientId + ID_SECONDS_POSTFIX) );
274         }
275
276         inputDate.setSubmittedValue( userData );
277     }
278     
279     public Object JavaDoc getConvertedValue(FacesContext context, UIComponent uiComponent, Object JavaDoc submittedValue) throws ConverterException {
280         UserData userData = (UserData) submittedValue;
281         try {
282             return userData.parse();
283         } catch (ParseException JavaDoc e) {
284             Object JavaDoc[] args = {uiComponent.getId()};
285             throw new ConverterException(MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR, DATE_MESSAGE_ID, args));
286         }
287     }
288 }
Popular Tags