KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > taglib > core > html > LabelTag


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 com.blandware.atleap.webapp.taglib.core.html;
17
18 import com.blandware.atleap.webapp.util.core.ApplicationResources;
19 import com.blandware.atleap.webapp.taglib.core.html.FormTag;
20 import org.apache.commons.lang.StringUtils;
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23 import org.apache.commons.validator.Field;
24 import org.apache.commons.validator.Form;
25 import org.apache.commons.validator.ValidatorResources;
26 import org.apache.struts.Globals;
27 import org.apache.struts.action.ActionMessage;
28 import org.apache.struts.action.ActionMessages;
29 import org.apache.struts.taglib.TagUtils;
30 import org.apache.struts.taglib.html.Constants;
31 import org.apache.struts.validator.ValidatorPlugIn;
32
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.jsp.JspException JavaDoc;
35 import javax.servlet.jsp.JspTagException JavaDoc;
36 import javax.servlet.jsp.PageContext JavaDoc;
37 import javax.servlet.jsp.tagext.SimpleTagSupport JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.Locale JavaDoc;
40
41
42 /**
43  * <p>This class is designed to render a <label> tag for labeling your forms; it
44  * adds an asterisk (*) for required fields. It was originally written by Erik
45  * Hatcher (http://www.ehatchersolutions.com/JavaDevWithAnt/).
46  * </p>
47  * <p>Modified in order to provide flexibility by <a HREF="mailto:sergey.zubtcovskii@blandware.com">Sergey Zubtcovskii</a>
48  * </p>
49  * <p>It is designed to be used as follows:
50  * <pre>
51  * &lt;atleap:label property="username" key="core.user.form.username" /&gt;
52  * </pre>
53  * You may also specify <em>formName</em> attribute. By default it will be taken from enclosing
54  * FormTag. If no such tag is found, JspException will be thrown.
55  * <br />
56  * You MUST specify <em>property</em> attribute, but <em>key</em> attribute may be omitted.
57  * In such case field key will be constructed from form name and property as follows:
58  * <pre>
59  * <div align="center" style="font-style: italic;">formKey = formName.property</div>
60  * </pre>
61  * </p>
62  * <p>
63  * Full list of allowed attributes:
64  * <ul>
65  * <li>
66  * <b>property</b> - required - property this label is created for
67  * </li>
68  * <li>
69  * <b>key</b> - bundle key for our field, it's used to get label; by default
70  * it's <b>formName</b>.<b>property</b> (form name and property separated with
71  * period).
72  * </li>
73  * <li>
74  * <b>formName</b> - name of form bean to which property belongs. By default is
75  * taken from enclosing <em>form</em> tag.
76  * </li>
77  * <li>
78  * <b>colon</b> - whether or not to put colon (':') after label. Default is
79  * true.
80  * </li>
81  * <li>
82  * <b>helpTip</b> - whether or not to create a helptip event for this label.
83  * Default is false.
84  * </li>
85  * <li>
86  * <b>style</b> - CSS style to be applied to this element
87  * </li>
88  * <li>
89  * <b>styleClass</b> - CSS class for label in normal state, if not specified and
90  * field is required, then "required" will be used
91  * </li>
92  * <li>
93  * <b>errorClass</b> - CSS class for label when validation error has occured.
94  * By default it is "error".
95  * </li>
96  * </ul>
97  * </p>
98  * <p><a HREF="LabelTag.java.htm"><i>View Source</i></a></p>*
99  *
100  * @author Eric Hatcher <a HREF="http://www.ehatchersolutions.com/JavaDevWithAnt/">http://www.ehatchersolutions.com/JavaDevWithAnt/</a>
101  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
102  * @version $Revision: 1.3 $ $Date: 2005/10/24 15:06:23 $
103  * @jsp.tag name="label" body-content="empty"
104  */

105 public class LabelTag extends SimpleTagSupport JavaDoc {
106     protected transient final Log log = LogFactory.getLog(LabelTag.class);
107
108     /**
109      * Bundle key for our field
110      */

111     protected String JavaDoc key = null;
112
113     /**
114      * CSS class for label in normal state, if not specified and
115      * field is required, then "required" will be used
116      */

117     protected String JavaDoc styleClass = null;
118
119     /**
120      * CSS style to be applied to this element
121      */

122     protected String JavaDoc style = null;
123
124     /**
125      * CSS class for label when validation error has occured. By default it is "error"
126      */

127     protected String JavaDoc errorClass = null;
128
129     /**
130      * Whether or not to put colon after label
131      */

132     protected boolean colon = true;
133
134     /**
135      * Whether or not create a helptip event for this label
136      */

137     protected boolean helpTip = false;
138
139     /**
140      * Property this label is created for
141      */

142     protected String JavaDoc property = null;
143
144     /**
145      * Name of form bean to which property belongs. By default is taken from enclosing FormTag
146      */

147     protected String JavaDoc formName = null;
148
149     /**
150      * Processes the tag
151      *
152      * @throws JspException
153      */

154     public void doTag() throws JspException JavaDoc {
155
156         PageContext JavaDoc pageContext = (PageContext JavaDoc) getJspContext();
157         HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) pageContext.getRequest();
158         ApplicationResources applicationResources = ApplicationResources.getInstance(pageContext.getServletContext());
159
160         // Look up this key to see if it's a field of the current form
161
boolean requiredField = false;
162         boolean validationError = false;
163         TagUtils tagUtils = TagUtils.getInstance();
164
165         ValidatorResources resources =
166                 (ValidatorResources) pageContext.getServletContext()
167                 .getAttribute(ValidatorPlugIn.VALIDATOR_KEY);
168
169         Locale JavaDoc locale =
170                 (Locale JavaDoc) pageContext.findAttribute(Globals.LOCALE_KEY);
171
172         if ( locale == null ) {
173             locale = Locale.getDefault();
174         }
175
176         FormTag formTag =
177                 (FormTag) pageContext.getAttribute(Constants.FORM_KEY,
178                         PageContext.REQUEST_SCOPE);
179
180         // if form tag was not found in request, try to find ancestor
181
if ( formTag == null ) {
182             formTag = (FormTag) findAncestorWithClass(this, FormTag.class);
183         }
184
185         // if still not found - throw an exception
186
if ( formTag == null ) {
187             String JavaDoc errorMessage = "Couldn't find enclosing 'form' tag";
188             if ( log.isErrorEnabled() ) {
189                 log.error(errorMessage);
190             }
191             throw new JspTagException JavaDoc(errorMessage);
192         }
193
194         if ( formName == null ) {
195             formName = formTag.getBeanName();
196         }
197
198         if ( key == null || key.length() == 0 ) {
199             StringBuffer JavaDoc strBuffer = new StringBuffer JavaDoc(formName);
200             strBuffer.append(".");
201             strBuffer.append(property);
202             key = strBuffer.toString();
203         }
204
205         if ( resources != null ) {
206             Form form = resources.getForm(locale, formName);
207
208             if ( form != null ) {
209                 Field field = form.getField(property);
210
211                 if ( field != null ) {
212                     if ( field.isDependency("required") ) {
213                         requiredField = true;
214                     }
215                 }
216             }
217         }
218
219         ActionMessages errors = tagUtils.getActionMessages(pageContext, Globals.ERROR_KEY);
220
221         StringBuffer JavaDoc valMessage = new StringBuffer JavaDoc();
222
223         if ( errors != null ) {
224             // check for errors from the validator
225
Iterator JavaDoc valIterator = errors.get(property);
226
227             while ( valIterator.hasNext() ) {
228                 validationError = true;
229
230                 ActionMessage error = (ActionMessage) valIterator.next();
231
232                 // Retrieve the message string we are looking for
233
valMessage.append(applicationResources.getMessage(request, error.getKey(), error.getValues()));
234             }
235         }
236
237         // Retrieve the message string we are looking for
238
String JavaDoc message = applicationResources.getMessage(request, key);
239
240         StringBuffer JavaDoc valError = new StringBuffer JavaDoc();
241
242         if ( message == null ) {
243             message = "???" + key + "???";
244         } else if ( validationError ) {
245             valError.append(valMessage);
246         }
247
248         String JavaDoc cssClass = null;
249         if ( styleClass != null ) {
250             cssClass = styleClass;
251         } else if ( requiredField ) {
252             cssClass = "required";
253         }
254
255         String JavaDoc cssErrorClass = (errorClass != null) ? errorClass : "error";
256         StringBuffer JavaDoc label = new StringBuffer JavaDoc();
257
258         if ( (message == null) || "".equals(message.trim()) ) {
259             label.append("");
260         } else {
261             label.append("<label for=\"" + property + "\"");
262
263             if ( validationError ) {
264                 label.append(" class=\"" + cssErrorClass + "\"");
265             } else if ( cssClass != null ) {
266                 label.append(" class=\"" + cssClass + "\"");
267             }
268
269             if ( style != null && style.length() != 0 ) {
270                 label.append(" style=\"" + style + "\"");
271             }
272
273             label.append(">" + ((requiredField) ? "* " : "") + message);
274             String JavaDoc marker = (locale.equals(Locale.FRENCH)) ? " :" : ":";
275             label.append(((colon) ? marker : "") + "</label>");
276
277             if ( valError.length() > 0 ) {
278                 String JavaDoc error = valError.toString();
279
280                 if ( helpTip ) {
281                     // strip out any single or double quotes
282
String JavaDoc htmlFriendly = StringUtils.replace(error, "'", "\\\'");
283                     htmlFriendly =
284                             StringUtils.replace(htmlFriendly, "\"", "\\\"");
285                     label.append(" <a class=\"errorLink\" HREF=\"?\" onclick=\"showHelpTip(event, '");
286
287                     label.append(htmlFriendly + "', false); return false\" ");
288                     label.append("onmouseover=\"showHelpTip(event, '");
289                     label.append(htmlFriendly + "', false); return false\" ");
290                     label.append("onmouseout=\"hideHelpTip(event); return false\">");
291                 }
292
293
294                 label.append("<img class=\"validationWarning\" ");
295
296                 String JavaDoc context =
297                         ((HttpServletRequest JavaDoc) pageContext.getRequest())
298                         .getContextPath();
299
300                 label.append("src=\"" + context);
301                 label.append(applicationResources.getMessage(request, "core.commons.icon.warning.img"));
302                 label.append("\" />");
303                 if ( helpTip ) {
304                     label.append("</a>");
305                 }
306             }
307         }
308
309         // Print the retrieved message to our output writer
310
tagUtils.write(pageContext, label.toString());
311
312     }
313
314     /**
315      * Sets bundle key corresponding to the field
316      *
317      * @param key bundle key corresponding to the field
318      * @jsp.attribute required="false"
319      * rtexprvalue="true"
320      * type="java.lang.String"
321      * description="Bundle key for our field"
322      */

323     public void setKey(String JavaDoc key) {
324         this.key = key;
325     }
326
327     /**
328      * Sets whether or not to put colon after label
329      *
330      * @param colon whether to put colon after label
331      * @jsp.attribute required="false"
332      * rtexprvalue="true"
333      * type="boolean"
334      * description="Whether or not put colon after label"
335      */

336     public void setColon(boolean colon) {
337         this.colon = colon;
338     }
339
340     /**
341      * Sets style class
342      *
343      * @param styleClass style class to set
344      * @jsp.attribute required="false"
345      * rtexprvalue="true"
346      * type="java.lang.String"
347      * description="CSS class for label in normal state"
348      */

349     public void setStyleClass(String JavaDoc styleClass) {
350         this.styleClass = styleClass;
351     }
352
353     /**
354      * Sets CSS style
355      *
356      * @param style CSS style to set
357      * @jsp.attribute required="false"
358      * rtexprvalue="true"
359      * type="java.lang.String"
360      * description="CSS style to be applied to this element"
361      */

362     public void setStyle(String JavaDoc style) {
363         this.style = style;
364     }
365
366     /**
367      * Sets error style class
368      *
369      * @param errorClass error style class to set
370      * @jsp.attribute required="false"
371      * rtexprvalue="true"
372      * type="java.lang.String"
373      * description="CSS class for label when validation error has occured"
374      */

375     public void setErrorClass(String JavaDoc errorClass) {
376         this.errorClass = errorClass;
377     }
378
379     /**
380      * Sets whether to create a help tip
381      *
382      * @param helpTip whether to create a help tip
383      * @jsp.attribute required="false"
384      * rtexprvalue="true"
385      * type="boolean"
386      * description="Whether or not create a helptip event for this label"
387      */

388     public void setHelpTip(boolean helpTip) {
389         this.helpTip = helpTip;
390     }
391
392     /**
393      * Sets property name for which this label is created
394      *
395      * @param property property name to set
396      * @jsp.attribute required="true"
397      * rtexprvalue="true"
398      * type="java.lang.String"
399      * description="Property this label is created for"
400      */

401     public void setProperty(String JavaDoc property) {
402         this.property = property;
403     }
404
405     /**
406      * Sets form name to which this label belongs
407      *
408      * @param formName form name to set
409      * @jsp.attribute required="false"
410      * rtexprvalue="true"
411      * type="java.lang.String"
412      * description="Name of form bean to which property belongs."
413      */

414     public void setFormName(String JavaDoc formName) {
415         this.formName = formName;
416     }
417
418 }
419
Popular Tags