KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > thauvin > google > TagUtility


1 /*
2  * @(#)TagUtility.java
3  *
4  * Copyright (c) 2002-2003, Erik C. Thauvin (erik@thauvin.net)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  * Redistributions of source code must retain the above copyright notice,
12  * this list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution.
17  *
18  * Neither the name of the author nor the names of its contributors may be
19  * used to endorse or promote products derived from this software without
20  * specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
23  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * $Id: TagUtility.java,v 1.5 2003/10/13 23:43:20 ethauvin Exp $
35  *
36  */

37 package net.thauvin.google;
38
39 import java.net.URLEncoder JavaDoc;
40
41 import java.util.Enumeration JavaDoc;
42
43 import javax.servlet.ServletRequest JavaDoc;
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.jsp.JspTagException JavaDoc;
46 import javax.servlet.jsp.PageContext JavaDoc;
47 import javax.servlet.jsp.tagext.BodyContent JavaDoc;
48
49
50 /**
51  * Implements various methods commonly used by custom tags.
52  *
53  * @author Erik C. Thauvin
54  * @created April 25, 2002
55  * @version $Revision: 1.5 $
56  * @since 1.0
57  */

58 public class TagUtility
59 {
60     /**
61      * The name of the cache request parameter.
62      */

63     public static final String JavaDoc CACHE_PARAM = "cache";
64
65     /**
66      * The name of the filter request parameter.
67      */

68     public static final String JavaDoc FILTER_PARAM = "filter";
69
70     /**
71      * The HTTP proxy host.
72      */

73     public static final String JavaDoc GOOGLE_PROXY_HOST = "google_proxy_host";
74
75     /**
76      * The HTTP proxy password.
77      */

78     public static final String JavaDoc GOOGLE_PROXY_PASSWORD = "google_proxy_password";
79
80     /**
81      * The HTTP proxy port.
82      */

83     public static final String JavaDoc GOOGLE_PROXY_PORT = "google_proxy_port";
84
85     /**
86      * The HTTP proxy username.
87      */

88     public static final String JavaDoc GOOGLE_PROXY_USERNAME = "google_proxy_username";
89
90     /**
91      * The name of the Google Search bean attribute.
92      */

93     public static final String JavaDoc GOOGLE_SEARCH_BEAN = "GoogleSearchBean";
94
95     /**
96      * The name of the input encoding context parameter.
97      */

98     public static final String JavaDoc IE_PARAM = "ie";
99
100     /**
101      * The name of the key context parameter.
102      */

103     public static final String JavaDoc KEY_CONTEXT_PARAM = "google_key";
104
105     /**
106      * The name of the key request parameter.
107      */

108     public static final String JavaDoc KEY_PARAM = "key";
109
110     /**
111      * The name of the language restrict context parameter.
112      */

113     public static final String JavaDoc LR_PARAM = "lr";
114
115     /**
116      * The name of the maxResults request parameter.
117      */

118     public static final String JavaDoc MAX_RESULTS_PARAM = "maxResults";
119
120     /**
121      * The name of the output encoding context parameter.
122      */

123     public static final String JavaDoc OE_PARAM = "oe";
124
125     /**
126      * The name of the query request parameter.
127      */

128     public static final String JavaDoc QUERY_PARAM = "q";
129
130     /**
131      * The name of the restrict context parameter.
132      */

133     public static final String JavaDoc RESTRICT_PARAM = "restrict";
134
135     /**
136      * The name of the safeSearch context parameter.
137      */

138     public static final String JavaDoc SAFE_SEARCH_PARAM = "safeSearch";
139
140     /**
141      * The name of the site context parameter.
142      */

143     public static final String JavaDoc SITE_PARAM = "site";
144
145     /**
146      * The name of the start request parameter.
147      */

148     public static final String JavaDoc START_PARAM = "start";
149
150     /**
151      * The name of the (file) type request parameter.
152      */

153     public static final String JavaDoc TYPE_PARAM = "type";
154
155     /**
156      * Protected constructor to disable instantiation.
157      */

158     protected TagUtility()
159     {
160         // Disabled
161
}
162
163     /**
164      * Returns the body of a tag.
165      *
166      * @param bodyContent The body.
167      * @return The tag body string or null.
168      */

169     public static final String JavaDoc getTagBody(BodyContent JavaDoc bodyContent)
170     {
171         return getTagBody(bodyContent, false);
172     }
173
174     /**
175      * Returns the body of a tag.
176      *
177      * @param bodyContent The body.
178      * @param trim Trim the body if true
179      * @return The tag body string or null.
180      */

181     public static final String JavaDoc getTagBody(BodyContent JavaDoc bodyContent, boolean trim)
182     {
183         try
184         {
185             if (trim)
186             {
187                 return bodyContent.getString().trim();
188             }
189             else
190             {
191                 return bodyContent.getString();
192             }
193         }
194         catch (NullPointerException JavaDoc e)
195         {
196             return null;
197         }
198     }
199
200     /**
201      * Validates a string value by insuring it is not null or empty.
202      * <p>
203      * Beginning and trailing spaces are removed whenever the trim
204      * flag is set to true.
205      *
206      * @param stringValue The String value.
207      * @param trim The trim flag.
208      * @return true if valid, false if not.
209      */

210     public static final boolean isValidString(String JavaDoc stringValue, boolean trim)
211     {
212         if ((stringValue != null))
213         {
214             if (trim)
215             {
216                 return isValidString(stringValue.trim());
217             }
218             else
219             {
220                 return isValidString(stringValue);
221             }
222         }
223
224         return false;
225     }
226
227     /**
228      * Validates a string value by insuring it is not null or empty.
229      *
230      * @param stringValue The String value.
231      * @return true if valid, false if not.
232      */

233     public static final boolean isValidString(String JavaDoc stringValue)
234     {
235         if ((stringValue != null) && (stringValue.length() > 0))
236         {
237             return true;
238         }
239
240         return false;
241     }
242
243     /**
244      * Returns the GoogleSearchBean attribute using the default
245      * {@link #GOOGLE_SEARCH_BEAN bean name}.
246      *
247      * @param pageContext The page context.
248      * @return The default Google search bean.
249      */

250     public static GoogleSearchBean getGoogleSearchBean(PageContext JavaDoc pageContext)
251     {
252         // Fetch the bean using the default name
253
return ((GoogleSearchBean)pageContext.findAttribute(GOOGLE_SEARCH_BEAN));
254     }
255
256     /**
257      * Returns the value a specified parameter.
258      *
259      * @param request The ServletRequest object
260      * @param paramName The parameter name String value.
261      * @return The parameter value or null.
262      */

263     public static String JavaDoc getParameter(ServletRequest JavaDoc request, String JavaDoc paramName)
264     {
265         // The parameter value
266
String JavaDoc paramValue = null;
267
268         if (isValidString(paramName))
269         {
270             // Get all parameters names
271
final Enumeration JavaDoc names = request.getParameterNames();
272
273             // Loop thru the names
274
while (names.hasMoreElements())
275             {
276                 // Get the next parameter name
277
final String JavaDoc name = (String JavaDoc)names.nextElement();
278
279                 // Is it our parameter?
280
if (name.equalsIgnoreCase(paramName))
281                 {
282                     // Get the parameter value
283
paramValue = request.getParameter(name);
284                 }
285             }
286         }
287
288         // Return the parameter value
289
return paramValue;
290     }
291
292     /**
293      * Builds a HTML reference link:
294      * <p>
295      * For example: <code>&lt;a HREF="url" class="css" style="style" target="target"&gt;body&lt;/a&gt;</code>.
296      *
297      * @param url The reference URL.
298      * @param body The link body text.
299      * @param target The link target.
300      * @param style The link CSS style.
301      * @param css The link CSS class.
302      * @return A HTML reference link.
303      */

304     public static final String JavaDoc buildRefLink(String JavaDoc url, String JavaDoc body,
305                                             String JavaDoc target, String JavaDoc style,
306                                             String JavaDoc css)
307     {
308         final StringBuffer JavaDoc refLink = new StringBuffer JavaDoc();
309
310         // Output the hyperlink reference
311
refLink.append("<A HREF=\"").append(url).append('"');
312
313         // Is a target specified?
314
if (TagUtility.isValidString(target))
315         {
316             // Output the HREF target
317
refLink.append(" TARGET=\"").append(target).append('"');
318         }
319
320         if (TagUtility.isValidString(css))
321         {
322             // Ouput the CSS class
323
refLink.append(" CLASS=\"").append(css).append('"');
324         }
325
326         if (TagUtility.isValidString(style))
327         {
328             // Output the CSS style
329
refLink.append(" STYLE=\"").append(style).append('"');
330         }
331
332         // Close HREF
333
refLink.append('>').append(body).append("</A>");
334
335         return (refLink.toString());
336     }
337
338     /**
339      * Returns the default tag misplaced (not in container) error exception.
340      *
341      * @param tag The tag name.
342      * @param container The container name.
343      * @return The default misplaced error exception.
344      */

345     public static final JspTagException JavaDoc misplacedError(String JavaDoc tag,
346                                                        String JavaDoc container)
347     {
348         return new JspTagException JavaDoc("The '" + tag
349                                    + "' tag must be located within the '"
350                                    + container + "' container tag.");
351     }
352
353     /**
354      * Returns the default tag misplaced (not in valid container) error
355      * exception.
356      *
357      * @param tag The tag name.
358      * @return The default misplaced error exception.
359      */

360     public static final JspTagException JavaDoc misplacedError(String JavaDoc tag)
361     {
362         return new JspTagException JavaDoc("The '" + tag
363                                    + "' tag must be located within a valid container tag.");
364     }
365
366     /**
367      * Builds name=value pair with URL encoding.
368      *
369      * @param name The name string.
370      * @param value The value string.
371      * @return The name=value pair.
372      */

373     public static final String JavaDoc nameValuePair(String JavaDoc name, String JavaDoc value)
374     {
375         return (URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
376     }
377
378     /**
379      * Returns a nested exception.
380      * <p>
381      * The nested exception format is as follows:
382      * <blockquote>
383      * <code>
384      * New Message<br>
385      * &lt;space>&gt;space&gt;nested exception is:&lt;space&gt;<br>
386      * &lt;tab&gt; java.lang.Exception: Old Message
387      * </code>
388      * </blockquote>
389      *
390      * @param msg The new exception message.
391      * @param old The old exception object.
392      * @return A nested exception.
393      */

394     public static final JspTagException JavaDoc nestedException(String JavaDoc msg,
395                                                         Exception JavaDoc old)
396     {
397         return new JspTagException JavaDoc(msg + "\n nested exception is: \n\t"
398                                    + old.toString());
399     }
400
401     /**
402      * Returns the default tag output error exception.
403      *
404      * @param tag The tag name.
405      * @param e The caught exception.
406      * @return The default tag output error exception.
407      */

408     public static final JspTagException JavaDoc outputError(String JavaDoc tag, Exception JavaDoc e)
409     {
410         StringBuffer JavaDoc buff =
411             new StringBuffer JavaDoc("An error occurred while processing the '" + tag
412                              + "' tag.");
413
414         if (e != null)
415         {
416             buff.append("\n\nException:\n");
417         }
418
419         if (e != null)
420         {
421             buff.append("\n nested exception is: \n\t"
422                         + e.getClass().getName() + ": "
423                         + e.getLocalizedMessage());
424         }
425
426         return new JspTagException JavaDoc(buff.toString());
427     }
428
429     /**
430      * Converts the request's parameter names/values into ampersand-delimited
431      * and URL-encoded name/value pairs.
432      *
433      * @param request The servlet request object.
434      * @param remove The parameter to be removed.
435      * @return The name/value pairs.
436      */

437     public static final String JavaDoc requestParamsToUrl(HttpServletRequest JavaDoc request,
438                                                   String JavaDoc remove)
439     {
440         final StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
441         final Enumeration JavaDoc names = request.getParameterNames();
442
443         // Are there any parameters?
444
if (names.hasMoreElements())
445         {
446             // Loop through the parameter names
447
while (names.hasMoreElements())
448             {
449                 // Get the next parameter name
450
final String JavaDoc name = (String JavaDoc)names.nextElement();
451
452                 // Is it the name to be removed?
453
if ((remove == null) || (!remove.equals(name)))
454                 {
455                     // Get the parameter values
456
final String JavaDoc values[] = request.getParameterValues(name);
457
458                     // Loop through the values
459
for (int i = 0; i < values.length; i++)
460                     {
461                         // Is it the very first parameter?
462
if (buff.length() > 0)
463                         {
464                             // Append an ampersand to the buffer
465
buff.append("&");
466                         }
467
468                         // Append the parameter name and value to the buffer
469
buff.append(nameValuePair(name, values[i]));
470                     }
471                 }
472             }
473         }
474
475         return (buff.toString());
476     }
477 }
478
Popular Tags