KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > core > helper > servlet > DefaultServletRequestWrapper


1 /*
2  * Copyright (C) 2003 Christian Cryder [christianc@granitepeaks.com]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: DefaultServletRequestWrapper.java,v 1.2 2004/02/01 05:16:28 christianc Exp $
19  */

20 package org.enhydra.barracuda.core.helper.servlet;
21
22 import java.io.*;
23 import java.util.*;
24 import java.security.*;
25 import javax.servlet.*;
26 import javax.servlet.http.*;
27
28 import org.apache.log4j.Logger;
29
30 import org.enhydra.barracuda.core.helper.state.*;
31 import org.enhydra.barracuda.plankton.data.*;
32
33 //csc_010404_1 - revamped to extend from servlet package's HttpServletRequestWrapper
34
/**
35  * <p>This class acts as a thin wrapper around a ServletRequest. Most calls
36  * are simply passed through to the underlying request object. This object
37  * does however, expose a method which allows you to set parameters in
38  * the request object. This was necessary for cases where we needed to
39  * be able to do a POST, save the parameters somewhere, and then do a GET
40  * and reconstitute the parameters from that.
41  *
42  * <p>When you instantiate this object, it will automatically check the
43  * clients session to see if there are any parameter state information that
44  * needs to be reconstituted into the current request.
45  */

46 public class DefaultServletRequestWrapper extends HttpServletRequestWrapper implements BarracudaServletRequestWrapper {
47
48     protected static final Logger logger = Logger.getLogger(DefaultServletRequestWrapper.class.getName());
49
50     HttpServletRequest req = null;
51     List paramList = null;
52     String method = null;
53     
54     /**
55      * Create a DefaultServletRequestWrapper around some other
56      * HttpServletRequest impl. The wrapper adds the ability to
57      * add/remove parameter values.
58      *
59      * @param ireq the underlying HttpServletRequest
60      */

61     public DefaultServletRequestWrapper(HttpServletRequest ireq) {
62         super(ireq);
63         setRequest(ireq);
64     }
65
66
67     //--------------- BarracudaServletRequestWrapper -------------
68
/**
69      * Set the underlying request method.
70      *
71      * @param method the underlying request method (GET, POST, etc)
72      */

73     public void setMethod(String imethod) {
74         method = imethod;
75     }
76
77     /**
78      * Get the underlying request method.
79      */

80     public String getMethod() {
81         return (method!=null ? method : req.getMethod());
82     }
83
84     /**
85      * Set a given parameter (note that this is backed by a hashmap,
86      * so the structure is slightly different than that of the
87      * underlying ServletRequest which allows multiple paramters
88      * with the same name). This means that if you attempt to
89      * set a parameter whose key already exists you will effectively
90      * overwrite the existing value.
91      *
92      * @param name the key name for the parameter
93      * @param value the value associated with the given key
94      */

95     public void addParameter(String name, String value) {
96         //eliminate the obvious
97
if (name==null) return;
98
99         //make sure the paramList is initialized
100
if (paramList==null) setupParamList();
101
102         //finally store the new value
103
paramList.add(new Param(name, value));
104     }
105
106     /**
107      * Returns the value of a request parameter as a String, or
108      * null if the parameter does not exist.
109      *
110      * @param name the key name for the parameter
111      * @return the parameter value associated with a key name
112      */

113     public String getParameter(String name) {
114         //eliminate the obvious
115
if (name==null) return null;
116
117         //if paramList exists, get the value from there
118
if (paramList!=null) {
119             Iterator it = paramList.iterator();
120             while (it.hasNext()) {
121                 Param param = (Param) it.next();
122                 if (param.getKey().equals(name)) return param.getValue();
123             }
124             return null;
125
126         //otherwise just delegate to the underlying request
127
} else {
128 //merg_092901.1_start
129
//This patch submitted by Merg [merg@merg.be]. The basic problem
130
//is that some servlet containers do not accurately report all
131
//parameters submitted with the request. If the request is a post,
132
//and there were additional parameters submitted in the url, the
133
//additional params are sometimes not returned (ie. on ATG Dynamo).
134
//SO...if the value comes back null, then actually check the
135
//query string for them.
136
// return req.getParameter(name);
137
String s = req.getParameter(name);
138             if (s==null) {
139                 // Still no parameter found, check the queryString
140
String queryString = req.getQueryString();
141                 if (queryString!=null) {
142 //csc_110102.1_start - fix deprecation issues
143
//csc_110402.1 - revert
144
//jrk_20030731.1_start - catch runtime exceptions in the decode() method
145
try {
146                         queryString = java.net.URLDecoder.decode(queryString);
147                     } catch (Exception e) {
148                         logger.warn("failed to decode queryString, but allowing to continue", e);
149                     }
150 //jrk_20030731.1_end
151
/*
152                     try {
153                         queryString = java.net.URLDecoder.decode(queryString, "UTF-8");
154                     } catch (UnsupportedEncodingException e) {
155                         System.out.println("Encoding Exception: "+e);
156                         e.printStackTrace();
157                     }
158 */

159 //csc_110102.1_end
160
//jrk_20030828.1_start
161
// int startPos = queryString.indexOf(name + "="); //need "=" to know it is a parameter name as opposed to a value
162
// int endPos = -1;
163

164                     //need "=" to know it is a parameter name as opposed to a value
165
// also need '&' to make difference between id and aaa_id for example
166
// if is first param, will be checked in different place
167
int startPos = queryString.indexOf("&"+name + "=");
168                     int endPos = -1;
169
170                     if (startPos == -1) {
171                         // not found inside parameter list, try find as first
172
if (queryString.startsWith(name+"=")) {
173                             startPos = 0;
174                         }
175                     } else {
176                         // skip '&'
177
startPos++;
178                     }
179 //jrk_20030828.1_end
180

181                     if (startPos!=-1) {
182                         startPos = startPos + name.length() + 1;
183                         endPos = queryString.indexOf("&", startPos);
184
185                         if (endPos==-1) {
186                             s = queryString.substring(startPos);
187                         }
188                         else {
189                             s = queryString.substring(startPos, endPos);
190                         }
191                     }
192                 }
193             }
194             return s;
195 //merg_092901.1_end
196
}
197     }
198
199     /**
200      * Returns an Enumeration of String objects containing the
201      * names of the parameters contained in this request.
202      *
203      * @return an Enumeration of all the parameter names
204      */

205     public Enumeration getParameterNames() {
206         //if paramList is not null, get the enum from there
207
if (paramList!=null) {
208             return new LocalEnumerator(paramList);
209
210         //otherwise just delegate to the underlying request
211
} else {
212             return req.getParameterNames();
213         }
214     }
215
216     /**
217      * Returns a java.util.Map of the parameters of this request.
218      * Request parameters are extra information sent with the request.
219      * For HTTP servlets, parameters are contained in the query string
220      * or posted form data.
221      */

222     public Map getParameterMap() {
223         //if paramList exists, get the value from there
224
if (paramList!=null) {
225             Iterator it = paramList.iterator();
226             Map paramMap = new HashMap(paramList.size());
227 // Map paramMap = new TreeMap();
228
//csc_120602.1_start
229
/*
230 Ok, so the problem with this is that
231 a) the values should be stored as a String[], and
232 b) if you have multiple values for a given its not going to work as implemented
233             while (it.hasNext()) {
234                 Param param = (Param) it.next();
235                 paramMap.put(param.getKey(), param.getValue());
236 */

237             //populate the paramMap with key/val pairs
238
while (it.hasNext()) {
239                 Param param = (Param) it.next();
240                 String key = param.getKey();
241                 List valList = (List) paramMap.get(key);
242                 if (valList==null) {
243                     valList = new ArrayList(10);
244                     paramMap.put(key, valList);
245                 }
246                 valList.add(param.getValue());
247             }
248
249             //now run back through the paramMap and convert all the
250
//List values into String[] (to conform with servlet spec)
251
it = paramMap.keySet().iterator();
252             while (it.hasNext()) {
253                 Object key = it.next();
254                 List valList = (List) paramMap.get(key);
255 //csc_010404_1_start
256
//Not sure why, but all of a sudden this code was erring with a Class cast exception -
257
//List seems to return an Object[] and that can't be cast to a String[] even if all the items
258
//in the list are Strings
259
// paramMap.put(key, (String[]) valList.toArray());
260
int idx = -1;
261                 String[] valArr = new String[valList.size()];
262                 Iterator it2 = valList.iterator();
263                 while (it2.hasNext()) {
264                     valArr[++idx] = (String) it2.next();
265                 }
266                 paramMap.put(key, valArr);
267 //csc_010404_1_end
268
}
269 //csc_120602.1_end
270

271             return paramMap;
272
273         //otherwise just delegate to the underlying request
274
} else {
275             return req.getParameterMap();
276         }
277     }
278     //csc_013102.1_end
279

280     /**
281      * Returns an array of String objects containing all of the
282      * values the given request parameter has, or null if the
283      * parameter does not exist.
284      *
285      * @param name the key name for the parameter
286      * @return an array of Strings for the given key name
287      */

288     public String[] getParameterValues(String name) {
289         //eliminate the obvious
290
if (name==null) return null;
291
292         //if paramList is not null, build the array from there
293
if (paramList!=null) {
294             List valueList = new ArrayList(paramList.size());
295             Iterator it = paramList.iterator();
296             while (it.hasNext()) {
297                 Param param = (Param) it.next();
298                 if (param.getKey().equals(name)) valueList.add(param.getValue());
299             }
300             int idx = -1;
301             String[] valueArr = new String[valueList.size()];
302             it = valueList.iterator();
303             while (it.hasNext()) {
304                 valueArr[++idx] = (String) it.next();
305             }
306             if (valueArr.length==0) return null;
307             else return valueArr;
308
309         //otherwise just delegate to the underlying request
310
} else {
311             return req.getParameterValues(name);
312         }
313     }
314
315     /**
316      * Remove the first parameter whose key matches the specified name
317      *
318      * @param name the key name for the parameter
319      */

320     public void removeParameter(String name) {
321         //eliminate the obvious
322
if (name==null) return;
323
324         //make sure the paramList is initialized
325
if (paramList==null) setupParamList();
326
327         //finally remove the first occurence of the parameter
328
for (int i=0, max=paramList.size(); i<max; i++) {
329             Param param = (Param) paramList.get(i);
330             if (param.getKey().equals(name)) {
331                 paramList.remove(i);
332                 break;
333             }
334         }
335
336     }
337
338     /**
339      * Remove all parameters for a specified name
340      *
341      * @param name the key name for the parameter
342      */

343     public void removeAllParameters(String name) {
344         //eliminate the obvious
345
if (name==null) return;
346
347         //make sure the paramList is initialized
348
if (paramList==null) setupParamList();
349
350         //finally remove the all occurences of the parameter
351
for (int i=paramList.size()-1; i>=0; i--) {
352             Param param = (Param) paramList.get(i);
353             if (param.getKey().equals(name)) paramList.remove(i);
354         }
355     }
356
357     /**
358      * Reset the parameter values to their original state
359      * (ie. the actual values in the request)
360      */

361     public void resetParameters() {
362         paramList=null;
363     }
364
365     /**
366      * Get the underlying servlet request. The only reason you
367      * should ever have to do this is if you are trying to forward
368      * a request. Some containers check to make sure that the
369      * request object being forwarded is an instance of their own
370      * implementation...
371      *
372      * @return the underlying servlet request object
373      */

374     public HttpServletRequest getCoreRequest() {
375         return req;
376     }
377
378
379     //--------------- ServletRequestWrapper ----------------------
380
/**
381      * Set the underlying request object.
382      *
383      * @param ireq the underlying HttpServletRequest
384      */

385     public void setRequest(ServletRequest ireq) {
386         super.setRequest(ireq);
387
388         if (req!=ireq && ireq instanceof HttpServletRequest) {
389             //set the reference to the req
390
req = (HttpServletRequest) ireq;
391         
392             //reconstitute any param values from the user's session
393
ParamPersister.reconstituteReqParamState(this);
394         }
395     }
396
397
398
399
400     //--------------- HttpServletRequestWrapper ------------------
401

402
403
404
405
406     //-------------------- Utility stuff -------------------------
407
private void setupParamList() {
408         //eliminate the obvious (only initialize once!)
409
if (paramList!=null) return;
410
411         //create the param list
412
paramList = new ArrayList(10);
413
414         //now copy in all param values from the underlying servlet
415
//request. From this point on then, the param values will
416
//be maintained in the paramList
417
Enumeration enum = req.getParameterNames();
418         while (enum.hasMoreElements()) {
419             //get the key
420
String key = (String) enum.nextElement();
421
422             //find all values associated with the key
423
String[] vals = req.getParameterValues(key);
424             for (int i=0, max=vals.length; i<max; i++) {
425                 paramList.add(new Param(key, vals[i]));
426             }
427         }
428     }
429
430     /**
431      * This inner class implements Enumaration. It will effectively
432      * enumerate over all of the parameter key names.
433      */

434     class LocalEnumerator implements Enumeration {
435         List keyList = null;
436         Iterator it = null;
437
438         public LocalEnumerator(List iparamList) {
439             keyList = new ArrayList(iparamList.size());
440             it = iparamList.iterator();
441             while (it.hasNext()) {
442                 Param param = (Param) it.next();
443                 if (!keyList.contains(param.getKey())) keyList.add(param.getKey());
444             }
445             it = keyList.iterator();
446         }
447
448         public boolean hasMoreElements() {
449             return (it.hasNext());
450         }
451
452         public Object nextElement() {
453             return it.next();
454         }
455     }
456 }
Popular Tags