KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > widgets > CmsCalendarWidget


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/widgets/CmsCalendarWidget.java,v $
3  * Date : $Date: 2006/09/22 15:17:03 $
4  * Version: $Revision: 1.14 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.widgets;
33
34 import org.opencms.file.CmsObject;
35 import org.opencms.i18n.CmsMessages;
36 import org.opencms.main.CmsLog;
37 import org.opencms.util.CmsStringUtil;
38 import org.opencms.workplace.CmsWorkplace;
39
40 import java.text.DateFormat JavaDoc;
41 import java.text.ParseException JavaDoc;
42 import java.text.SimpleDateFormat JavaDoc;
43 import java.util.GregorianCalendar JavaDoc;
44 import java.util.Locale JavaDoc;
45 import java.util.Map JavaDoc;
46 import java.util.TimeZone JavaDoc;
47
48 import org.apache.commons.logging.Log;
49
50 /**
51  * Provides a DHTML calendar widget, for use on a widget dialog.<p>
52  *
53  * @author Alexander Kandzior
54  *
55  * @version $Revision: 1.14 $
56  *
57  * @since 6.0.0
58  */

59 public class CmsCalendarWidget extends A_CmsWidget {
60
61     /** The log object for this class. */
62     private static final Log LOG = CmsLog.getLog(CmsCalendarWidget.class);
63
64     /**
65      * Creates a new calendar widget.<p>
66      */

67     public CmsCalendarWidget() {
68
69         // empty constructor is required for class registration
70
this("");
71     }
72
73     /**
74      * Creates a new calendar widget with the given configuration.<p>
75      *
76      * @param configuration the configuration to use
77      */

78     public CmsCalendarWidget(String JavaDoc configuration) {
79
80         super(configuration);
81     }
82
83     /**
84      * Creates the HTML JavaScript and stylesheet includes required by the calendar for the head of the page.<p>
85      *
86      * The default <code>"opencms"</code> style is used.<p>
87      *
88      * @param locale the locale to use for the calendar
89      *
90      * @return the necessary HTML code for the js and stylesheet includes
91      *
92      * @see #calendarIncludes(Locale, String)
93      */

94     public static String JavaDoc calendarIncludes(Locale JavaDoc locale) {
95
96         return calendarIncludes(locale, "opencms");
97     }
98
99     /**
100      * Creates the HTML JavaScript and stylesheet includes required by the calendar for the head of the page.<p>
101      *
102      * @param locale the locale to use for the calendar
103      * @param style the name of the used calendar style, e.g. "system", "blue"
104      *
105      * @return the necessary HTML code for the js and stylesheet includes
106      */

107     public static String JavaDoc calendarIncludes(Locale JavaDoc locale, String JavaDoc style) {
108
109         StringBuffer JavaDoc result = new StringBuffer JavaDoc(512);
110         String JavaDoc calendarPath = CmsWorkplace.getSkinUri() + "components/js_calendar/";
111         if (CmsStringUtil.isEmpty(style)) {
112             style = "system";
113         }
114         result.append("<link rel=\"stylesheet\" type=\"text/css\" HREF=\"");
115         result.append(calendarPath);
116         result.append("calendar-");
117         result.append(style);
118         result.append(".css\">\n");
119         result.append("<script type=\"text/javascript\" SRC=\"");
120         result.append(calendarPath);
121         result.append("calendar.js\"></script>\n");
122         result.append("<script type=\"text/javascript\" SRC=\"");
123         result.append(calendarPath);
124         result.append("lang/calendar-");
125         result.append(locale.getLanguage());
126         result.append(".js\"></script>\n");
127         result.append("<script type=\"text/javascript\" SRC=\"");
128         result.append(calendarPath);
129         result.append("calendar-setup.js\"></script>\n");
130         return result.toString();
131     }
132
133     /**
134      * Generates the HTML to initialize the JavaScript calendar element on the end of a page.<p>
135      *
136      * This method must be called at the end of a HTML page, e.g. before the closing &lt;body&gt; tag.<p>
137      *
138      * @param messages the messages to use (for date and time formats)
139      * @param inputFieldId the ID of the input field where the date is pasted to
140      * @param triggerButtonId the ID of the button which triggers the calendar
141      * @param align initial position of the calendar popup element
142      * @param singleClick if true, a single click selects a date and closes the calendar, otherwise calendar is closed by doubleclick
143      * @param weekNumbers show the week numbers in the calendar or not
144      * @param mondayFirst show monday as first day of week
145      * @param dateStatusFunc name of the function which determines if/how a date should be disabled
146      * @param showTime true if the time selector should be shown, otherwise false
147      * @return the HTML code to initialize a calendar poup element
148      */

149     public static String JavaDoc calendarInit(
150         CmsMessages messages,
151         String JavaDoc inputFieldId,
152         String JavaDoc triggerButtonId,
153         String JavaDoc align,
154         boolean singleClick,
155         boolean weekNumbers,
156         boolean mondayFirst,
157         String JavaDoc dateStatusFunc,
158         boolean showTime) {
159
160         StringBuffer JavaDoc result = new StringBuffer JavaDoc(512);
161         if (CmsStringUtil.isEmpty(align)) {
162             align = "Bc";
163         }
164         result.append("<script type=\"text/javascript\">\n");
165         result.append("<!--\n");
166         result.append("\tCalendar.setup({\n");
167         result.append("\t\tinputField : \"");
168         result.append(inputFieldId);
169         result.append("\",\n");
170         result.append("\t\tifFormat : \"");
171         result.append(messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_DATE_FORMAT_0));
172         if (showTime) {
173             result.append(" ");
174             result.append(messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIME_FORMAT_0));
175         }
176         result.append("\",\n");
177         result.append("\t\tbutton : \"");
178         result.append(triggerButtonId);
179         result.append("\",\n");
180         result.append("\t\talign : \"");
181         result.append(align);
182         result.append("\",\n");
183         result.append("\t\tsingleClick : ");
184         result.append(singleClick);
185         result.append(",\n");
186         result.append("\t\tweekNumbers : ");
187         result.append(weekNumbers);
188         result.append(",\n");
189         result.append("\t\tmondayFirst : ");
190         result.append(mondayFirst);
191         result.append(",\n");
192         result.append("\t\tshowsTime : " + showTime);
193         if (showTime
194             && (messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIMEFORMAT_0).toLowerCase().indexOf("p") != -1)) {
195             result.append(",\n\t\ttimeFormat : \"12\"");
196         }
197         if (CmsStringUtil.isNotEmpty(dateStatusFunc)) {
198             result.append(",\n\t\tdateStatusFunc : ");
199             result.append(dateStatusFunc);
200         }
201         result.append("\n\t});\n");
202
203         result.append("//-->\n");
204         result.append("</script>\n");
205         return result.toString();
206     }
207
208     /**
209      * Creates the time in milliseconds from the given parameter.<p>
210      *
211      * @param messages the messages that contain the time format definitions
212      * @param dateString the String representation of the date
213      * @param useTime true if the time should be parsed, too, otherwise false
214      *
215      * @return the time in milliseconds
216      *
217      * @throws ParseException if something goes wrong
218      */

219     public static long getCalendarDate(CmsMessages messages, String JavaDoc dateString, boolean useTime) throws ParseException JavaDoc {
220
221         long dateLong = 0;
222
223         // substitute some chars because calendar syntax != DateFormat syntax
224
String JavaDoc dateFormat = messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_DATE_FORMAT_0);
225         if (useTime) {
226             dateFormat += " " + messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIME_FORMAT_0);
227         }
228         dateFormat = CmsCalendarWidget.getCalendarJavaDateFormat(dateFormat);
229
230         SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc(dateFormat);
231         dateLong = df.parse(dateString).getTime();
232         return dateLong;
233     }
234
235     /**
236      * Parses the JavaScript calendar date format to the java patterns of SimpleDateFormat.<p>
237      *
238      * @param dateFormat the dateformat String of the JS calendar
239      * @return the parsed SimpleDateFormat pattern String
240      */

241     public static String JavaDoc getCalendarJavaDateFormat(String JavaDoc dateFormat) {
242
243         dateFormat = CmsStringUtil.substitute(dateFormat, "%", ""); // remove all "%"
244
dateFormat = CmsStringUtil.substitute(dateFormat, "m", "${month}");
245         dateFormat = CmsStringUtil.substitute(dateFormat, "H", "${hour}");
246         dateFormat = CmsStringUtil.substitute(dateFormat, "Y", "${4anno}");
247         dateFormat = dateFormat.toLowerCase();
248         dateFormat = CmsStringUtil.substitute(dateFormat, "${month}", "M");
249         dateFormat = CmsStringUtil.substitute(dateFormat, "${hour}", "H");
250         dateFormat = CmsStringUtil.substitute(dateFormat, "y", "yy");
251         dateFormat = CmsStringUtil.substitute(dateFormat, "${4anno}", "yyyy");
252         dateFormat = CmsStringUtil.substitute(dateFormat, "m", "mm"); // minutes with two digits
253
dateFormat = dateFormat.replace('e', 'd'); // day of month
254
dateFormat = dateFormat.replace('i', 'h'); // 12 hour format
255
dateFormat = dateFormat.replace('p', 'a'); // pm/am String
256
return dateFormat;
257     }
258
259     /**
260      * Returns the given timestamp as String formatted in a localized pattern.<p>
261      *
262      * @param locale the locale for the time format
263      * @param messages the messages that contain the time format definitions
264      * @param timestamp the time to format
265      *
266      * @return the given timestamp as String formatted in a localized pattern
267      */

268     public static String JavaDoc getCalendarLocalizedTime(Locale JavaDoc locale, CmsMessages messages, long timestamp) {
269
270         // get the current date & time
271
TimeZone JavaDoc zone = TimeZone.getDefault();
272         GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc(zone, locale);
273         cal.setTimeInMillis(timestamp);
274         // format it nicely according to the localized pattern
275
DateFormat JavaDoc df = new SimpleDateFormat JavaDoc(
276             CmsCalendarWidget.getCalendarJavaDateFormat(messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_DATE_FORMAT_0)
277                 + " "
278                 + messages.key(org.opencms.workplace.Messages.GUI_CALENDAR_TIME_FORMAT_0)));
279         return df.format(cal.getTime());
280     }
281
282     /**
283      * @see org.opencms.widgets.I_CmsWidget#getDialogIncludes(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog)
284      */

285     public String JavaDoc getDialogIncludes(CmsObject cms, I_CmsWidgetDialog widgetDialog) {
286
287         return calendarIncludes(widgetDialog.getLocale());
288     }
289
290     public String JavaDoc getWidgetStringValue(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
291
292         String JavaDoc result = param.getStringValue(cms);
293         if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(result) && !"0".equals(result)) {
294             try {
295                 result = getCalendarLocalizedTime(
296                     widgetDialog.getLocale(),
297                     widgetDialog.getMessages(),
298                     Long.parseLong(result));
299             } catch (NumberFormatException JavaDoc e) {
300                 result = "";
301             }
302         } else {
303             result = "";
304         }
305         return result;
306     }
307
308     /**
309      * @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
310      */

311     public String JavaDoc getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
312
313         StringBuffer JavaDoc result = new StringBuffer JavaDoc(16);
314         result.append("<td class=\"xmlTd\">");
315         result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>");
316         result.append("<input class=\"xmlInputSmall");
317         if (param.hasError()) {
318             result.append(" xmlInputError");
319         }
320         result.append("\" value=\"");
321         String JavaDoc dateTimeValue = getWidgetStringValue(cms, widgetDialog, param);
322         result.append(dateTimeValue);
323         String JavaDoc id = param.getId();
324         result.append("\" name=\"");
325         result.append(id);
326         result.append("\" id=\"");
327         result.append(id);
328         result.append("\"></td>");
329         result.append(widgetDialog.dialogHorizontalSpacer(10));
330         result.append("<td>");
331         result.append("<table class=\"editorbuttonbackground\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"");
332         result.append(id);
333         result.append(".calendar\"><tr>");
334         result.append(widgetDialog.button(
335             "#",
336             null,
337             "calendar",
338             org.opencms.workplace.Messages.GUI_CALENDAR_CHOOSE_DATE_0,
339             widgetDialog.getButtonStyle()));
340         result.append("</tr></table>");
341         result.append("</td></tr></table>");
342
343         result.append(calendarInit(
344             widgetDialog.getMessages(),
345             id,
346             id + ".calendar",
347             "cR",
348             false,
349             false,
350             true,
351             null,
352             true));
353
354         result.append("</td>");
355
356         return result.toString();
357     }
358
359     /**
360      * @see org.opencms.widgets.I_CmsWidget#newInstance()
361      */

362     public I_CmsWidget newInstance() {
363
364         return new CmsCalendarWidget(getConfiguration());
365     }
366
367     /**
368      * @see org.opencms.widgets.I_CmsWidget#setEditorValue(org.opencms.file.CmsObject, java.util.Map, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
369      */

370     public void setEditorValue(
371         CmsObject cms,
372         Map JavaDoc formParameters,
373         I_CmsWidgetDialog widgetDialog,
374         I_CmsWidgetParameter param) {
375
376         String JavaDoc[] values = (String JavaDoc[])formParameters.get(param.getId());
377         if ((values != null) && (values.length > 0)) {
378             long dateTime;
379             try {
380                 dateTime = Long.valueOf(param.getStringValue(cms)).longValue();
381             } catch (NumberFormatException JavaDoc e) {
382                 dateTime = 0;
383             }
384             String JavaDoc dateTimeValue = values[0].trim();
385             if (CmsStringUtil.isNotEmpty(dateTimeValue)) {
386                 try {
387                     dateTime = getCalendarDate(widgetDialog.getMessages(), dateTimeValue, true);
388                 } catch (ParseException JavaDoc e) {
389                     // TODO: Better exception handling
390
if (LOG.isWarnEnabled()) {
391                         LOG.warn(Messages.get().getBundle().key(Messages.ERR_PARSE_DATETIME_1, dateTimeValue), e);
392                     }
393                 }
394             } else {
395                 dateTime = 0;
396             }
397             param.setStringValue(cms, String.valueOf(dateTime));
398         }
399     }
400 }
Popular Tags