KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > controller > SecureRequestUtils


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.controller;
66
67 import com.jcorporate.expresso.core.misc.URLUTF8Encoder;
68
69 import javax.servlet.http.HttpServletRequest JavaDoc;
70 import java.util.Enumeration JavaDoc;
71 import java.util.HashMap JavaDoc;
72 import java.util.Iterator JavaDoc;
73 import java.util.List JavaDoc;
74 import java.util.Map JavaDoc;
75 import java.util.Set JavaDoc;
76
77 /**
78  * Extended the Struts' <code>RequestUtils</code> to add additional
79  * utility methods.
80  *
81  * @author Max Cooper, Steve Ditlinger,Prakash Malani eBuilt Inc.
82  */

83 public class SecureRequestUtils {
84     /**
85      * The message resources.
86      */

87 // protected static MessageResources messages =
88
// MessageResources.getMessageResources( "org.apache.struts.taglib.html.LocalStrings" ) ;
89

90     private static final String JavaDoc HTTP = "http";
91     private static final String JavaDoc HTTPS = "https";
92     private static final String JavaDoc STD_HTTP_PORT = "80";
93     private static final String JavaDoc STD_HTTPS_PORT = "443";
94
95     private static final String JavaDoc STOWED_REQUEST_ATTRIBS =
96             "ssl.redirect.attrib.stowed";
97
98
99     /**
100      * Builds the protocol, server name, and port portion of the new URL
101      *
102      * @param request The current request
103      * @param desiredScheme The scheme (http or https) to be used in the new URL
104      * @param desiredPort The port number to be used in th enew URL
105      * @return The new URL as a StringBuffer
106      */

107     private static StringBuffer JavaDoc startNewUrlString(HttpServletRequest JavaDoc request,
108                                                   String JavaDoc desiredScheme,
109                                                   String JavaDoc desiredPort) {
110         StringBuffer JavaDoc url = new StringBuffer JavaDoc(128);
111         String JavaDoc serverName = request.getServerName();
112         url.append(desiredScheme).append("://").append(serverName);
113
114         if ((HTTP.equals(desiredScheme) && !STD_HTTP_PORT.equals(desiredPort)) ||
115                 (HTTPS.equals(desiredScheme) && !STD_HTTPS_PORT.equals(desiredPort))) {
116             url.append(":").append(desiredPort);
117         }
118
119         return url;
120     }
121
122
123     /**
124      * Creates query String from request body parameters
125      *
126      * @param aRequest The current request
127      * @return The created query string (with no leading "?")
128      */

129     public static String JavaDoc getRequestParameters(HttpServletRequest JavaDoc aRequest) {
130         Map JavaDoc m = aRequest.getParameterMap();
131         return createQueryStringFromMap(m, "&").toString();
132     }
133
134     /**
135      * Builds a query string from a given map of parameters
136      *
137      * @param m A map of parameters
138      * @param ampersand String to use for ampersands (e.g. "&" or "&amp;" )
139      * @return query string (with no leading "?")
140      */

141     public static StringBuffer JavaDoc createQueryStringFromMap(Map JavaDoc m, String JavaDoc ampersand) {
142         StringBuffer JavaDoc aReturn = new StringBuffer JavaDoc(128);
143         Set JavaDoc aEntryS = m.entrySet();
144         Iterator JavaDoc aEntryI = aEntryS.iterator();
145         while (aEntryI.hasNext()) {
146             Map.Entry JavaDoc aEntry = (Map.Entry JavaDoc) aEntryI.next();
147             Object JavaDoc value = aEntry.getValue();
148             String JavaDoc[] aValues = new String JavaDoc[1];
149             if (value == null) {
150                 aValues[0] = "";
151             } else if (value instanceof List JavaDoc) { // Work around for Weblogic 6.1sp1
152
List JavaDoc aList = (List JavaDoc) value;
153                 aValues = (String JavaDoc[]) aList.toArray(new String JavaDoc[aList.size()]);
154             } else if (value instanceof String JavaDoc) { // Single value from Struts tags
155
aValues[0] = (String JavaDoc) value;
156             } else { // String array, the standard returned from request.getParameterMap()
157
aValues = (String JavaDoc[]) value; // This is the standard
158
}
159             for (int i = 0; i < aValues.length; i++) {
160                 append(aEntry.getKey(), aValues[i], aReturn, ampersand);
161             }
162         }
163         return aReturn;
164     }
165
166     /**
167      * Appends new key and value pair to query string
168      *
169      * @param key parameter name
170      * @param value value of parameter
171      * @param queryString existing query string
172      * @param ampersand string to use for ampersand (e.g. "&" or "&amp;")
173      * @return query string (with no leading "?")
174      */

175     private static StringBuffer JavaDoc append(Object JavaDoc key, Object JavaDoc value, StringBuffer JavaDoc queryString, String JavaDoc ampersand) {
176         if (queryString.length() > 0) {
177             queryString.append(ampersand);
178         }
179         queryString.append(URLUTF8Encoder.encode(key.toString()));
180         queryString.append("=");
181         queryString.append(URLUTF8Encoder.encode(value.toString()));
182
183         return queryString;
184     }
185
186     /**
187      * Stores request attributes in session
188      *
189      * @param aRequest The current request
190      * @return true, if the attributes were stowed in the session,
191      * false otherwise
192      */

193     public static boolean stowRequestAttributes(HttpServletRequest JavaDoc aRequest) {
194
195         if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
196             return false;
197         }
198
199         Enumeration JavaDoc anEnum = aRequest.getAttributeNames();
200         Map JavaDoc map = new HashMap JavaDoc();
201         while (anEnum.hasMoreElements()) {
202             String JavaDoc name = (String JavaDoc) anEnum.nextElement();
203             map.put(name, aRequest.getAttribute(name));
204         }
205         aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
206         return true;
207     }
208
209
210     /**
211      * Reclaims request attributes from session to request
212      *
213      * @param aRequest The current request
214      * @param doRemove True, if the attributes should be removed after being reclaimed,
215      * false otherwise
216      */

217     public static void reclaimRequestAttributes(HttpServletRequest JavaDoc aRequest,
218                                                 boolean doRemove) {
219         Map JavaDoc map = (Map JavaDoc) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
220
221         if (map == null) {
222             return;
223         }
224
225         Iterator JavaDoc itr = map.keySet().iterator();
226         while (itr.hasNext()) {
227             String JavaDoc name = (String JavaDoc) itr.next();
228
229             aRequest.setAttribute(name, map.get(name));
230         }
231
232         if (doRemove) {
233             aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
234         }
235     }
236
237
238     /**
239      * Creates a redirect URL string if the current request should be redirected
240      *
241      * @param request current servlet request
242      * @param httpPort the http port used by the web application
243      * @param httpsPort the https port used by the web application
244      * @param isSecure True if the current request should be transmitted via SSL
245      * @return the URL to redirect to
246      */

247     static public String JavaDoc getRedirectString(HttpServletRequest JavaDoc request,
248                                            String JavaDoc httpPort,
249                                            String JavaDoc httpsPort,
250                                            boolean isSecure) {
251
252
253         // get the scheme we want to use for this page and
254
// get the scheme used in this request
255
String JavaDoc desiredScheme = isSecure ? HTTPS : HTTP;
256         String JavaDoc usingScheme = request.getScheme();
257
258         // Determine the port number we want to use
259
// and the port number we used in this request
260
String JavaDoc desiredPort = isSecure ? httpsPort : httpPort;
261         String JavaDoc usingPort = String.valueOf(request.getServerPort());
262
263         String JavaDoc urlString = null;
264
265         // Must also check ports, because of IE multiple redirect problem
266
if (!desiredScheme.equals(usingScheme) || !desiredPort.equals(usingPort)) {
267
268             urlString = buildNewUrlString(request,
269                     desiredScheme,
270                     usingScheme,
271                     desiredPort,
272                     usingPort);
273
274             // Temporarily store attributes in session
275
if (!SecureRequestUtils.stowRequestAttributes(request)) {
276                 // If request attributes already stored in session, reclaim them
277
// This is a hack for the IE multiple redirect problem
278
SecureRequestUtils.reclaimRequestAttributes(request, false);
279             }
280         } else {
281             // Retrieve attributes from session
282
SecureRequestUtils.reclaimRequestAttributes(request, true);
283         }
284
285         return urlString;
286     }
287
288
289     /**
290      * Builds the URL that we will redirect to
291      *
292      * @param request The current request
293      * @param desiredScheme The protocol (http or https) we wish to use in new URL
294      * @param usingScheme The scheme we used in the current request
295      * @param desiredPort The port number we wish to use in new URL
296      * @param usingPort The port number we used in the current request
297      * @return the URL we will redirect to, as a String
298      * @keep
299      */

300     private static String JavaDoc buildNewUrlString(HttpServletRequest JavaDoc request,
301                                             String JavaDoc desiredScheme,
302                                             String JavaDoc usingScheme,
303                                             String JavaDoc desiredPort,
304                                             String JavaDoc usingPort) {
305
306
307         StringBuffer JavaDoc url = startNewUrlString(request, desiredScheme, desiredPort);
308
309         url.append(request.getRequestURI());
310
311         return addQueryString(request, url);
312     }
313
314     /**
315      * Adds the query string, if any, to the given URL. The query string
316      * is either taken from the existing query string or
317      * generated from the posting request body parameters.
318      *
319      * @param request The current request
320      * @param url The existing URL we will add the query string to
321      * @return The URL with query string
322      * @keep
323      */

324     private static String JavaDoc addQueryString(HttpServletRequest JavaDoc request, StringBuffer JavaDoc url) {
325         // add query string, if any
326
String JavaDoc queryString = request.getQueryString();
327         if (queryString != null && queryString.length() != 0) {
328             url.append("?" + queryString);
329         } else {
330             queryString = SecureRequestUtils.getRequestParameters(request);
331             if (queryString != null && queryString.length() != 0) {
332                 url.append("?" + queryString);
333             }
334         }
335
336         return url.toString();
337     }
338 }
Popular Tags