KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > ActionServletRequest


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

43 package net.jforum;
44
45 import java.io.File JavaDoc;
46 import java.io.IOException JavaDoc;
47 import java.util.Enumeration JavaDoc;
48 import java.util.HashMap JavaDoc;
49 import java.util.Iterator JavaDoc;
50 import java.util.List JavaDoc;
51 import java.util.Map JavaDoc;
52
53 import javax.servlet.http.HttpServletRequest JavaDoc;
54 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
55
56 import net.jforum.exceptions.MultipartHandlingException;
57 import net.jforum.util.legacy.commons.fileupload.FileItem;
58 import net.jforum.util.legacy.commons.fileupload.FileUploadException;
59 import net.jforum.util.legacy.commons.fileupload.disk.DiskFileItemFactory;
60 import net.jforum.util.legacy.commons.fileupload.servlet.ServletFileUpload;
61 import net.jforum.util.legacy.commons.fileupload.servlet.ServletRequestContext;
62 import net.jforum.util.preferences.ConfigKeys;
63 import net.jforum.util.preferences.SystemGlobals;
64
65 /**
66  * @author Rafael Steil
67  * @version $Id: ActionServletRequest.java,v 1.30 2006/02/12 18:14:24 rafaelsteil Exp $
68  */

69 public class ActionServletRequest extends HttpServletRequestWrapper JavaDoc
70 {
71     /**
72      * URL Patterns keeper.
73      * Represents a single URL pattern. Each pattern is composed
74      * by a name, the pattern itself, the pattern's size and the
75      * splited variables. <br><br>
76      *
77      * The pattern is expected in the form <i>var1, var2, varN</i>, in the
78      * correct order. This means that if <i>var1</i> comes first, it <b>must</b>
79      * come first in the URL. The same is valid to others.<br><br>
80      *
81      * Please note that "first" here is "first" after regular URL, which is
82      * composed by server and servlet name, in the most simple case.<br><br>
83      *
84      * <b>Example:</b><br>
85      *
86      * URL: <i>http://localhost:8080/webappName/someDir/myServlet/news/view/3.page<i>.
87      * <br>
88      * In this case, <i>http://localhost:8080/webappName/someDir/myServlet/</i> is the
89      * regular URL, the part that we don't care about. We only want the part
90      * <i>news/view/3.page</i> ( where .page is the servlet extension ).
91      * <br>For this URL, we could make the following pattern:<br><br>
92      *
93      * <i>news.view.1 = news_id</i><br><br>
94      *
95      * Here, <i>news.view.1</i> is the pattern's name, and <i>news_id</i> is
96      * the patterns itself. <br>
97      * Another example:<br><br>
98      *
99      * <i>news.view.2 = page, news_id</i><br><br>
100      *
101      * In this case we have a new var called <i>page</i>, that represents the page being seen.<br>
102      * Each entry is composed in the form:<br><br>
103      *
104      * <i>&lt;moduleName&gt;.&lt;actionName&gt;.&lt;numberOfParameters&gt; = &lt;var 1&gt;,&lt;var n&gt;</i>
105      * <br><br>
106      *
107      * Please note that module and action's name aren't pattern's composition, so
108      * don't put them there. The system will consider that the pattern only contains
109      * the variables diferent to each request ( e.g, id's ). If the pattern you're
110      * constructing doesn't have any variable, just leave it blank, like<br><br>
111      *
112      * <i>myModule.myAction.0 = </i><br><br>
113      *
114      * @author Rafael Steil
115      */

116     private static class UrlPattern
117     {
118         private String JavaDoc name;
119         private String JavaDoc value;
120         private int size;
121         private String JavaDoc[] vars;
122         
123         public UrlPattern(String JavaDoc name, String JavaDoc value)
124         {
125             this.name = name;
126             this.value = value;
127             
128             this.processPattern();
129         }
130         
131         private void processPattern()
132         {
133             String JavaDoc[] p = this.value.split(",");
134             
135             this.vars = new String JavaDoc[p.length];
136             this.size = ((((p[0]).trim()).equals("")) ? 0 : p.length);
137             
138             for (int i = 0; i < this.size; i++) {
139                 this.vars[i] = (p[i]).trim();
140             }
141         }
142
143         /**
144          * Gets the pattern name
145          *
146          * @return String with the pattern name
147          */

148         public String JavaDoc getName()
149         {
150             return this.name;
151         }
152
153         /**
154          * Get pattern's total vars
155          *
156          * @return The total
157          */

158         public int getSize()
159         {
160             return this.size;
161         }
162         
163         /**
164          * Gets the vars.
165          * The URL variables are in the correct order, which means
166          * that the first position always will be "something1", the
167          * second "something2" and so on. The system expects this
168          * order never changes from requisition to requisition.
169          *
170          * @return The vars
171          */

172         public String JavaDoc[] getVars()
173         {
174             return this.vars;
175         }
176     }
177     
178     /**
179      * Keeps a collection of <code>UrlPattern</code> objects.
180      *
181      * @author Rafael Steil
182      */

183     private static class UrlPatternCollection
184     {
185         private static HashMap JavaDoc patternsMap = new HashMap JavaDoc();
186         
187         /**
188          * Try to find a <code>UrlPattern</code> by its name.
189          *
190          * @param name The pattern name
191          * @return The <code>UrlPattern</code> object if a match was found, or <code>null</code> if not
192          */

193         public static UrlPattern findPattern(String JavaDoc name)
194         {
195             return (UrlPattern)UrlPatternCollection.patternsMap.get(name);
196         }
197         
198         /**
199          * Adds a new <code>UrlPattern</code>.
200          *
201          * @param name The pattern name
202          * @param value The pattern value
203          */

204         public static void addPattern(String JavaDoc name, String JavaDoc value)
205         {
206             UrlPatternCollection.patternsMap.put(name, new UrlPattern(name, value));
207         }
208     }
209     
210     private Map JavaDoc query;
211     private JForumContext jforumcontext;
212     
213     /**
214      * Default constructor.
215      *
216      * @param superRequest Original <code>HttpServletRequest</code> instance
217      * @throws IOException
218      */

219     public ActionServletRequest(HttpServletRequest JavaDoc superRequest) throws IOException JavaDoc
220     {
221         super(superRequest);
222
223         this.query = new HashMap JavaDoc();
224         boolean isMultipart = false;
225         
226         String JavaDoc requestType = (superRequest.getMethod()).toUpperCase();
227         String JavaDoc requestUri = superRequest.getRequestURI();
228         
229         // Remove the "jsessionid" (or similar) from the URI
230
// Probably this is not the right way to go, since we're
231
// discarting the value...
232
int index = requestUri.indexOf(';');
233         
234         if (index > -1) {
235             int lastIndex = requestUri.indexOf('?', index);
236             
237             if (lastIndex == -1) {
238                 lastIndex = requestUri.indexOf('&', index);
239             }
240             
241             if (lastIndex == -1) {
242                 requestUri = requestUri.substring(0, index);
243             }
244             else {
245                 String JavaDoc part1 = requestUri.substring(0, index);
246                 requestUri = part1 + requestUri.substring(lastIndex);
247             }
248         }
249         
250         String JavaDoc encoding = SystemGlobals.getValue(ConfigKeys.ENCODING);
251         
252         if ((("GET").equals(requestType) && (superRequest.getQueryString() == null))
253                 && requestUri.endsWith(SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION))) {
254             superRequest.setCharacterEncoding(encoding);
255             
256             requestUri = requestUri.substring(0, requestUri.length() - SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION).length());
257             
258             String JavaDoc[] urlModel = requestUri.split("/");
259             
260             // If (context name is not null) {
261
// 0: empty
262
// 1: context name
263
// 2: module
264
// 3: action
265
// 4 .. n: request dependent data
266
// } else {
267
// 0: empty
268
// 1: module
269
// 2: action
270
// 3 .. n: request dependent data
271
// }
272

273             int moduleIndex = 2;
274             int actionIndex = 3;
275             int baseLen = 4;
276             
277             String JavaDoc contextName = superRequest.getContextPath();
278             if ((contextName == null) || contextName.equals("")) {
279                 moduleIndex = 1;
280                 actionIndex = 2;
281                 baseLen = 3;
282             }
283             
284             UrlPattern url = null;
285             
286             if (urlModel.length >= baseLen) {
287                 // <moduleName>.<actionName>.<numberOfParameters>
288
url = UrlPatternCollection.findPattern(urlModel[moduleIndex]
289                     + "."
290                     + urlModel[actionIndex]
291                     + "."
292                     + (urlModel.length - baseLen));
293             }
294
295             if (url != null) {
296                 // We have parameters?
297
if (url.getSize() >= urlModel.length - baseLen) {
298                     for (int i = 0; i < url.getSize(); i++) {
299                         this.addParameter(url.getVars()[i], urlModel[i + baseLen]);
300                     }
301                 }
302                 
303                 this.addParameter("module", urlModel[moduleIndex]);
304                 this.addParameter("action", urlModel[actionIndex]);
305             }
306             else {
307                 this.addParameter("module", null);
308                 this.addParameter("action", null);
309             }
310         }
311         else if (("POST").equals(requestType)) {
312             isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(superRequest));
313             if (isMultipart) {
314                 String JavaDoc tmpDir = SystemGlobals.getApplicationPath() + "/" + SystemGlobals.getValue(ConfigKeys.TMP_DIR);
315                 ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(100 * 1024, new File JavaDoc(tmpDir)));
316                 upload.setHeaderEncoding(encoding);
317         
318                 try {
319                     List JavaDoc items = upload.parseRequest(superRequest);
320                     for (Iterator JavaDoc iter = items.iterator(); iter.hasNext(); ) {
321                         FileItem item = (FileItem)iter.next();
322                         if (item.isFormField()) {
323                             this.query.put(item.getFieldName(), item.getString(encoding));
324                         }
325                         else {
326                             if (item.getSize() > 0) {
327                                 this.query.put(item.getFieldName(), item);
328                             }
329                         }
330                     }
331                 }
332                 catch (FileUploadException e) {
333                     throw new MultipartHandlingException("Error while processing multipart content: " + e);
334                 }
335             }
336         }
337         
338         if (isMultipart == false) {
339             superRequest.setCharacterEncoding(encoding);
340             String JavaDoc containerEncoding = SystemGlobals.getValue(ConfigKeys.DEFAULT_CONTAINER_ENCODING);
341             
342             if ("POST".equals(requestType)) {
343                 containerEncoding = encoding;
344             }
345             
346             for (Enumeration JavaDoc e = superRequest.getParameterNames(); e.hasMoreElements(); ) {
347                 String JavaDoc name = (String JavaDoc)e.nextElement();
348                 this.query.put(name, new String JavaDoc(superRequest.getParameter(name).getBytes(containerEncoding), encoding));
349             }
350         }
351     }
352
353     /**
354      * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
355      */

356     public String JavaDoc getParameter(String JavaDoc parameter)
357     {
358         return (String JavaDoc)this.query.get(parameter);
359     }
360
361     /**
362      * Gets an parameter that is a number.
363      * A call to <code>Integer#parseInt(String)</code> is made
364      * to do the conversion
365      * @param parameter The parameter name to get the value
366      * @return
367      */

368     public int getIntParameter(String JavaDoc parameter)
369     {
370         return Integer.parseInt(this.getParameter(parameter));
371     }
372     
373     /**
374      * Gets all parameters of the current request.
375      *
376      * @return <code>java.util.Map</code> with all request
377      * data.
378      */

379     public Map JavaDoc dumpRequest()
380     {
381         return this.query;
382     }
383     
384     /**
385      * Restores a request "dump".
386      *
387      * @param query A <code>java.util.Map</code> with all request
388      * data. Usually it will be the result of a previous call
389      * to @link #dumpRequest()
390      */

391     public void restoreDump(Map JavaDoc query)
392     {
393         this.query = query;
394     }
395     
396     /**
397      * Gets some request parameter as <code>Object</code>.
398      * This method may be used when you have to get some value
399      * of a <i>multipart/form-data</i> request, like a image
400      * of file. <br>
401      *
402      * @param parameter
403      * @return
404      */

405     public Object JavaDoc getObjectParameter(String JavaDoc parameter)
406     {
407         return this.query.get(parameter);
408     }
409     
410     /**
411      * Adds a new <code>UrlPattern</code>.
412      *
413      * @param name The pattern name
414      * @param value The Pattern value
415      */

416     public static void addUrlPattern(String JavaDoc name, String JavaDoc value)
417     {
418         UrlPatternCollection.addPattern(name, value);
419     }
420     
421     /**
422      * Adds a new parameter to the request.
423      *
424      * If you want to have one more, or to modify an existing one parameter,
425      * you should use this method to the job.
426      *
427      * @param name Parameter name
428      * @param value Parameter value
429      */

430     public void addParameter(String JavaDoc name, Object JavaDoc value)
431     {
432         this.query.put(name, value);
433     }
434     
435     /**
436      * Gets the <i>action</i> of the current request.
437      *
438      * An <i>Action</i> is the parameter name which specifies
439      * what next action should be done by the system. It may be
440      * add or edit a post, editing the groups, whatever. In the URL, the
441      * Action can the represented in two forms:
442      * <p>
443      * <blockquote>
444      * <code>
445      * http://www.host.com/webapp/servletName?module=groups&action=list
446      * </code>
447      * </blockquote>
448      * <p>
449      * or
450      * <p>
451      * <blockquote>
452      * <code>
453      * http://www.host.com/webapp/servletName/groups/list
454      * </code>
455      * </blockquote>
456      * <p>
457      * In both situations, the action's name is "list".
458      *
459      * @return String representing the action name
460      */

461     public String JavaDoc getAction()
462     {
463         return this.getParameter("action");
464     }
465     
466     /**
467      * Gets the <i>module</i> of the current request.
468      *
469      * A <i>Module</i> is the parameter name which specifies
470      * what module the user is requesting. It may be the group
471      * administration, the topics or anything else configured module.
472      *In the URL, the Module can the represented in two forms:
473      * <p>
474      * <blockquote>
475      * <code>
476      * http://www.host.com/webapp/servletName?module=groups&action=list
477      * </code>
478      * </blockquote>
479      * <p>
480      * or
481      * <p>
482      * <blockquote>
483      * <code>
484      * http://www.host.com/webapp/servletName/groups/list
485      * </code>
486      * </blockquote>
487      * <p>
488      * In both situations, the module's name is "groups".
489      *
490      * @return String representing the module name
491      */

492     public String JavaDoc getModule()
493     {
494         return this.getParameter("module");
495     }
496     
497     public Object JavaDoc getObjectRequestParameter(String JavaDoc parameter)
498     {
499         return this.query.get(parameter);
500     }
501     
502     public JForumContext getJForumContext()
503     {
504         return this.jforumcontext;
505     }
506     
507     public void setJForumContext(JForumContext jforumcontext)
508     {
509         this.jforumcontext = jforumcontext;
510     }
511 }
512
Popular Tags