KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > servlet > ServletUtil


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.servlet;
4
5 import java.io.IOException JavaDoc;
6 import java.util.Enumeration JavaDoc;
7 import java.util.HashMap JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.Map JavaDoc;
10
11 import javax.servlet.ServletRequest JavaDoc;
12 import javax.servlet.jsp.PageContext JavaDoc;
13 import javax.servlet.http.Cookie JavaDoc;
14 import javax.servlet.http.HttpServletRequest JavaDoc;
15 import javax.servlet.http.HttpServletResponse JavaDoc;
16 import javax.servlet.http.HttpSession JavaDoc;
17
18 import jodd.util.Base64;
19
20 /**
21  * Miscellaneous servlet utilities.
22  */

23 public class ServletUtil {
24
25
26     // ---------------------------------------------------------------- multipart
27

28     /**
29      * Returns <code>true</code> if a request is multi-part request.
30      */

31     public static boolean isMultipartRequest(HttpServletRequest JavaDoc request) {
32         String JavaDoc type = request.getHeader("Content-Type");
33         return (type != null) && type.startsWith("multipart/form-data");
34     }
35
36     /**
37      * Sets the Vary response header to User-Agent to indicate that the page content
38      * varies depending on which user agent (browser) is being used.
39      */

40     public static void setBrowserVary(HttpServletResponse JavaDoc response) {
41         response.setHeader( "Vary", "User-Agent");
42     }
43
44
45     // ---------------------------------------------------------------- authorization
46
/**
47      * Decodes the "Authorization" header and retrieves the
48      * user's name from it. Returns <code>null</code> if the header is not present.
49      */

50     public static String JavaDoc getAuthUsername(HttpServletRequest JavaDoc request) {
51         String JavaDoc header = request.getHeader("Authorization");
52         if (header == null) {
53             return null;
54         }
55         String JavaDoc encoded = header.substring(header.indexOf(' ') + 1);
56         String JavaDoc decoded = new String JavaDoc(Base64.decode(encoded));
57         return decoded.substring(0, decoded.indexOf(':'));
58     }
59
60     /**
61      * Decodes the "Authorization" header and retrieves the
62      * password from it. Returns null if the header is not present.
63      */

64     public static String JavaDoc getAuthPassword(HttpServletRequest JavaDoc request) {
65         String JavaDoc header = request.getHeader("Authorization");
66         if (header == null) {
67             return null;
68         }
69         String JavaDoc encoded = header.substring(header.indexOf(' ') + 1);
70         String JavaDoc decoded = new String JavaDoc(Base64.decode(encoded));
71         return decoded.substring(decoded.indexOf(':') +1);
72     }
73
74     /**
75      * Sends correct headers to require basic authentication for the given realm.
76      */

77     public static void requireAuthentication(HttpServletResponse JavaDoc resp, String JavaDoc realm) throws IOException JavaDoc {
78         resp.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + '\"');
79         resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
80     }
81
82
83     // ---------------------------------------------------------------- cookie
84

85     /**
86      * Returns cookie value from client.
87      *
88      * @return cookie value or <code>null</code> if cookie with specified name doesn't exist.
89      */

90     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc cookieName) {
91         Cookie JavaDoc[] cookies = request.getCookies();
92         if (cookies != null) {
93             Cookie JavaDoc cookie;
94             for (int i = 0; i < cookies.length; i++) {
95                 cookie = cookies[i];
96                 if (cookie.getName().equals(cookieName)) {
97                     return cookie;
98                 }
99             }
100         }
101         return null;
102     }
103
104
105     // ---------------------------------------------------------------- request/session
106

107
108     /**
109      * Return HTTP request parameter as String or String[].
110      */

111     public static Object JavaDoc getRequestParameter(ServletRequest JavaDoc request, String JavaDoc name) {
112         String JavaDoc[] values = request.getParameterValues(name);
113         if (values == null) {
114             return null;
115         }
116         if (values.length == 1) {
117             return values[0];
118         }
119         return values;
120     }
121
122
123     /**
124      * Transfer attributes from a map to request.
125      */

126     public static void setRequestAttributes(ServletRequest JavaDoc request, Map JavaDoc attributes) {
127         Iterator JavaDoc iterator = attributes.keySet().iterator();
128         while (iterator.hasNext()) {
129             String JavaDoc key = (String JavaDoc) iterator.next();
130             request.setAttribute(key, attributes.get(key));
131         }
132     }
133
134     /**
135      * Returns a new map containing request attributes.
136      */

137     public static Map JavaDoc getRequestAttributes(ServletRequest JavaDoc request) {
138         Map JavaDoc map = new HashMap JavaDoc();
139         loadRequestAttributes(map, request);
140         return map;
141     }
142
143     public static void loadRequestAttributes(Map JavaDoc map, ServletRequest JavaDoc request) {
144         Enumeration JavaDoc names = request.getAttributeNames();
145         while (names.hasMoreElements()) {
146             String JavaDoc name = (String JavaDoc) names.nextElement();
147             map.put(name, request.getAttribute(name));
148         }
149     }
150
151     /**
152      * Returns a new map containing request parameters. Request parameter may
153      * be either String or String[].
154      * @see #getRequestParameter(ServletRequest, String)
155      */

156     public static Map JavaDoc getRequestParameters(ServletRequest JavaDoc request) {
157         Map JavaDoc map = new HashMap JavaDoc();
158         loadRequestParameters(map, request);
159         return map;
160     }
161
162     public static void loadRequestParameters(Map JavaDoc map, ServletRequest JavaDoc request) {
163         Enumeration JavaDoc names = request.getParameterNames();
164         while (names.hasMoreElements()) {
165             String JavaDoc name = (String JavaDoc) names.nextElement();
166             map.put(name, getRequestParameter(request, name));
167         }
168     }
169
170     /**
171      * Loads session attributes into a map.
172      */

173     public static void loadSessionAttributes(Map JavaDoc destination, HttpSession JavaDoc session) {
174         Enumeration JavaDoc names = session.getAttributeNames();
175         while (names.hasMoreElements()) {
176             String JavaDoc name = (String JavaDoc) names.nextElement();
177             destination.put(name, session.getAttribute(name));
178         }
179     }
180
181     public static Map JavaDoc getSessionAttributes(HttpSession JavaDoc session) {
182         Map JavaDoc map = new HashMap JavaDoc();
183         loadSessionAttributes(map, session);
184         return map;
185     }
186
187     public static void setSessionAttributes(HttpSession JavaDoc session, Map JavaDoc attributes) {
188         Iterator JavaDoc iterator = attributes.keySet().iterator();
189         while (iterator.hasNext()) {
190             String JavaDoc key = (String JavaDoc) iterator.next();
191             session.setAttribute(key, attributes.get(key));
192         }
193     }
194
195
196     // ---------------------------------------------------------------- get value
197

198     /**
199      * Returns non-null attribute value. All scopes are examined in the
200      * following order: page (if exist), request, session, application.
201      */

202     public static Object JavaDoc getAttributeValue(HttpServletRequest JavaDoc request, String JavaDoc name, PageContext JavaDoc page) {
203         Object JavaDoc value;
204         if (page != null) {
205             value = page.getAttribute(name);
206             if (value != null) {
207                 return value;
208             }
209         }
210         value = request.getAttribute(name);
211         if (value != null) {
212             return value;
213         }
214         value = request.getSession().getAttribute(name);
215         if (value != null) {
216             return value;
217         }
218         value = request.getSession().getServletContext().getAttribute(name);
219         return value;
220     }
221
222     public static Object JavaDoc getAttributeValue(HttpServletRequest JavaDoc request, String JavaDoc name) {
223         return getAttributeValue(request, name, null);
224     }
225
226     /**
227      * Returns non-null value of property/attribute. Scopes are examined in the following
228      * order: page (if exist), request, request parameters, session, application.
229      */

230     public static Object JavaDoc getValue(HttpServletRequest JavaDoc request, String JavaDoc name, PageContext JavaDoc page) {
231         Object JavaDoc value;
232         if (page != null) {
233             value = page.getAttribute(name);
234             if (value != null) {
235                 return value;
236             }
237         }
238         value = request.getAttribute(name);
239         if (value != null) {
240             return value;
241         }
242         value = request.getParameter(name);
243         if (value != null) {
244             return value;
245         }
246         value = request.getSession().getAttribute(name);
247         if (value != null) {
248             return value;
249         }
250         value = request.getSession().getServletContext().getAttribute(name);
251         return value;
252     }
253
254     public static Object JavaDoc getValue(HttpServletRequest JavaDoc request, String JavaDoc name) {
255         return getValue(request, name, null);
256     }
257
258
259     // ---------------------------------------------------------------- resolve url
260

261
262     /**
263      * Valid characters in a scheme, as specified by RFC 1738.
264      */

265     public static final String JavaDoc VALID_SCHEME_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-";
266
267     /**
268      * Returns <code>true</code> if current URL is absolute, <code>false</code> otherwise.
269      */

270     public static boolean isAbsoluteUrl(String JavaDoc url) {
271         if (url == null) { // a null URL is not absolute
272
return false;
273         }
274         int colonPos; // fast simple check first
275
if ((colonPos = url.indexOf(':')) == -1) {
276             return false;
277         }
278
279         // if we DO have a colon, make sure that every character
280
// leading up to it is a valid scheme character
281
for (int i = 0; i < colonPos; i++) {
282             if (VALID_SCHEME_CHARS.indexOf(url.charAt(i)) == -1) {
283                 return false;
284             }
285         }
286         return true;
287     }
288
289     /**
290      * Strips a servlet session ID from <code>url</code>. The session ID
291      * is encoded as a URL "path parameter" beginning with "jsessionid=".
292      * We thus remove anything we find between ";jsessionid=" (inclusive)
293      * and either EOS or a subsequent ';' (exclusive).
294      */

295     public static String JavaDoc stripSession(String JavaDoc url) {
296         StringBuffer JavaDoc u = new StringBuffer JavaDoc(url);
297         int sessionStart;
298         while ((sessionStart = u.toString().indexOf(";jsessionid=")) != -1) {
299             int sessionEnd = u.toString().indexOf(';', sessionStart + 1);
300             if (sessionEnd == -1) {
301                 sessionEnd = u.toString().indexOf('?', sessionStart + 1);
302             }
303             if (sessionEnd == -1) {
304                 sessionEnd = u.length();
305             }
306             u.delete(sessionStart, sessionEnd);
307         }
308         return u.toString();
309     }
310
311     public static String JavaDoc resolveUrl(String JavaDoc url, PageContext JavaDoc pageContext) {
312         return resolveUrl(url, (HttpServletRequest JavaDoc) pageContext.getRequest());
313     }
314
315     public static String JavaDoc resolveUrl(String JavaDoc url, HttpServletRequest JavaDoc request) {
316         if (isAbsoluteUrl(url)) {
317             return url;
318         }
319         if (url.startsWith("/")) {
320             return (request.getContextPath() + url);
321         } else {
322             return url;
323         }
324     }
325
326     public static String JavaDoc resolveUrl(String JavaDoc url, String JavaDoc context) {
327         if (isAbsoluteUrl(url)) {
328             return url;
329         }
330         if (!context.startsWith("/") || !url.startsWith("/")) {
331             throw new IllegalArgumentException JavaDoc("Values of both 'context' and 'url' must start with '/'.");
332         }
333         if (context.equals("/")) {
334             return url;
335         } else {
336             return (context + url);
337         }
338     }
339
340
341     // ---------------------------------------------------------------- debug
342

343     /**
344      * Returns a string with debug info from all servlet objects.
345      * @see #debug(javax.servlet.http.HttpServletRequest, javax.servlet.jsp.PageContext)
346      */

347     public static String JavaDoc debug(HttpServletRequest JavaDoc request) {
348         return debug(request, null);
349     }
350
351     /**
352      * Returns a string with debug info from all servlet objects, including pageScope.
353      */

354     public static String JavaDoc debug(HttpServletRequest JavaDoc request, PageContext JavaDoc page) {
355         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
356         result.append("\nPARAMETERS\n----------\n");
357         Enumeration JavaDoc enumeration = request.getParameterNames();
358         while (enumeration.hasMoreElements()) {
359             String JavaDoc name = (String JavaDoc) enumeration.nextElement();
360             Object JavaDoc[] value = request.getParameterValues(name);
361             result.append(name).append('=');
362             if (value == null) {
363                 result.append("<null>");
364             } else if (value.length == 1) {
365                 result.append('[').append(value[0]).append("]\n");
366             } else {
367                 result.append('[').append(value).append("]\n");
368             }
369         }
370
371         loop:
372         for (int i = 0; i < 4; i++) {
373             switch (i) {
374                 case 0: result.append("\nREQUEST\n--------\n");
375                         enumeration = request.getAttributeNames();
376                         break;
377                 case 1: result.append("\nSESSION\n--------\n");
378                         enumeration = request.getSession().getAttributeNames();
379                         break;
380                 case 2: result.append("\nAPPLICATION\n-----------\n");
381                         enumeration = request.getSession().getServletContext().getAttributeNames();
382                         break;
383                 case 3: if (page == null) {
384                             break loop;
385                         }
386                         result.append("\nPAGE\n-----------\n");
387                         enumeration = page.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
388             }
389             while (enumeration.hasMoreElements()) {
390                 String JavaDoc name = (String JavaDoc) enumeration.nextElement();
391                 Object JavaDoc value = request.getAttribute(name);
392                 result.append(name).append('=');
393                 if (value == null) {
394                     result.append("<null>\n");
395                 } else {
396                     result.append('[').append(value).append("]\n");
397                 }
398             }
399         }
400         return result.toString();
401     }
402
403 }
404
Popular Tags