KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > ui > core > util > RequestUtil


1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. The ASF licenses this file to You
4 * under the Apache License, Version 2.0 (the "License"); you may not
5 * 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. For additional information regarding
15 * copyright in this work, please see the NOTICE file in the top level
16 * directory of this distribution.
17 */

18 package org.apache.roller.ui.core.util;
19
20 import java.util.Enumeration JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.Set JavaDoc;
25 import javax.servlet.http.Cookie JavaDoc;
26 import javax.servlet.http.HttpServletRequest JavaDoc;
27 import javax.servlet.http.HttpServletResponse JavaDoc;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.struts.taglib.TagUtils;
31
32 /**
33  * RequestUtil utility class Good ol' copy-n-paste from <a
34  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt">
35  * http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt </a> which
36  * is referenced in the following article: <a
37  * HREF="http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html">
38  * http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html </a>
39  */

40 public class RequestUtil
41 {
42     private static final String JavaDoc STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed";
43     private transient static Log log = LogFactory.getLog(RequestUtil.class);
44
45     /**
46      * Creates query String from request body parameters
47      */

48     public static String JavaDoc getRequestParameters(HttpServletRequest JavaDoc aRequest)
49     {
50         // set the ALGORIGTHM as defined for the application
51
//ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
52
Map JavaDoc m = aRequest.getParameterMap();
53         return createQueryStringFromMap(m, "&").toString();
54     }
55
56     /**
57      * Builds a query string from a given map of parameters
58      *
59      * @param m
60      * A map of parameters
61      * @param ampersand
62      * String to use for ampersands (e.g. "&" or "&amp;" )
63      *
64      * @return query string (with no leading "?")
65      */

66     public static StringBuffer JavaDoc createQueryStringFromMap(Map JavaDoc m, String JavaDoc ampersand)
67     {
68         StringBuffer JavaDoc aReturn = new StringBuffer JavaDoc("");
69         Set JavaDoc aEntryS = m.entrySet();
70         Iterator JavaDoc aEntryI = aEntryS.iterator();
71         while (aEntryI.hasNext())
72         {
73             Map.Entry JavaDoc aEntry = (Map.Entry JavaDoc) aEntryI.next();
74             Object JavaDoc o = aEntry.getValue();
75             if (o == null)
76             {
77                 append(aEntry.getKey(), "", aReturn, ampersand);
78             }
79             else if (o instanceof String JavaDoc)
80             {
81                 append(aEntry.getKey(), o, aReturn, ampersand);
82             }
83             else if (o instanceof String JavaDoc[])
84             {
85                 String JavaDoc[] aValues = (String JavaDoc[]) o;
86                 for (int i = 0; i < aValues.length; i++)
87                 {
88                     append(aEntry.getKey(), aValues[i], aReturn, ampersand);
89                 }
90             }
91             else
92             {
93                 append(aEntry.getKey(), o, aReturn, ampersand);
94             }
95         }
96         return aReturn;
97     }
98
99     /**
100      * Appends new key and value pair to query string
101      *
102      * @param key
103      * parameter name
104      * @param value
105      * value of parameter
106      * @param queryString
107      * existing query string
108      * @param ampersand
109      * string to use for ampersand (e.g. "&" or "&amp;")
110      *
111      * @return query string (with no leading "?")
112      */

113     private static StringBuffer JavaDoc append(Object JavaDoc key, Object JavaDoc value,
114                     StringBuffer JavaDoc queryString, String JavaDoc ampersand)
115     {
116         if (queryString.length() > 0)
117         {
118             queryString.append(ampersand);
119         }
120         TagUtils tagUtils = TagUtils.getInstance();
121         // Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4
122
// compliant
123
queryString.append(tagUtils.encodeURL(key.toString()));
124         queryString.append("=");
125         queryString.append(tagUtils.encodeURL(value.toString()));
126         return queryString;
127     }
128
129     /**
130      * Stores request attributes in session
131      *
132      * @param aRequest
133      * the current request
134      */

135     public static void stowRequestAttributes(HttpServletRequest JavaDoc aRequest)
136     {
137         if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null)
138         {
139             return;
140         }
141         Enumeration JavaDoc e = aRequest.getAttributeNames();
142         Map JavaDoc map = new HashMap JavaDoc();
143         while (e.hasMoreElements())
144         {
145             String JavaDoc name = (String JavaDoc) e.nextElement();
146             map.put(name, aRequest.getAttribute(name));
147         }
148         aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
149     }
150
151     /**
152      * Returns request attributes from session to request
153      *
154      * @param aRequest
155      * DOCUMENT ME!
156      */

157     public static void reclaimRequestAttributes(HttpServletRequest JavaDoc aRequest)
158     {
159         Map JavaDoc map = (Map JavaDoc) aRequest.getSession().getAttribute(
160                         STOWED_REQUEST_ATTRIBS);
161         if (map == null)
162         {
163             return;
164         }
165         Iterator JavaDoc itr = map.keySet().iterator();
166         while (itr.hasNext())
167         {
168             String JavaDoc name = (String JavaDoc) itr.next();
169             aRequest.setAttribute(name, map.get(name));
170         }
171         aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
172     }
173
174     /**
175      * Convenience method to set a cookie
176      *
177      * @param response
178      * @param name
179      * @param value
180      * @param path
181      */

182     public static void setCookie(HttpServletResponse JavaDoc response, String JavaDoc name,
183                     String JavaDoc value, String JavaDoc path)
184     {
185         if (log.isDebugEnabled())
186         {
187             log.debug("Setting cookie '" + name + "' on path '" + path + "'");
188         }
189         Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
190         cookie.setSecure(false);
191         // if path is nothing, use "/" so remember me will work
192
// when installed as root app
193
cookie.setPath((path.length() == 0) ? "/" : path);
194         cookie.setMaxAge(3600 * 24 * 30); // 30 days
195
response.addCookie(cookie);
196     }
197
198     /**
199      * Convenience method to get a cookie by name
200      *
201      * @param request
202      * the current request
203      * @param name
204      * the name of the cookie to find
205      *
206      * @return the cookie (if found), null if not found
207      */

208     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name)
209     {
210         Cookie JavaDoc[] cookies = request.getCookies();
211         Cookie JavaDoc returnCookie = null;
212         if (cookies == null)
213         {
214             return returnCookie;
215         }
216         for (int i = 0; i < cookies.length; i++)
217         {
218             Cookie JavaDoc thisCookie = cookies[i];
219             if (thisCookie.getName().equals(name))
220             {
221                 // cookies with no value do me no good!
222
if (!thisCookie.getValue().equals(""))
223                 {
224                     returnCookie = thisCookie;
225                     break;
226                 }
227             }
228         }
229         return returnCookie;
230     }
231
232     /**
233      * Convenience method for deleting a cookie by name
234      *
235      * @param response
236      * the current web response
237      * @param cookie
238      * the cookie to delete
239      * @param path
240      * the path on which the cookie was set (i.e. /appfuse)
241      */

242     public static void deleteCookie(HttpServletResponse JavaDoc response,
243                     Cookie JavaDoc cookie, String JavaDoc path)
244     {
245         if (cookie != null)
246         {
247             // Delete the cookie by setting its maximum age to zero
248
cookie.setMaxAge(0);
249             cookie.setPath(path);
250             response.addCookie(cookie);
251         }
252     }
253
254     /**
255      * Convenience method to get the application's URL based on request
256      * variables.
257      */

258     public static String JavaDoc getAppURL(HttpServletRequest JavaDoc request)
259     {
260         StringBuffer JavaDoc url = new StringBuffer JavaDoc();
261         int port = request.getServerPort();
262         if (port < 0)
263         {
264             port = 80; // Work around java.net.URL bug
265
}
266         String JavaDoc scheme = request.getScheme();
267         url.append(scheme);
268         url.append("://");
269         url.append(request.getServerName());
270         if ((scheme.equals("http") && (port != 80))
271                         || (scheme.equals("https") && (port != 443)))
272         {
273             url.append(':');
274             url.append(port);
275         }
276         return url.toString();
277     }
278 }
Popular Tags