KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > util > RequestUtil


1 package org.roller.presentation.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 import javax.servlet.http.Cookie JavaDoc;
9 import javax.servlet.http.HttpServletRequest JavaDoc;
10 import javax.servlet.http.HttpServletResponse JavaDoc;
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.apache.struts.taglib.TagUtils;
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> which
19  * 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 {
25     private static final String JavaDoc STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed";
26     private transient static Log log = LogFactory.getLog(RequestUtil.class);
27
28     /**
29      * Creates query String from request body parameters
30      */

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

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

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

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

140     public static void reclaimRequestAttributes(HttpServletRequest JavaDoc aRequest)
141     {
142         Map JavaDoc map = (Map JavaDoc) aRequest.getSession().getAttribute(
143                         STOWED_REQUEST_ATTRIBS);
144         if (map == null)
145         {
146             return;
147         }
148         Iterator JavaDoc itr = map.keySet().iterator();
149         while (itr.hasNext())
150         {
151             String JavaDoc name = (String JavaDoc) itr.next();
152             aRequest.setAttribute(name, map.get(name));
153         }
154         aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
155     }
156
157     /**
158      * Convenience method to set a cookie
159      *
160      * @param response
161      * @param name
162      * @param value
163      * @param path
164      */

165     public static void setCookie(HttpServletResponse JavaDoc response, String JavaDoc name,
166                     String JavaDoc value, String JavaDoc path)
167     {
168         if (log.isDebugEnabled())
169         {
170             log.debug("Setting cookie '" + name + "' on path '" + path + "'");
171         }
172         Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
173         cookie.setSecure(false);
174         // if path is nothing, use "/" so remember me will work
175
// when installed as root app
176
cookie.setPath((path.length() == 0) ? "/" : path);
177         cookie.setMaxAge(3600 * 24 * 30); // 30 days
178
response.addCookie(cookie);
179     }
180
181     /**
182      * Convenience method to get a cookie by name
183      *
184      * @param request
185      * the current request
186      * @param name
187      * the name of the cookie to find
188      *
189      * @return the cookie (if found), null if not found
190      */

191     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name)
192     {
193         Cookie JavaDoc[] cookies = request.getCookies();
194         Cookie JavaDoc returnCookie = null;
195         if (cookies == null)
196         {
197             return returnCookie;
198         }
199         for (int i = 0; i < cookies.length; i++)
200         {
201             Cookie JavaDoc thisCookie = cookies[i];
202             if (thisCookie.getName().equals(name))
203             {
204                 // cookies with no value do me no good!
205
if (!thisCookie.getValue().equals(""))
206                 {
207                     returnCookie = thisCookie;
208                     break;
209                 }
210             }
211         }
212         return returnCookie;
213     }
214
215     /**
216      * Convenience method for deleting a cookie by name
217      *
218      * @param response
219      * the current web response
220      * @param cookie
221      * the cookie to delete
222      * @param path
223      * the path on which the cookie was set (i.e. /appfuse)
224      */

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

241     public static String JavaDoc getAppURL(HttpServletRequest JavaDoc request)
242     {
243         StringBuffer JavaDoc url = new StringBuffer JavaDoc();
244         int port = request.getServerPort();
245         if (port < 0)
246         {
247             port = 80; // Work around java.net.URL bug
248
}
249         String JavaDoc scheme = request.getScheme();
250         url.append(scheme);
251         url.append("://");
252         url.append(request.getServerName());
253         if ((scheme.equals("http") && (port != 80))
254                         || (scheme.equals("https") && (port != 443)))
255         {
256             url.append(':');
257             url.append(port);
258         }
259         return url.toString();
260     }
261 }
Popular Tags