KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jdon > util > RequestUtil


1 package com.jdon.util;
2
3 import java.util.Enumeration JavaDoc;
4 import java.util.HashMap JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import java.util.Map JavaDoc;
7 import java.util.Set JavaDoc;
8
9 import javax.servlet.http.Cookie JavaDoc;
10 import javax.servlet.http.HttpServletRequest JavaDoc;
11 import javax.servlet.http.HttpServletResponse JavaDoc;
12
13 import java.net.URLEncoder JavaDoc;
14
15 /**
16  * RequestUtil utility class Good ol' copy-n-paste from <a
17  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt">
18  * http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt</a>
19  * which is referenced in the following article: <a
20  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html">
21  * http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html</a>
22  */

23 public class RequestUtil {
24   private static final String JavaDoc STOWED_REQUEST_ATTRIBS =
25       "ssl.redirect.attrib.stowed";
26
27   private static final String JavaDoc JDON_AUTOLOGIN_COOKIE =
28       "jdon.autologin";
29
30   // "Tweakable" parameters for the cookie password encoding. NOTE: changing
31
// these and recompiling this class will essentially invalidate old cookies.
32
private final static int ENCODE_XORMASK = 0x5A;
33   private final static char ENCODE_DELIMETER = '\002';
34   private final static char ENCODE_CHAR_OFFSET1 = 'A';
35   private final static char ENCODE_CHAR_OFFSET2 = 'h';
36
37   /**
38    * Creates query String from request body parameters
39    */

40   public static String JavaDoc getRequestParameters(HttpServletRequest JavaDoc aRequest) {
41     // set the ALGORIGTHM as defined for the application
42
//ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
43
Map JavaDoc m = aRequest.getParameterMap();
44
45     return createQueryStringFromMap(m, "&").toString();
46   }
47
48   /**
49    * Builds a query string from a given map of parameters
50    *
51    * @param m A map of parameters
52    * @param ampersand String to use for ampersands (e.g. "&" or "&amp;" )
53    *
54    * @return query string (with no leading "?")
55    */

56   public static StringBuffer JavaDoc createQueryStringFromMap(Map JavaDoc m, String JavaDoc ampersand) {
57     StringBuffer JavaDoc aReturn = new StringBuffer JavaDoc("");
58     Set JavaDoc aEntryS = m.entrySet();
59     Iterator JavaDoc aEntryI = aEntryS.iterator();
60
61     while (aEntryI.hasNext()) {
62       Map.Entry JavaDoc aEntry = (Map.Entry JavaDoc) aEntryI.next();
63       Object JavaDoc o = aEntry.getValue();
64
65       if (o == null) {
66         append(aEntry.getKey(), "", aReturn, ampersand);
67       } else if (o instanceof String JavaDoc) {
68         append(aEntry.getKey(), o, aReturn, ampersand);
69       } else if (o instanceof String JavaDoc[]) {
70         String JavaDoc[] aValues = (String JavaDoc[]) o;
71
72         for (int i = 0; i < aValues.length; i++) {
73           append(aEntry.getKey(), aValues[i], aReturn, ampersand);
74         }
75       } else {
76         append(aEntry.getKey(), o, aReturn, ampersand);
77       }
78     }
79
80     return aReturn;
81   }
82
83   /**
84    * Appends new key and value pair to query string
85    *
86    * @param key parameter name
87    * @param value value of parameter
88    * @param queryString existing query string
89    * @param ampersand string to use for ampersand (e.g. "&" or "&amp;")
90    *
91    * @return query string (with no leading "?")
92    */

93   private static StringBuffer JavaDoc append(Object JavaDoc key, Object JavaDoc value,
94                                      StringBuffer JavaDoc queryString,
95                                      String JavaDoc ampersand) {
96     if (queryString.length() > 0) {
97       queryString.append(ampersand);
98     }
99
100     // Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4 compliant
101
queryString.append(encodeURL(key.toString()));
102     queryString.append("=");
103     queryString.append(encodeURL(value.toString()));
104
105     return queryString;
106   }
107
108   /**
109    * Stores request attributes in session
110    *
111    * @param aRequest the current request
112    */

113   public static void stowRequestAttributes(HttpServletRequest JavaDoc aRequest) {
114     if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
115       return;
116     }
117
118     Enumeration JavaDoc e = aRequest.getAttributeNames();
119     Map JavaDoc map = new HashMap JavaDoc();
120
121     while (e.hasMoreElements()) {
122       String JavaDoc name = (String JavaDoc) e.nextElement();
123       map.put(name, aRequest.getAttribute(name));
124     }
125
126     aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
127   }
128
129   /**
130    * Returns request attributes from session to request
131    *
132    * @param aRequest DOCUMENT ME!
133    */

134   public static void reclaimRequestAttributes(HttpServletRequest JavaDoc aRequest) {
135     Map JavaDoc map =
136         (Map JavaDoc) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
137
138     if (map == null) {
139       return;
140     }
141
142     Iterator JavaDoc itr = map.keySet().iterator();
143
144     while (itr.hasNext()) {
145       String JavaDoc name = (String JavaDoc) itr.next();
146       aRequest.setAttribute(name, map.get(name));
147     }
148
149     aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
150   }
151
152   public static void saveAuthCookie(HttpServletResponse JavaDoc response,
153                                     String JavaDoc username,
154                                     String JavaDoc password) {
155     // Save the cookie value for 1 month
156
setCookie(response, JDON_AUTOLOGIN_COOKIE,
157               encodePasswordCookie(username, password), "/");
158   }
159
160   public static String JavaDoc[] getAuthCookie(HttpServletRequest JavaDoc request) {
161     Cookie JavaDoc cookie = getCookie(request, JDON_AUTOLOGIN_COOKIE);
162     String JavaDoc[] values = null;
163     if (cookie != null) {
164       try {
165         values = decodePasswordCookie(cookie.getValue());
166       } catch (Exception JavaDoc e) {
167         System.err.print("getAuthCookie() err:" + e);
168       }
169     }
170     return values;
171   }
172
173   /**
174    * Convenience method to set a cookie
175    *
176    * @param response
177    * @param name
178    * @param value
179    * @param path
180    * @return HttpServletResponse
181    */

182   public static void setCookie(HttpServletResponse JavaDoc response, String JavaDoc name,
183                                String JavaDoc value, String JavaDoc path) {
184
185     Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
186     cookie.setSecure(false);
187     cookie.setPath(path);
188     cookie.setMaxAge(3600 * 24 * 30); // 30 days
189

190     response.addCookie(cookie);
191   }
192
193   /**
194    * Convenience method to get a cookie by name
195    *
196    * @param request the current request
197    * @param name the name of the cookie to find
198    *
199    * @return the cookie (if found), null if not found
200    */

201   public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name) {
202     Cookie JavaDoc[] cookies = request.getCookies();
203     Cookie JavaDoc returnCookie = null;
204
205     if (cookies == null) {
206       return returnCookie;
207     }
208
209     for (int i = 0; i < cookies.length; i++) {
210       Cookie JavaDoc thisCookie = cookies[i];
211
212       if (thisCookie.getName().equals(name)) {
213         // cookies with no value do me no good!
214
if (!thisCookie.getValue().equals("")) {
215           returnCookie = thisCookie;
216
217           break;
218         }
219       }
220     }
221
222     return returnCookie;
223   }
224
225   /**
226    * Convenience method for deleting a cookie by name
227    *
228    * @param response the current web response
229    * @param cookie the cookie to delete
230    *
231    * @return the modified response
232    */

233   public static void deleteCookie(HttpServletResponse JavaDoc response,
234                                   Cookie JavaDoc cookie, String JavaDoc path) {
235     if (cookie != null) {
236       // Delete the cookie by setting its maximum age to zero
237
cookie.setMaxAge(0);
238       cookie.setPath(path);
239       response.addCookie(cookie);
240     }
241   }
242
243   /**
244    * Convenience method to get the application's URL based on request
245    * variables.
246    */

247   public static String JavaDoc getAppURL(HttpServletRequest JavaDoc request) {
248     StringBuffer JavaDoc url = new StringBuffer JavaDoc();
249     int port = request.getServerPort();
250     if (port < 0) {
251       port = 80; // Work around java.net.URL bug
252
}
253     String JavaDoc scheme = request.getScheme();
254     url.append(scheme);
255     url.append("://");
256     url.append(request.getServerName());
257     if ( (scheme.equals("http") && (port != 80)) ||
258         (scheme.equals("https") && (port != 443))) {
259       url.append(':');
260       url.append(port);
261     }
262     return url.toString();
263   }
264
265   public static String JavaDoc encodeURL(String JavaDoc url) {
266     return encodeURL(url, "UTF-8");
267   }
268
269   /**
270    * Use the new URLEncoder.encode() method from Java 1.4 if available, else
271    * use the old deprecated version. This method uses reflection to find the
272    * appropriate method; if the reflection operations throw exceptions, this
273    * will return the url encoded with the old URLEncoder.encode() method.
274    * @param enc The character encoding the urlencode is performed on.
275    * @return String The encoded url.
276    */

277   public static String JavaDoc encodeURL(String JavaDoc url, String JavaDoc enc) {
278     try {
279
280       if (enc == null || enc.length() == 0) {
281         enc = "UTF-8";
282       }
283
284       return URLEncoder.encode(url, enc);
285
286     } catch (Exception JavaDoc e) {
287       System.err.print(e);
288     }
289     return null;
290   }
291
292   /**
293    * Builds a cookie string containing a username and password.<p>
294    *
295    * Note: with open source this is not really secure, but it prevents users
296    * from snooping the cookie file of others and by changing the XOR mask and
297    * character offsets, you can easily tweak results.
298    *
299    * @param username The username.
300    * @param password The password.
301    * @return String encoding the input parameters, an empty string if one of
302    * the arguments equals <code>null</code>.
303    */

304   private static String JavaDoc encodePasswordCookie(String JavaDoc username, String JavaDoc password) {
305     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
306     if (username != null && password != null) {
307       byte[] bytes = (username + ENCODE_DELIMETER + password).getBytes();
308       int b;
309
310       for (int n = 0; n < bytes.length; n++) {
311         b = bytes[n] ^ (ENCODE_XORMASK + n);
312         buf.append( (char) (ENCODE_CHAR_OFFSET1 + (b & 0x0F)));
313         buf.append( (char) (ENCODE_CHAR_OFFSET2 + ( (b >> 4) & 0x0F)));
314       }
315     }
316     return buf.toString();
317   }
318
319   /**
320    * Unrafels a cookie string containing a username and password.
321    * @param value The cookie value.
322    * @return String[] containing the username at index 0 and the password at
323    * index 1, or <code>{ null, null }</code> if cookieVal equals
324    * <code>null</code> or the empty string.
325    */

326   private static String JavaDoc[] decodePasswordCookie(String JavaDoc cookieVal) {
327
328     // check that the cookie value isn't null or zero-length
329
if (cookieVal == null || cookieVal.length() <= 0) {
330       return null;
331     }
332
333     // unrafel the cookie value
334
char[] chars = cookieVal.toCharArray();
335     byte[] bytes = new byte[chars.length / 2];
336     int b;
337     for (int n = 0, m = 0; n < bytes.length; n++) {
338       b = chars[m++] - ENCODE_CHAR_OFFSET1;
339       b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
340       bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
341     }
342     cookieVal = new String JavaDoc(bytes);
343     int pos = cookieVal.indexOf(ENCODE_DELIMETER);
344     String JavaDoc username = (pos < 0) ? "" : cookieVal.substring(0, pos);
345     String JavaDoc password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
346
347     return new String JavaDoc[] {
348         username, password};
349   }
350
351 }
352
Popular Tags