KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > util > core > RequestUtil


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 com.blandware.atleap.webapp.util.core;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.webapp.taglib.core.grid.GridTag;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.apache.commons.validator.GenericValidator;
23
24 import javax.servlet.http.Cookie JavaDoc;
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27 import java.io.UnsupportedEncodingException JavaDoc;
28 import java.net.URLDecoder JavaDoc;
29 import java.net.URLEncoder JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Enumeration JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Set JavaDoc;
37
38
39 /**
40  * <p>RequestUtil utility class Good ol' copy-n-paste from <a
41  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt">
42  * http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt</a>
43  * which is referenced in the following article: <a
44  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html">
45  * http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html</a>
46  * </p>
47  * Added some methods by Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
48  *
49  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
50  * @version $Revision: 1.7 $ $Date: 2005/11/21 10:39:13 $
51  */

52 public class RequestUtil {
53     private static final String JavaDoc STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed";
54     protected transient final Log log = LogFactory.getLog(RequestUtil.class);
55
56
57     /**
58      * Creates query String from request body parameters
59      *
60      * @param request The request that will supply parameters
61      * @return Query string corresponding to that request parameters
62      */

63     public static String JavaDoc getRequestParameters(HttpServletRequest JavaDoc request) {
64         // set the ALGORIGTHM as defined for the application
65
//ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
66
Map JavaDoc m = request.getParameterMap();
67         return createQueryStringFromMap(m, "&").toString();
68     }
69
70
71     /**
72      * Creates map of request parameters from given query string
73      *
74      * @param queryString Query string to get parameters from
75      * @return Map with request parameters mapped to their values
76      */

77     public static Map JavaDoc getRequestParametersFromString(String JavaDoc queryString) {
78         HashMap JavaDoc parameterMap = new HashMap JavaDoc();
79
80         for ( int k = 0; k < queryString.length(); ) {
81             int ampPos = queryString.indexOf('&', k);
82             if ( ampPos == -1 ) {
83                 ampPos = queryString.length();
84             }
85             String JavaDoc parameter = queryString.substring(k, ampPos);
86             int equalsSignPos = parameter.indexOf('=');
87             if (equalsSignPos != -1) {
88                 String JavaDoc key = parameter.substring(0, equalsSignPos);
89                 String JavaDoc value = parameter.substring(equalsSignPos + 1);
90                 try {
91                     key = URLDecoder.decode(key, Constants.DEFAULT_ENCODING);
92                     value = URLDecoder.decode(value, Constants.DEFAULT_ENCODING);
93                     parameterMap.put(key, mergeValues(parameterMap.get(key), value));
94                 } catch ( UnsupportedEncodingException JavaDoc e ) {
95                     // do nothing
96
}
97             }
98             k = ampPos + 1;
99         }
100
101         return parameterMap;
102     }
103
104
105     /**
106      * Creates a map of request parameters from URI.
107      *
108      * @param uri An address to extract request parameters from
109      * @return map of request parameters
110      */

111     public static Map JavaDoc getRequestParametersFromUri(String JavaDoc uri) {
112         if (GenericValidator.isBlankOrNull(uri)) {
113             return new HashMap JavaDoc();
114         }
115
116         int qSignPos = uri.indexOf('?');
117         if (qSignPos == -1) {
118             return new HashMap JavaDoc();
119         }
120
121         return RequestUtil.getRequestParametersFromString(uri.substring(qSignPos + 1));
122     }
123
124
125     /**
126      * Extracts a base address from URI (that is, part of address before '?')
127      *
128      * @param uri An address to extract base address from
129      * @return base address
130      */

131     public static String JavaDoc getBaseFromUri(String JavaDoc uri) {
132         if (GenericValidator.isBlankOrNull(uri)) {
133             return "";
134         }
135
136         int qSignPos = uri.indexOf('?');
137         if (qSignPos == -1) {
138             return uri;
139         }
140
141         return uri.substring(0, qSignPos);
142     }
143
144
145     /**
146      * Builds a query string from a given map of parameters
147      *
148      * @param m A map of parameters
149      * @param ampersand String to use for ampersands (e.g. "&" or "&amp;" )
150      * @param encode Whether or not to encode non-ASCII characters
151      * @return query string (with no leading "?")
152      */

153     public static StringBuffer JavaDoc createQueryStringFromMap(Map JavaDoc m, String JavaDoc ampersand, boolean encode) {
154         StringBuffer JavaDoc result = new StringBuffer JavaDoc("");
155         Set JavaDoc entrySet = m.entrySet();
156         Iterator JavaDoc entrySetIterator = entrySet.iterator();
157
158         while ( entrySetIterator.hasNext() ) {
159             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entrySetIterator.next();
160             Object JavaDoc o = entry.getValue();
161
162             if ( o == null ) {
163                 append(entry.getKey(), "", result, ampersand, encode);
164             } else if ( o instanceof String JavaDoc ) {
165                 append(entry.getKey(), o, result, ampersand, encode);
166             } else if ( o instanceof String JavaDoc[] ) {
167                 String JavaDoc[] values = (String JavaDoc[]) o;
168
169                 for ( int i = 0; i < values.length; i++ ) {
170                     append(entry.getKey(), values[i], result, ampersand, encode);
171                 }
172             } else {
173                 append(entry.getKey(), o, result, ampersand, encode);
174             }
175         }
176
177         return result;
178     }
179
180     /**
181      * Builds a query string from a given map of parameters
182      *
183      * @param m A map of parameters
184      * @param ampersand String to use for ampersands (e.g. "&" or "&amp;" )
185      * @return query string (with no leading "?")
186      */

187     public static StringBuffer JavaDoc createQueryStringFromMap(Map JavaDoc m, String JavaDoc ampersand) {
188         return createQueryStringFromMap(m, ampersand, true);
189     }
190
191     /**
192      * Append parameters to base URI.
193      *
194      * @param uri An address that is base for adding params
195      * @param params A map of parameters
196      * @return resulting URI
197      */

198     public static String JavaDoc appendParams(String JavaDoc uri, Map JavaDoc params) {
199         String JavaDoc delim = (uri.indexOf('?') == -1) ? "?" : "&";
200         return uri + delim + RequestUtil.createQueryStringFromMap(params, "&").toString();
201     }
202
203     /**
204      * Removes request parameters added by different grid tags
205      *
206      * @param parameterMap Parameter map to remove parameters from
207      * @return Map with additional parameters removed
208      */

209     public static Map JavaDoc prepareParameterMap(Map JavaDoc parameterMap) {
210         parameterMap.remove("clearFilter");
211         parameterMap.remove("clearAllFilters");
212         parameterMap.remove("sortField");
213         parameterMap.remove("pageNumber");
214         parameterMap.remove("gridName");
215         return parameterMap;
216     }
217
218     /**
219      * Creates page URL from page url and request parameters specified in parent grid tag
220      *
221      * @param parentGridTag The grid tag
222      * @return URL for this grid tag
223      */

224     public static String JavaDoc getPageUrl(GridTag parentGridTag) {
225         String JavaDoc pageUrl = parentGridTag.getPageUrl();
226         Map JavaDoc parameterMap = prepareParameterMap(parentGridTag.getParameterMap());
227         String JavaDoc queryString = RequestUtil.createQueryStringFromMap(parameterMap, "&").toString();
228         if ( queryString != null && queryString.length() != 0 ) {
229             queryString = "?" + queryString;
230         }
231         pageUrl += queryString;
232         return pageUrl;
233     }
234
235     /**
236      * Appends new key and value pair to query string
237      *
238      * @param key parameter name
239      * @param value value of parameter
240      * @param queryString existing query string
241      * @param ampersand string to use for ampersand (e.g. "&" or "&amp;")
242      * @param encode whether to encode value
243      * @return query string (with no leading "?")
244      */

245     private static StringBuffer JavaDoc append(Object JavaDoc key, Object JavaDoc value,
246                                        StringBuffer JavaDoc queryString,
247                                        String JavaDoc ampersand, boolean encode) {
248         if ( queryString.length() > 0 ) {
249             queryString.append(ampersand);
250         }
251
252         try {
253             if ( encode ) {
254                 key = URLEncoder.encode(key.toString(), Constants.DEFAULT_ENCODING);
255                 value = URLEncoder.encode(value.toString(), Constants.DEFAULT_ENCODING);
256             }
257             queryString.append(key);
258             queryString.append("=");
259             queryString.append(value);
260         } catch ( UnsupportedEncodingException JavaDoc e ) {
261             // do nothing
262
}
263         return queryString;
264     }
265
266     /**
267      * Stores request attributes in session
268      *
269      * @param aRequest the current request
270      */

271     public static void stowRequestAttributes(HttpServletRequest JavaDoc aRequest) {
272         if ( aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null ) {
273             return;
274         }
275
276         Enumeration JavaDoc e = aRequest.getAttributeNames();
277         Map JavaDoc map = new HashMap JavaDoc();
278
279         while ( e.hasMoreElements() ) {
280             String JavaDoc name = (String JavaDoc) e.nextElement();
281             map.put(name, aRequest.getAttribute(name));
282         }
283
284         aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
285     }
286
287     /**
288      * Returns request attributes from session to request
289      *
290      * @param aRequest a request to which saved in session parameters will be
291      * assigned
292      */

293     public static void reclaimRequestAttributes(HttpServletRequest JavaDoc aRequest) {
294         Map JavaDoc map =
295                 (Map JavaDoc) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
296
297         if ( map == null ) {
298             return;
299         }
300
301         Iterator JavaDoc itr = map.keySet().iterator();
302
303         while ( itr.hasNext() ) {
304             String JavaDoc name = (String JavaDoc) itr.next();
305             aRequest.setAttribute(name, map.get(name));
306         }
307
308         aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
309     }
310
311     /**
312      * Convenience method to set a cookie. The cookie gets max age set to 30 days.
313      *
314      * @param response response that will accept a cookie
315      * @param name name of the cookie to store
316      * @param value value of the cookie
317      * @param path path of the cookie
318      */

319     public static void setCookie(HttpServletResponse JavaDoc response, String JavaDoc name,
320                                  String JavaDoc value, String JavaDoc path) {
321         Log log = LogFactory.getLog(RequestUtil.class);
322
323         if ( log.isDebugEnabled() ) {
324             log.debug("Setting cookie '" + name + "' on path '" + path + "'");
325         }
326
327         Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
328         cookie.setSecure(false);
329         cookie.setPath(path);
330         cookie.setMaxAge(3600 * 24 * 30); // 30 days
331

332         response.addCookie(cookie);
333     }
334
335     /**
336      * Convenience method to get a cookie by name
337      *
338      * @param request the current request
339      * @param name the name of the cookie to find
340      * @return the cookie (if found), null if not found
341      */

342     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name) {
343         Cookie JavaDoc[] cookies = request.getCookies();
344         Cookie JavaDoc returnCookie = null;
345
346         if ( cookies == null ) {
347             return returnCookie;
348         }
349
350         for ( int i = 0; i < cookies.length; i++ ) {
351             Cookie JavaDoc thisCookie = cookies[i];
352
353             if ( thisCookie.getName().equals(name) ) {
354                 // cookies with no value do me no good!
355
if ( !thisCookie.getValue().equals("") ) {
356                     returnCookie = thisCookie;
357
358                     break;
359                 }
360             }
361         }
362
363         return returnCookie;
364     }
365
366     /**
367      * Convenience method for deleting a cookie by name
368      *
369      * @param response the current web response
370      * @param cookie the cookie to delete
371      * @param path the path on which the cookie was set (i.e. /appfuse)
372      */

373     public static void deleteCookie(HttpServletResponse JavaDoc response,
374                                     Cookie JavaDoc cookie, String JavaDoc path) {
375         if ( cookie != null ) {
376             // Delete the cookie by setting its maximum age to zero
377
cookie.setMaxAge(0);
378             cookie.setPath(path);
379             response.addCookie(cookie);
380         }
381     }
382
383     /**
384      * Convenience method to get the application's URL based on request
385      * variables.
386      *
387      * @param request the request from which the URL is calculated
388      * @return Application URL
389      */

390     public static String JavaDoc getAppURL(HttpServletRequest JavaDoc request) {
391         StringBuffer JavaDoc url = new StringBuffer JavaDoc();
392         int port = request.getServerPort();
393         if ( port < 0 ) {
394             port = 80; // Work around java.net.URL bug
395
}
396         String JavaDoc scheme = request.getScheme();
397         url.append(scheme);
398         url.append("://");
399         url.append(request.getServerName());
400         if ( (scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443)) ) {
401             url.append(':');
402             url.append(port);
403         }
404         url.append(request.getContextPath());
405         return url.toString();
406     }
407
408     /**
409      * Merges values into one array. Instances of <code>java.lang.String</code>,
410      * <code>java.lang.String[]</code> and <code>java.util.Collection</code> are supported
411      * both in <code>v1</code> and <code>v2</code> arguments.
412      *
413      * @param v1 First object to merge
414      * @param v2 Second object to merge
415      * @return Array contains merged objects
416      */

417     public static String JavaDoc[] mergeValues(Object JavaDoc v1, Object JavaDoc v2) {
418         String JavaDoc[] values1 = null;
419         String JavaDoc[] values2 = null;
420
421         // get first array of values
422
if ( v1 == null ) {
423             values1 = new String JavaDoc[0];
424         } else if ( v1 instanceof String JavaDoc[] ) {
425             values1 = (String JavaDoc[]) v1;
426         } else if ( v1 instanceof Collection JavaDoc ) {
427             Collection JavaDoc c = (Collection JavaDoc) v1;
428             values1 = (String JavaDoc[]) new ArrayList JavaDoc(c).toArray(new String JavaDoc[0]);
429         } else {
430             values1 = new String JavaDoc[]{String.valueOf(v1)};
431         }
432
433         // get second array of values
434
if ( v2 == null ) {
435             values2 = new String JavaDoc[0];
436         } else if ( v2 instanceof String JavaDoc[] ) {
437             values2 = (String JavaDoc[]) v2;
438         } else if ( v2 instanceof Collection JavaDoc ) {
439             Collection JavaDoc c = (Collection JavaDoc) v2;
440             values2 = (String JavaDoc[]) new ArrayList JavaDoc(c).toArray(new String JavaDoc[0]);
441         } else {
442             values2 = new String JavaDoc[]{String.valueOf(v2)};
443         }
444
445         // merge arrays
446
String JavaDoc[] result = new String JavaDoc[values1.length + values2.length];
447         System.arraycopy(values1, 0, result, 0, values1.length);
448         System.arraycopy(values2, 0, result, values1.length, values2.length);
449
450         return result;
451     }
452 }
453
Popular Tags