KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > input > Util


1 /*
2  * Copyright 1999,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.taglibs.input;
17
18 import java.beans.IntrospectionException JavaDoc;
19 import java.beans.PropertyDescriptor JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.lang.reflect.InvocationTargetException JavaDoc;
22 import java.lang.reflect.Method JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Map JavaDoc;
25
26 import javax.servlet.jsp.JspTagException JavaDoc;
27 import javax.servlet.jsp.JspWriter JavaDoc;
28 import javax.servlet.jsp.tagext.Tag JavaDoc;
29 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
30
31 /**
32  *
33  * This class includes several utility functions used by various input tags.
34  * Functionality common to several classes is located here on the relatively
35  * renegade premise that building variability into a design is better than using
36  * even single inheritance. (For example, the interfaces to all utility
37  * functions is clearly outlined here , and the utility functions don't have
38  * access to private members of the "interesting" classes.) I'll defend that
39  * this is more straightforward than a base class that includes these any day.
40  *
41  * @version 0.90
42  * @author Shawn Bayern
43  * @author Lance Lavandowska
44  * @author Karl von Randow
45  */

46
47 class Util {
48
49     /** Print out any HTML tag attributes we might have been passed. */
50     public static void printAttributes(JspWriter JavaDoc out, Map JavaDoc attributes)
51             throws JspTagException JavaDoc, IOException JavaDoc {
52         if (attributes != null) {
53             Iterator JavaDoc i = attributes.keySet().iterator();
54             while (i.hasNext()) {
55                 Object JavaDoc oKey = i.next();
56                 Object JavaDoc oVal = attributes.get(oKey);
57
58                 /*
59                  * If the attribute contains non-Strings, give the user a more
60                  * meaningful message than what he or she would get if we just
61                  * propagated a ClassCastException back. (This'll get caught
62                  * below.)
63                  */

64                 if (!(oKey instanceof String JavaDoc)
65                         || (oVal != null && !(oVal instanceof String JavaDoc)))
66                     throw new JspTagException JavaDoc(
67                             "all members in attributes Map must be Strings");
68                 String JavaDoc key = (String JavaDoc) oKey;
69                 String JavaDoc value = (String JavaDoc) oVal;
70
71                 // check for illegal keys
72
if (key.equals("name") || key.equals("value")
73                         || key.equals("type") || key.equals("checked"))
74                     throw new JspTagException JavaDoc("illegal key '" + key
75                             + "'found in attributes Map");
76
77                 /*
78                  * Print the key and value. If the value is null, make it equal
79                  * to the key. This follows the conventions of XHTML 1.0 and
80                  * does not break regular HTML.
81                  */

82                 if (value == null)
83                     value = key;
84
85                 out.print(quote(key) + "=\"" + quote(value) + "\" ");
86             }
87         }
88     }
89
90     /** Quote metacharacters in HTML. */
91     public static String JavaDoc quote(String JavaDoc x) {
92         if (x == null)
93             return null;
94         else {
95             // deal with ampersands first so we can ignore the ones we add later
96
x = replace(x, "&", "&");
97             x = replace(x, "\"", """);
98             x = replace(x, "<", "&lt;");
99             x = replace(x, ">", "&gt;");
100             return x;
101         }
102     }
103
104     /**
105      * Efficient string replace function. Replaces instances of the substring
106      * find with replace in the string subject. karl@xk72.com
107      *
108      * @param subject
109      * The string to search for and replace in.
110      * @param find
111      * The substring to search for.
112      * @param replace
113      * The string to replace instances of the string find with.
114      */

115     public static String JavaDoc replace(String JavaDoc subject, String JavaDoc find, String JavaDoc replace) {
116         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
117         int l = find.length();
118         int s = 0;
119         int i = subject.indexOf(find);
120         while (i != -1) {
121             buf.append(subject.substring(s, i));
122             buf.append(replace);
123             s = i + l;
124             i = subject.indexOf(find, s);
125         }
126         buf.append(subject.substring(s));
127         return buf.toString();
128     }
129
130     /**
131      * Gets a named property from a JavaBean and returns its value as an Object,
132      * possibly null.
133      */

134     public static Object JavaDoc beanPropertyValueObject(Object JavaDoc bean, String JavaDoc name)
135             throws JspTagException JavaDoc {
136         if (bean != null) {
137             Method JavaDoc reader = null;
138             Object JavaDoc[] params = null;
139
140             // Try to find a reader method for the named property
141
try {
142                 PropertyDescriptor JavaDoc prop = new PropertyDescriptor JavaDoc(name, bean
143                         .getClass());
144                 reader = prop.getReadMethod();
145             } catch (IntrospectionException JavaDoc e) {
146                 // No property exists with that name, try a generic get method
147
// Object get( Object key )
148
try {
149                     reader = bean.getClass().getMethod("get",
150                             new Class JavaDoc[] { Object JavaDoc.class });
151                     params = new Object JavaDoc[] { name };
152                 } catch (NoSuchMethodException JavaDoc f) {
153                     // Try an Object get( String key) method
154
try {
155                         reader = bean.getClass().getMethod("get",
156                                 new Class JavaDoc[] { String JavaDoc.class });
157                         params = new Object JavaDoc[] { name };
158                     } catch (NoSuchMethodException JavaDoc g) {
159                         // Give up
160
}
161                 }
162             }
163
164             // If a reader method has been found
165
if (reader != null) {
166                 try {
167                     return reader.invoke(bean, params);
168                 } catch (IllegalAccessException JavaDoc e) {
169                 } catch (IllegalArgumentException JavaDoc e) {
170                 } catch (InvocationTargetException JavaDoc e) {
171                     throw new JspTagException JavaDoc("Exception getting property \""
172                             + name + "\" from bean "
173                             + bean.getClass().getName() + ": "
174                             + e.getTargetException());
175                 }
176             }
177         }
178
179         return null;
180     }
181
182     /**
183      * Gets a named property from a JavaBean and returns its value as a String,
184      * possibly null.
185      */

186     public static String JavaDoc beanPropertyValue(Object JavaDoc bean, String JavaDoc name)
187             throws JspTagException JavaDoc {
188         Object JavaDoc value = beanPropertyValueObject(bean, name);
189         return (value != null ? value.toString() : null);
190     }
191
192     /**
193      * Gets a named property (possibly an array property) from a JavaBean and
194      * returns its values as an array of Strings, possibly null. If the property
195      * is not an array property, an array of size 1 is returned.
196      */

197     public static String JavaDoc[] beanPropertyValues(Object JavaDoc bean, String JavaDoc name)
198             throws JspTagException JavaDoc {
199         Object JavaDoc value = beanPropertyValueObject(bean, name);
200         if (value != null) {
201             // Check if the value is an array object
202
if (value.getClass().isArray()) {
203                 // Convert to an array of Strings
204
int n = java.lang.reflect.Array.getLength(value);
205                 String JavaDoc[] strs = new String JavaDoc[n];
206                 for (int i = 0; i < n; i++) {
207                     Object JavaDoc o = java.lang.reflect.Array.get(value, i);
208                     strs[i] = (o != null ? o.toString() : null);
209                 }
210                 return strs;
211             }
212             // If not an array, just convert the object to a String in an array
213
// and return
214
else {
215                 return new String JavaDoc[] { value.toString() };
216             }
217         } else {
218             return null;
219         }
220     }
221
222     /**
223      * Finds the input:form tag enclosing the given tag and returns it.
224      */

225     public static Form findFormTag(Tag JavaDoc tag) {
226         Tag JavaDoc formTag = TagSupport.findAncestorWithClass(tag, Form.class);
227         if (formTag != null) {
228             return (Form) formTag;
229         } else {
230             return null;
231         }
232     }
233
234     /**
235      * Finds the input:form tag enclosing the given tag and returns the "bean"
236      * property from it, that is the default bean for this form, possibly null.
237      */

238     public static String JavaDoc defaultFormBeanId(Tag JavaDoc tag) {
239         Form form = findFormTag(tag);
240         if (form != null) {
241             return form.getBean();
242         } else {
243             return null;
244         }
245     }
246 }
Popular Tags