KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > atlassian > seraph > util > CookieUtils


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

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

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

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

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

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

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

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

151     public static String JavaDoc encodePasswordCookie(String JavaDoc username, String JavaDoc password, String JavaDoc encoding)
152     {
153         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
154         if (username != null && password != null)
155         {
156             char offset1 = (encoding != null && encoding.length() > 1) ? encoding.charAt(1) : ENCODE_CHAR_OFFSET1;
157             char offset2 = (encoding != null && encoding.length() > 2) ? encoding.charAt(2) : ENCODE_CHAR_OFFSET2;
158
159             byte[] bytes = (username + DELIMITER + password).getBytes();
160             int b;
161
162             for (int n = 0; n < bytes.length; n++)
163             {
164                 b = bytes[n] ^ (ENCODE_XORMASK + n);
165                 buf.append((char) (offset1 + (b & 0x0F)));
166                 buf.append((char) (offset2 + ((b >> 4) & 0x0F)));
167             }
168         }
169         return buf.toString();
170     }
171
172     /**
173      * Decodes a cookie string containing a username and password.
174      * @param cookieVal The cookie value.
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)
180     {
181         return decodePasswordCookie(cookieVal, new String JavaDoc(new char[]{DELIMITER, ENCODE_CHAR_OFFSET1, ENCODE_CHAR_OFFSET2}));
182     }
183
184     /**
185      * Decodes a cookie string containing a username and password.
186      * @param cookieVal The cookie value.
187      * @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!
188      * @return String[] containing the username at index 0 and the password at
189      * index 1, or <code>{ null, null }</code> if cookieVal equals
190      * <code>null</code> or the empty string.
191      */

192     public static String JavaDoc[] decodePasswordCookie(String JavaDoc cookieVal, String JavaDoc encoding)
193     {
194         // check that the cookie value isn't null or zero-length
195
if (cookieVal == null || cookieVal.length() <= 0)
196         {
197             return null;
198         }
199
200         char offset1 = (encoding != null && encoding.length() > 1) ? encoding.charAt(1) : ENCODE_CHAR_OFFSET1;
201         char offset2 = (encoding != null && encoding.length() > 2) ? encoding.charAt(2) : ENCODE_CHAR_OFFSET2;
202
203         // decode the cookie value
204
char[] chars = cookieVal.toCharArray();
205         byte[] bytes = new byte[chars.length / 2];
206         int b;
207         for (int n = 0, m = 0; n < bytes.length; n++)
208         {
209             b = chars[m++] - offset1;
210             b |= (chars[m++] - offset2) << 4;
211             bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
212         }
213         cookieVal = new String JavaDoc(bytes);
214         int pos = cookieVal.indexOf(DELIMITER);
215         String JavaDoc username = (pos < 0) ? "" : cookieVal.substring(0, pos);
216         String JavaDoc password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
217
218         return new String JavaDoc[]{username, password};
219     }
220 }
221
Popular Tags