KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > portlet > util > CookieUtils


1 package com.opensymphony.webwork.portlet.util;
2
3 import org.apache.log4j.Category;
4
5 import javax.servlet.http.Cookie JavaDoc;
6 import javax.servlet.http.HttpServletRequest JavaDoc;
7 import javax.servlet.http.HttpServletResponse JavaDoc;
8
9 /**
10  * Cookie utility class for dealing with cookies
11  * <p/>
12  * Includes code from Jive 1.2.4 (released under the Apache license)
13  */

14 public class CookieUtils {
15     private static final Category log = Category.getInstance(CookieUtils.class);
16
17     // the key which represents the list of cookies to add for this request (in case of redirect)
18
public static final String JavaDoc COOKIES_TO_SEND = "atlassian.core.web.cookies.unsent";
19
20     // Character used to separate username and password in persistent cookies.
21
// 0x13 == "Device Control 3" non-printing ASCII char. Unlikely to appear in a username
22
private static final char DELIMITER = 0x13;
23
24     //"Tweakable" parameters for the cookie encoding. NOTE: changing these
25
//and recompiling this class will essentially invalidate old cookies.
26
private final static int ENCODE_XORMASK = 0x5A;
27     private final static char ENCODE_CHAR_OFFSET1 = 'C';
28     private final static char ENCODE_CHAR_OFFSET2 = 'i';
29
30     /**
31      * Invalidate the specified cookie and delete it from the response object.
32      *
33      * @param response The HttpServletResponse object, known as "response" in a JSP page.
34      * @param cookieName The name of the cookie you want to delete.
35      * @param path of the path the cookie you want to delete.
36      */

37     public static void invalidateCookie(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc cookieName, String JavaDoc path) {
38         log.debug("CookieUtils.invalidateCookie " + cookieName + " for path " + path);
39         setCookie(request, response, cookieName, null, 0, path);
40     }
41
42     /**
43      * Invalidate the specified cookie and delete it from the response object. Deletes only cookies mapped
44      * against the root "/" path. Otherwise use
45      * {@link #invalidateCookie(HttpServletRequest, HttpServletResponse, String, String)}
46      *
47      * @param response The HttpServletResponse object, known as "response" in a JSP page.
48      * @param cookieName The name of the cookie you want to delete.
49      * @see #invalidateCookie(HttpServletRequest, HttpServletResponse, String, String)
50      */

51     public static void invalidateCookie(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc cookieName) {
52         invalidateCookie(request, response, cookieName, "/");
53     }
54
55     /**
56      * Returns the specified Cookie object, or null if the cookie does not exist.
57      *
58      * @param request The HttpServletRequest object, known as "request" in a
59      * JSP page.
60      * @param name the name of the cookie.
61      * @return the Cookie object if it exists, otherwise null.
62      */

63     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name) {
64         Cookie JavaDoc cookies[] = request.getCookies();
65         if (cookies == null || name == null || name.length() == 0) {
66             return null;
67         }
68         //Otherwise, we have to do a linear scan for the cookie.
69
for (int i = 0; i < cookies.length; i++) {
70             if (cookies[i].getName().equals(name)) {
71                 return cookies[i];
72             }
73         }
74         return null;
75     }
76
77     /**
78      * Sets a cookie
79      * <p/>
80      * This will also put the cookie in a list of cookies to send with this request's response
81      * (so that in case of a redirect occurring down the chain, the first filter
82      * will always try to set this cookie again)
83      */

84     public static Cookie JavaDoc setCookie(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc name, String JavaDoc value, int maxAge, String JavaDoc path) {
85         log.debug("CookieUtils.setCookie " + name + ":" + value);
86         Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
87         cookie.setMaxAge(maxAge);
88         cookie.setPath(path);
89         response.addCookie(cookie);
90
91         return cookie;
92     }
93
94     /**
95      * Returns the value of the specified cookie as a String. If the cookie
96      * does not exist, the method returns null.
97      *
98      * @param request the HttpServletRequest object, known as "request" in a
99      * JSP page.
100      * @param name the name of the cookie
101      * @return the value of the cookie, or null if the cookie does not exist.
102      */

103     public static String JavaDoc getCookieValue(HttpServletRequest JavaDoc request, String JavaDoc name) {
104         Cookie JavaDoc cookie = getCookie(request, name);
105         if (cookie != null) {
106             return cookie.getValue();
107         }
108         return null;
109     }
110
111     /**
112      * Builds a cookie string containing a username and password.<p>
113      * <p/>
114      * Note: with open source this is not really secure, but it prevents users
115      * from snooping the cookie file of others and by changing the XOR mask and
116      * character offsets, you can easily tweak results.
117      *
118      * @param username The username.
119      * @param password The password.
120      * @return String encoding the input parameters, an empty string if one of
121      * the arguments equals <code>null</code>.
122      */

123     public static String JavaDoc encodePasswordCookie(String JavaDoc username, String JavaDoc password) {
124         return encodePasswordCookie(username, password, new String JavaDoc(new char[]{DELIMITER, ENCODE_CHAR_OFFSET1, ENCODE_CHAR_OFFSET2}));
125     }
126
127     /**
128      * Builds a cookie string containing a username and password, using offsets to customise the encoding.<p>
129      * <p/>
130      * Note: with open source this is not really secure, but it prevents users
131      * from snooping the cookie file of others and by changing the XOR mask and
132      * character offsets, you can easily tweak results.
133      *
134      * @param username The username.
135      * @param password The password.
136      * @param encoding A String used to customise cookie encoding (only the first 3 characters are used)
137      * @return String encoding the input parameters, an empty string if one of
138      * the arguments equals <code>null</code>.
139      */

140     public static String JavaDoc encodePasswordCookie(String JavaDoc username, String JavaDoc password, String JavaDoc encoding) {
141         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
142         if (username != null && password != null) {
143             char offset1 = (encoding != null && encoding.length() > 1) ? encoding.charAt(1) : ENCODE_CHAR_OFFSET1;
144             char offset2 = (encoding != null && encoding.length() > 2) ? encoding.charAt(2) : ENCODE_CHAR_OFFSET2;
145
146             byte[] bytes = (username + DELIMITER + password).getBytes();
147             int b;
148
149             for (int n = 0; n < bytes.length; n++) {
150                 b = bytes[n] ^ (ENCODE_XORMASK + n);
151                 buf.append((char) (offset1 + (b & 0x0F)));
152                 buf.append((char) (offset2 + ((b >> 4) & 0x0F)));
153             }
154         }
155         return buf.toString();
156     }
157
158     /**
159      * Decodes a cookie string containing a username and password.
160      *
161      * @param cookieVal The cookie value.
162      * @return String[] containing the username at index 0 and the password at
163      * index 1, or <code>{ null, null }</code> if cookieVal equals
164      * <code>null</code> or the empty string.
165      */

166     public static String JavaDoc[] decodePasswordCookie(String JavaDoc cookieVal) {
167         return decodePasswordCookie(cookieVal, new String JavaDoc(new char[]{DELIMITER, ENCODE_CHAR_OFFSET1, ENCODE_CHAR_OFFSET2}));
168     }
169
170     /**
171      * Decodes a cookie string containing a username and password.
172      *
173      * @param cookieVal The cookie value.
174      * @param encoding A String used to customise cookie encoding (only the first 3 characters are used) - should be the same string you used to encode the cookie!
175      * @return String[] containing the username at index 0 and the password at
176      * index 1, or <code>{ null, null }</code> if cookieVal equals
177      * <code>null</code> or the empty string.
178      */

179     public static String JavaDoc[] decodePasswordCookie(String JavaDoc cookieVal, String JavaDoc encoding) {
180         // check that the cookie value isn't null or zero-length
181
if (cookieVal == null || cookieVal.length() <= 0) {
182             return null;
183         }
184
185         char offset1 = (encoding != null && encoding.length() > 1) ? encoding.charAt(1) : ENCODE_CHAR_OFFSET1;
186         char offset2 = (encoding != null && encoding.length() > 2) ? encoding.charAt(2) : ENCODE_CHAR_OFFSET2;
187
188         // decode the cookie value
189
char[] chars = cookieVal.toCharArray();
190         byte[] bytes = new byte[chars.length / 2];
191         int b;
192         for (int n = 0, m = 0; n < bytes.length; n++) {
193             b = chars[m++] - offset1;
194             b |= (chars[m++] - offset2) << 4;
195             bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
196         }
197         cookieVal = new String JavaDoc(bytes);
198         int pos = cookieVal.indexOf(DELIMITER);
199         String JavaDoc username = (pos < 0) ? "" : cookieVal.substring(0, pos);
200         String JavaDoc password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
201
202         return new String JavaDoc[]{username, password};
203     }
204 }
205
Popular Tags