KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > tools > view > tools > ParameterParser


1 /*
2  * Copyright 2003-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
17 package org.apache.velocity.tools.view.tools;
18
19 import javax.servlet.ServletRequest JavaDoc;
20
21 import org.apache.velocity.tools.view.context.ViewContext;
22 import org.apache.velocity.tools.view.tools.ViewTool;
23
24 /**
25  * <p>Utility class for easy parsing of {@link ServletRequest} parameters.</p>
26  * <p><pre>
27  * Template example(s):
28  * $pp.foo -> bar
29  * $pp.getNumber('baz') -> 12.6
30  * $pp.getInt('baz') -> 12
31  * $pp.getNumbers('foo') -> [12.6]
32  *
33  * Toolbox configuration:
34  * &lt;tool&gt;
35  * &lt;key&gt;pp&lt;/key&gt;
36  * &lt;scope&gt;request&lt;/scope&gt;
37  * &lt;class&gt;org.apache.velocity.tools.view.tools.ParameterParser&lt;/class&gt;
38  * &lt;/tool&gt;
39  * </pre></p>
40  *
41  * <p>When used as a view tool, this should only be used in the request scope.
42  * This class is, however, quite useful in your application's controller, filter,
43  * or action code as well as in templates.</p>
44  *
45  * @author <a HREF="mailto:nathan@esha.com">Nathan Bubna</a>
46  * @version $Revision: 1.8.2.1 $ $Date: 2004/03/12 20:16:28 $
47  */

48 public class ParameterParser implements ViewTool
49 {
50
51     private ServletRequest JavaDoc request;
52
53
54     /**
55      * Constructs a new instance
56      */

57     public ParameterParser()
58     {}
59
60
61     /**
62      * Constructs a new instance using the specified request.
63      *
64      * @param request the {@link ServletRequest} to be parsed
65      */

66     public ParameterParser(ServletRequest JavaDoc request)
67     {
68         setRequest(request);
69     }
70     
71     
72     /**
73      * Initializes this instance.
74      *
75      * @param obj the current ViewContext or ServletRequest
76      * @throws IllegalArgumentException if the param is not a
77      * ViewContext or ServletRequest
78      */

79     public void init(Object JavaDoc obj)
80     {
81         if (obj instanceof ViewContext)
82         {
83             setRequest(((ViewContext)obj).getRequest());
84         }
85         else if (obj instanceof ServletRequest JavaDoc)
86         {
87             setRequest((ServletRequest JavaDoc)obj);
88         }
89         else
90         {
91             throw new IllegalArgumentException JavaDoc("Was expecting " + ViewContext.class +
92                                                " or " + ServletRequest JavaDoc.class);
93         }
94     }
95
96
97     /**
98      * Sets the current {@link ServletRequest}
99      *
100      * @param request the {@link ServletRequest} to be parsed
101      */

102     protected void setRequest(ServletRequest JavaDoc request)
103     {
104         this.request = request;
105     }
106
107
108     /**
109      * Returns the current {@link ServletRequest} for this instance.
110      *
111      * @return the current {@link ServletRequest}
112      * @throws UnsupportedOperationException if the request is null
113      */

114     protected ServletRequest JavaDoc getRequest()
115     {
116         if (request == null)
117         {
118             throw new UnsupportedOperationException JavaDoc("Request is null. ParameterParser must be initialized first!");
119         }
120         return request;
121     }
122
123
124     // ----------------- public parsing methods --------------------------
125

126     /**
127      * Convenience method for checking whether a certain parameter exists.
128      *
129      * @param key the parameter's key
130      * @return <code>true</code> if a parameter exists for the specified
131      * key; otherwise, returns <code>false</code>.
132      */

133     public boolean exists(String JavaDoc key)
134     {
135         return (getString(key) != null);
136     }
137
138
139     /**
140      * Convenience method for use in Velocity templates.
141      * This allows for easy "dot" access to parameters.
142      *
143      * e.g. $params.foo instead of $params.getString('foo')
144      *
145      * @param key the parameter's key
146      * @return parameter matching the specified key or
147      * <code>null</code> if there is no matching
148      * parameter
149      */

150     public String JavaDoc get(String JavaDoc key)
151     {
152         return getString(key);
153     }
154
155
156     /**
157      * @param key the parameter's key
158      * @return parameter matching the specified key or
159      * <code>null</code> if there is no matching
160      * parameter
161      */

162     public String JavaDoc getString(String JavaDoc key)
163     {
164         return getRequest().getParameter(key);
165     }
166
167
168     /**
169      * @param key the desired parameter's key
170      * @param alternate The alternate value
171      * @return parameter matching the specified key or the
172      * specified alternate String if there is no matching
173      * parameter
174      */

175     public String JavaDoc getString(String JavaDoc key, String JavaDoc alternate)
176     {
177         String JavaDoc s = getString(key);
178         return (s != null) ? s : alternate;
179     }
180
181
182     /**
183      * @param key the desired parameter's key
184      * @return a {@link Boolean} object for the specified key or
185      * <code>null</code> if no matching parameter is found
186      */

187     public Boolean JavaDoc getBoolean(String JavaDoc key)
188     {
189         String JavaDoc s = getString(key);
190         return (s != null) ? Boolean.valueOf(s) : null;
191     }
192
193
194     /**
195      * @param key the desired parameter's key
196      * @param alternate The alternate boolean value
197      * @return boolean value for the specified key or the
198      * alternate boolean is no value is found
199      */

200     public boolean getBoolean(String JavaDoc key, boolean alternate)
201     {
202         Boolean JavaDoc bool = getBoolean(key);
203         return (bool != null) ? bool.booleanValue() : alternate;
204     }
205
206
207     /**
208      * @param key the desired parameter's key
209      * @param alternate the alternate {@link Boolean}
210      * @return a {@link Boolean} for the specified key or the specified
211      * alternate if no matching parameter is found
212      */

213     public Boolean JavaDoc getBoolean(String JavaDoc key, Boolean JavaDoc alternate)
214     {
215         Boolean JavaDoc bool = getBoolean(key);
216         return (bool != null) ? bool : alternate;
217     }
218
219
220     /**
221      * @param key the desired parameter's key
222      * @return a {@link Number} for the specified key or
223      * <code>null</code> if no matching parameter is found
224      */

225     public Number JavaDoc getNumber(String JavaDoc key)
226     {
227         String JavaDoc s = getString(key);
228         if (s == null || s.length() == 0)
229         {
230             return null;
231         }
232         try
233         {
234             return parseNumber(s);
235         }
236         catch (Exception JavaDoc e)
237         {
238             //there is no Number with that key
239
return null;
240         }
241     }
242
243
244     /**
245      * @param key the desired parameter's key
246      * @param alternate The alternate Number
247      * @return a Number for the specified key or the specified
248      * alternate if no matching parameter is found
249      */

250     public Number JavaDoc getNumber(String JavaDoc key, Number JavaDoc alternate)
251     {
252         Number JavaDoc n = getNumber(key);
253         return (n != null) ? n : alternate;
254     }
255
256
257     /**
258      * @param key the desired parameter's key
259      * @param alternate The alternate int value
260      * @return the int value for the specified key or the specified
261      * alternate value if no matching parameter is found
262      */

263     public int getInt(String JavaDoc key, int alternate)
264     {
265         Number JavaDoc n = getNumber(key);
266         return (n != null) ? n.intValue() : alternate;
267     }
268
269
270     /**
271      * @param key the desired parameter's key
272      * @param alternate The alternate double value
273      * @return the double value for the specified key or the specified
274      * alternate value if no matching parameter is found
275      */

276     public double getDouble(String JavaDoc key, double alternate)
277     {
278         Number JavaDoc n = getNumber(key);
279         return (n != null) ? n.doubleValue() : alternate;
280     }
281
282
283     /**
284      * @param key the key for the desired parameter
285      * @return an array of String objects containing all of the values
286      * the given request parameter has, or <code>null</code>
287      * if the parameter does not exist
288      */

289     public String JavaDoc[] getStrings(String JavaDoc key)
290     {
291         return getRequest().getParameterValues(key);
292     }
293
294
295     /**
296      * @param key the key for the desired parameter
297      * @return an array of Number objects for the specified key or
298      * <code>null</code> if the parameter does not exist or the
299      * parameter does not contain Numbers.
300      */

301     public Number JavaDoc[] getNumbers(String JavaDoc key)
302     {
303         String JavaDoc[] strings = getStrings(key);
304         if (strings == null)
305         {
306             return null;
307         }
308         
309         Number JavaDoc[] nums = new Number JavaDoc[strings.length];
310         try
311         {
312             for(int i=0; i<nums.length; i++)
313             {
314                 if (strings[i] != null && strings[i].length() > 0)
315                 {
316                     nums[i] = parseNumber(strings[i]);
317                 }
318             }
319         }
320         catch (NumberFormatException JavaDoc nfe)
321         {
322             return null;
323         }
324         return nums;
325     }
326
327
328     /**
329      * @param key the key for the desired parameter
330      * @return an array of int values for the specified key or
331      * <code>null</code> if the parameter does not exist or the
332      * parameter does not contain ints.
333      */

334     public int[] getInts(String JavaDoc key)
335     {
336         String JavaDoc[] strings = getStrings(key);
337         if (strings == null)
338         {
339             return null;
340         }
341         
342         int[] ints = new int[strings.length];
343         try
344         {
345             for(int i=0; i<ints.length; i++)
346             {
347                 if (strings[i] != null && strings[i].length() > 0)
348                 {
349                     ints[i] = parseNumber(strings[i]).intValue();
350                 }
351             }
352         }
353         catch (NumberFormatException JavaDoc nfe)
354         {
355             return null;
356         }
357         return ints;
358     }
359
360
361     /**
362      * @param key the key for the desired parameter
363      * @return an array of double values for the specified key or
364      * <code>null</code> if the parameter does not exist or the
365      * parameter does not contain doubles.
366      */

367     public double[] getDoubles(String JavaDoc key)
368     {
369         String JavaDoc[] strings = getStrings(key);
370         if (strings == null)
371         {
372             return null;
373         }
374         
375         double[] doubles = new double[strings.length];
376         try
377         {
378             for(int i=0; i<doubles.length; i++)
379             {
380                 if (strings[i] != null && strings[i].length() > 0)
381                 {
382                     doubles[i] = parseNumber(strings[i]).doubleValue();
383                 }
384             }
385         }
386         catch (NumberFormatException JavaDoc nfe)
387         {
388             return null;
389         }
390         return doubles;
391     }
392
393
394     // --------------------------- protected methods ------------------
395

396     /**
397      * Converts a parameter value into a {@link Number}
398      * This is used as the base for all numeric parsing methods. So,
399      * sub-classes can override to allow for customized number parsing.
400      * (e.g. to handle fractions, compound numbers, etc.)
401      *
402      * @param value the string to be parsed
403      * @return the value as a {@link Number}
404      */

405     protected Number JavaDoc parseNumber(String JavaDoc value) throws NumberFormatException JavaDoc
406     {
407         if (value.indexOf('.') >= 0)
408         {
409             return new Double JavaDoc(value);
410         }
411         return new Long JavaDoc(value);
412     }
413  
414 }
415
Popular Tags