View Javadoc

1   /*
2    * This software was designed and created by Jason Carroll.
3    * Copyright (c) 2002, 2003, 2004 Jason Carroll.
4    * The author can be reached at jcarroll@cowsultants.com
5    * ITracker website: http://www.cowsultants.com
6    * ITracker forums: http://www.cowsultants.com/phpBB/index.php
7    *
8    * This program is free software; you can redistribute it and/or modify
9    * it only under the terms of the GNU General Public License as published by
10   * the Free Software Foundation; either version 2 of the License, or
11   * (at your option) any later version.
12   *
13   * This program is distributed in the hope that it will be useful,
14   * but WITHOUT ANY WARRANTY; without even the implied warranty of
15   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   * GNU General Public License for more details.
17   */
18  
19  package org.itracker.web.taglib;
20  
21  import java.text.DateFormat;
22  import java.text.ParseException;
23  import java.text.SimpleDateFormat;
24  import java.util.Calendar;
25  import java.util.Date;
26  import java.util.GregorianCalendar;
27  import java.util.HashMap;
28  import java.util.List;
29  import java.util.Locale;
30  import java.util.Map;
31  import java.util.ResourceBundle;
32  
33  import javax.servlet.http.HttpServletRequest;
34  import javax.servlet.jsp.JspException;
35  import javax.servlet.jsp.tagext.TagSupport;
36  
37  import org.apache.log4j.Logger;
38  import org.apache.struts.taglib.TagUtils;
39  import org.itracker.core.resources.ITrackerResources;
40  import org.itracker.model.CustomField;
41  import org.itracker.model.CustomFieldValue;
42  import org.itracker.model.NameValuePair;
43  import org.itracker.services.util.CustomFieldUtilities;
44  import org.itracker.services.util.HTMLUtilities;
45  import org.itracker.web.util.LoginUtilities;
46  import org.itracker.web.util.ServletContextUtils;
47  
48  public final class FormatCustomFieldTag extends TagSupport {
49  	/**
50       *
51       */
52  	private static final long serialVersionUID = 1L;
53  	public static final String DISPLAY_TYPE_EDIT = "edit";
54  	public static final String DISPLAY_TYPE_VIEW = "view";
55  
56  	private static final Logger logger = Logger
57  			.getLogger(FormatCustomFieldTag.class);
58  
59  	private CustomField field;
60  	private String currentValue;
61  	private String displayType;
62  	private String formName;
63  	private Map<Integer, List<NameValuePair>> listOptions;
64  
65  	public CustomField getField() {
66  		return field;
67  	}
68  
69  	public void setField(CustomField value) {
70  		field = value;
71  	}
72  
73  	public String getCurrentValue() {
74  		return currentValue;
75  	}
76  
77  	public void setCurrentValue(String value) {
78  		currentValue = value;
79  	}
80  
81  	public String getDisplayType() {
82  		return displayType;
83  	}
84  
85  	public void setDisplayType(String value) {
86  		displayType = value;
87  	}
88  
89  	public String getFormName() {
90  		return formName;
91  	}
92  
93  	public void setFormName(String value) {
94  		formName = value;
95  	}
96  
97  	public Map<Integer, List<NameValuePair>> getListOptions() {
98  		return (listOptions == null ? new HashMap<Integer, List<NameValuePair>>()
99  				: listOptions);
100 	}
101 
102 	public void setListOptions(Map<Integer, List<NameValuePair>> value) {
103 		listOptions = value;
104 	}
105 
106 	public int doStartTag() throws JspException {
107 		return SKIP_BODY;
108 	}
109 
110 	public int doEndTag() throws JspException {
111 		Locale locale = null;
112 
113 		if (field != null) {
114 			locale = LoginUtilities
115 					.getCurrentLocale((HttpServletRequest) pageContext
116 							.getRequest());
117 
118 			StringBuffer buf = new StringBuffer();
119 			buf
120 					.append("<td class=\""
121 							+ (DISPLAY_TYPE_VIEW.equalsIgnoreCase(displayType) ? "editColumnTitle"
122 									: "editColumnTitle") + "\">");
123 			buf.append(CustomFieldUtilities.getCustomFieldName(field.getId(),
124 					locale)
125 					+ ": ");
126 			buf.append("</td>\n");
127 			buf.append("<td align=\"left\" class=\"editColumnText\">");
128 			if (DISPLAY_TYPE_VIEW.equalsIgnoreCase(displayType)) {
129 				if (currentValue != null) {
130 					// buf.append((field.getFieldType() == CustomField.Type.LIST
131 					// ? field.getOptionNameByValue(currentValue) :
132 					// currentValue));
133 
134 					if (field.getFieldType() == CustomField.Type.LIST) {
135 						buf.append(CustomFieldUtilities
136 								.getCustomFieldOptionName(getField(),
137 										currentValue, locale));
138 
139 					} else {
140 
141 						buf.append(currentValue);
142 					}
143 				}
144 			} else {
145 				// Object requestValue = RequestUtils.lookup(pageContext,
146 				// org.apache.struts.taglib.html.Constants.BEAN_KEY,
147 				// "customFields(" + field.getId() + ")", null);
148 				Object requestValue = TagUtils.getInstance().lookup(
149 						pageContext,
150 						org.apache.struts.taglib.html.Constants.BEAN_KEY,
151 						"customFields(" + field.getId() + ")", null);
152 				if (currentValue == null && requestValue != null) {
153 					currentValue = requestValue.toString();
154 				}
155 
156 				if (field.getFieldType() == CustomField.Type.LIST) {
157 					List<CustomFieldValue> options = field.getOptions();
158 					// WorkflowUtilities.getListOptions(getListOptions(),
159 					// field.getId());
160 
161 					buf.append("<select name=\"customFields(").append(
162 							field.getId()).append(
163 							")\" class=\"editColumnText\">\n");
164 					for (int i = 0; i < options.size(); i++) {
165 						// TODO: why not work with option-id here? if value
166 						// contains quotes, problem.
167 						buf.append("<option value=\"").append(
168 								HTMLUtilities.escapeTags(options.get(i)
169 										.getValue())).append("\"");
170 						if (currentValue != null
171 								&& currentValue.equals(options.get(i)
172 										.getValue())) {
173 							buf.append(" selected=\"selected\"");
174 						}
175 						buf.append(" class=\"editColumnText\">");
176 						buf.append(CustomFieldUtilities
177 								.getCustomFieldOptionName(options.get(i),
178 										locale));
179 						// buf.append(options.get(i).getName());
180 						buf.append("</option>\n");
181 					}
182 					buf.append("</select>\n");
183 					
184 					
185 					
186 				} else if (field.getFieldType() == CustomField.Type.DATE) {
187 					String df = ITrackerResources.getString(
188 							"itracker.dateformat.dateonly", locale);
189 					if (field.getDateFormat().equals("full")) {
190 						df = ITrackerResources.getString(
191 								"itracker.dateformat.full", locale);
192 					}
193 					
194 					String fieldName = "customFields(" + field.getId() + ")";
195 					String cf = "cf" + field.getId();
196 					buf.append("<input type=\"text\" name=\"")
197 							.append(fieldName).append("\" id=\"")
198 							.append(fieldName).append("\"");
199 					buf.append((currentValue != null
200 							&& !currentValue.equals("") ? " value=\""
201 							+ currentValue + "\"" : ""));
202 //					buf.append(" onchange=\"onDateChange(this, " + cf + ")\"");
203 					buf.append(" class=\"editColumnText\" />&nbsp;");
204 					buf.append("<img onmouseup=\"toggleCalendar(" + cf + ")\"");
205 					buf.append("id=\"").append(cf).append(
206 							"Pos\" name=\"").append(cf).append(
207 							"Pos\" width=\"19\" height=\"19\" src=\"");
208 					buf.append(ServletContextUtils.getItrackerServices()
209 							.getConfigurationService().getSystemBaseURL());
210 					buf.append("/themes/defaulttheme/images/calendar.gif");
211 					buf.append("\" align=\"top\" border=\"0\" />");
212 					buf.append("<div class=\"scal tinyscal\" id=\"").append(cf).append(
213 							"\"></div>");
214 					
215 					SimpleDateFormat monthDf = new SimpleDateFormat("MMMMM", locale);
216 					SimpleDateFormat dayDf = new SimpleDateFormat("E", locale);
217 					Calendar cal = new GregorianCalendar(locale);
218 					cal.set(Calendar.MONTH, 0);
219 					cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
220 					
221 					Date date = null;
222 					try  {
223 						DateFormat df1 = new SimpleDateFormat(df);
224 						date = df1.parse(currentValue);
225 					} catch (ParseException e) {
226 						
227 					} catch (RuntimeException e) {
228 						
229 					}
230 
231 					buf.append("    <script type=\"text/javascript\" language=\"javascript\">");
232 					buf.append("    /* <![CDATA[*/\n");
233 					buf.append("Object.extend(Date.prototype, {");
234 					buf.append("monthnames: [\"");
235 					for (int i = 0; i < 12; i++) {
236 						cal.set(Calendar.MONTH, i);
237 						buf.append(monthDf.format(cal.getTime()));
238 						if (i == 11) {
239 							buf.append("\"]");
240 						} else {
241 							buf.append("\",\n \"");
242 						}
243 					}
244 					buf.append(",\n");
245 					buf.append("daynames: [\"");
246 					for (int i = 1; i < 8; i++) {
247 						cal.set(Calendar.DAY_OF_WEEK, i);
248 						buf.append(dayDf.format(cal.getTime()));
249 						if (i == 7) {
250 							buf.append("\"]");
251 						} else {
252 							buf.append("\",\n \"");
253 						}
254 					}
255 					buf.append("});\n");
256 
257 					buf.append("        var options = Object.extend({\n");
258 					buf.append("            titleformat:'mmmm yyyy',\n");
259 //					buf.append("            updateformat:'mm/dd/yyyy',\n");
260 					buf.append("            updateformat:'" + HTMLUtilities.getJSDateFormat(df) + "',\n");
261 					buf.append("            dayheadlength:2,\n");
262 					buf.append("            weekdaystart:1,\n");
263 					buf.append("            tabular: true,\n");
264 					buf.append("            closebutton:'x',\n");
265 					buf.append("            planner: false,\n");
266 //					custom expanded option
267 					buf.append("            expanded: false\n");
268 					buf.append("        });\n");
269 //					buf.append("\nvar updateyear = function(d){ $('"+ fieldName + "').value = d.format('" + HTMLUtilities.getJSDateFormat(df) + "'); };");
270 					buf.append("\nvar " + cf + " = new scal('" + cf + "', '"+ fieldName + "', options);");
271 					
272 					if (null != date) {
273 						Calendar cal1 = GregorianCalendar.getInstance();
274 						cal1.setTime(date);
275 						buf.append("\n " + cf + ".setCurrentDate(new Date(" + cal1.get(Calendar.YEAR) + ", " + cal1.get(Calendar.MONTH) + ", " + cal1.get(Calendar.DAY_OF_MONTH) + "));");
276 					}
277 					
278 //					buf.append("\n$('" + cf + "').cf=" + cf + ";");
279 					buf.append("// ]]>");
280 					buf.append("</script>");
281 
282 //					// try {
283 //					// buf.append(RequestUtils.computeURL(pageContext, null,
284 //					// null, "/images/calendar.gif", null, null, null, false));
285 //					buf.append(ServletContextUtils.getItrackerServices()
286 //							.getConfigurationService().getSystemBaseURL());
287 //					buf.append("/themes/defaulttheme/images/calendar.gif");
288 //					// buf.append(TagUtils.getInstance().computeURL(pageContext,
289 //					// null, null, "/images/calendar.gif", null, null, null,
290 //					// null, false));
291 //
292 //					// } catch(MalformedURLException murle) {
293 //					// buf.append("images/calendar.gif");
294 //					// }
295 
296 				} else {
297 					buf.append("<input type=\"text\" name=\"customFields(")
298 							.append(field.getId()).append(")\"");
299 					buf.append((currentValue != null
300 							&& !currentValue.equals("") ? " value=\""
301 							+ currentValue + "\"" : ""));
302 					buf.append(" class=\"editColumnText\">");
303 				}
304 			}
305 			buf.append("</td>\n");
306 
307 			// ResponseUtils.write(pageContext, buf.toString());
308 			TagUtils.getInstance().write(pageContext, buf.toString());
309 		}
310 
311 		clearState();
312 		return (EVAL_PAGE);
313 	}
314 
315 	public void release() {
316 		super.release();
317 		clearState();
318 	}
319 
320 	private void clearState() {
321 		field = null;
322 		currentValue = null;
323 		displayType = null;
324 		listOptions = null;
325 		formName = null;
326 	}
327 	
328 
329 	private String formatDate(Date dateValue, ResourceBundle bundle) {
330 		// TODO Auto-generated method stub
331 
332 		try {
333 
334 			SimpleDateFormat sdf =
335 				new SimpleDateFormat(bundle
336 						.getString("itracker.dateformat."
337 								+ field.getDateFormat()), bundle.getLocale());
338 
339 //			if (log.isDebugEnabled()) {
340 //				log.debug("getValue: dateFormat from itracker configuration "
341 //						+ sdf.toPattern());
342 //			}
343 			
344 			// sdf = new SimpleDateFormat(dateFormat, locale);
345 			String formattedDate = sdf.format(dateValue);
346 //			if (log.isDebugEnabled()) {
347 //				log.debug("getValue: formated date " + this.dateValue
348 //						+ " to " + formattedDate);
349 //			}
350 			return formattedDate;
351 		} catch (Exception ne) {
352 //			log.debug("getValue: ", ne);
353 //			if (dateValue == null) {
354 //				log.warn("getValue: failed to format date, null for "
355 //						+ customField);
356 //			}
357 			return "";
358 		}
359 	}
360 }