KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > http > HttpCookieParser


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  *
22  * $Id: HttpCookieParser.java,v 1.2 2005/03/24 10:51:20 slobodan Exp $
23  */

24
25
26
27
28
29 package com.lutris.http;
30 import java.text.FieldPosition JavaDoc;
31 import java.text.ParsePosition JavaDoc;
32 import java.text.SimpleDateFormat JavaDoc;
33 import java.util.Date JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36 import java.util.TimeZone JavaDoc;
37 import java.util.Vector JavaDoc;
38
39 import javax.servlet.http.Cookie JavaDoc;
40
41 /**
42  * This class takes a cookie header and converts it into a
43  * set of http cookies. It can be used to parse request and
44  * response cookie headers as well as format response cookies.
45  *
46  * @author Kyle Clark
47  * @version $Revision: 1.2 $
48  * @since Harmony1.0
49  */

50 public class HttpCookieParser {
51
52     private static final String JavaDoc EXPIRES = "expires";
53     private static final String JavaDoc MAXAGE = "max-age";
54     private static final String JavaDoc PATH = "path";
55     private static final String JavaDoc DOMAIN = "domain";
56     private static final String JavaDoc SECURE = "secure";
57
58     /**
59      * Object for formatting dates.
60      */

61     private static final SimpleDateFormat JavaDoc dateFormatter =
62         new SimpleDateFormat JavaDoc("EEEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
63
64     /*
65      * Class constructor.
66      */

67     static {
68     dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
69     }
70
71     /**
72      * Parses an http cookie request header and returns a vector
73      * of Cookie objects defined in the header. This method
74      * should only be used with the <b>request</b> cookie header "Cookie:".
75      *
76      * @param httpReqCookieHeader
77      * The http cookie request header to parse.
78      * @return
79      * vector containing the cookies defined in the header.
80      */

81     public static Vector JavaDoc parseRequestHeader(String JavaDoc httpReqCookieHeader) {
82         Cookie JavaDoc cookie;
83         Vector JavaDoc result = new Vector JavaDoc();
84
85         // Cookie are separated by ';'
86
StringTokenizer JavaDoc cookieTokens =
87             new StringTokenizer JavaDoc(httpReqCookieHeader.trim(), ";");
88         while (cookieTokens.hasMoreTokens()) {
89             // Name is separated from value by '='
90
StringTokenizer JavaDoc t =
91                 new StringTokenizer JavaDoc(cookieTokens.nextToken(), "=");
92             String JavaDoc name = t.nextToken().trim();
93             if (t.hasMoreTokens()) {
94                 // Name has a value
95
String JavaDoc value = t.nextToken().trim();
96                 result.addElement(new Cookie JavaDoc(name, value));
97             }
98         }
99         return result;
100     }
101
102     /**
103      * Parses an http cookie request header and returns the first
104      * cookie that matches the specified name. This method
105      * should only be used with the <b>request</b> cookie header "Cookie:".
106      *
107      * @param httpReqCookieHeader
108      * The http cookie request header to parse.
109      * @param name
110      * The cookie name of interest.
111      * @return
112      * The first cookie that matches. null if no matching cookies
113      * are found.
114      */

115     public static Cookie JavaDoc parseRequestHeader(String JavaDoc httpReqCookieHeader,
116                                             String JavaDoc name) {
117         // Cookie are separated by ';'
118
StringTokenizer JavaDoc cookieTokens =
119             new StringTokenizer JavaDoc(httpReqCookieHeader.trim(), ";");
120         while (cookieTokens.hasMoreTokens()) {
121             // Name is separated from value by '='
122
StringTokenizer JavaDoc t =
123                 new StringTokenizer JavaDoc(cookieTokens.nextToken(), "=");
124             String JavaDoc tokenName = t.nextToken().trim();
125             if (t.hasMoreTokens() && tokenName.equals(name)) {
126                 // if name has a value
127
String JavaDoc value = t.nextToken().trim();
128                 return new Cookie JavaDoc(name, value);
129             }
130         }
131         return null;
132     }
133
134
135     /**
136      * Convert an old cookie expires data to maximum age; assuming now
137      * as the start.
138      *
139      * @param dateStr The string expiry date.
140      * @return The max age, in seconds.
141      */

142     public static int expiresToMaxAge(String JavaDoc dateStr) {
143         Date JavaDoc date = dateFormatter.parse(dateStr.trim(), new ParsePosition JavaDoc(0));
144         Date JavaDoc current = new Date JavaDoc();
145         return (int)(current.getTime()-date.getTime()) * 1000;
146     }
147
148
149     /**
150      * Convert amaximum age to a old cookie expires data; assuming now
151      * as the start.
152      *
153      * @param The max age, in seconds.
154      * @return The string expiry date.
155      */

156     public static String JavaDoc maxAgeToExpires(int maxAge) {
157         long maxInMillis = (long)maxAge * 1000;
158         Date JavaDoc date = new Date JavaDoc(new Date JavaDoc().getTime()+maxInMillis);
159         StringBuffer JavaDoc dateStr = new StringBuffer JavaDoc();
160         dateFormatter.format(date, dateStr, new FieldPosition JavaDoc(0));
161         return dateStr.toString();
162     }
163
164     /**
165      * Parses an http cookie response header and returns a vector
166      * of Cookie objects defined in the header. This method
167      * only works with http <b>response</b> headers, (i.e. Set-Cookie).
168      *
169      * @param httpResponseCookieHeader
170      * The http cookie response header from which the cookies
171      * are constructed.
172      * @return
173      * Vector containing the cookies defined in the header.
174      */

175     public static Vector JavaDoc parseResponseHeader(String JavaDoc httpResponseCookieHeader) {
176         Vector JavaDoc result = new Vector JavaDoc();
177         httpResponseCookieHeader = httpResponseCookieHeader.trim();
178         // Cookies are separated by ','
179
StringTokenizer JavaDoc cookieTokens =
180             new StringTokenizer JavaDoc(httpResponseCookieHeader, ",");
181         while (cookieTokens.hasMoreTokens()) {
182             // Cookie fields are separated by ';'
183
StringTokenizer JavaDoc tokens =
184                 new StringTokenizer JavaDoc(cookieTokens.nextToken(), ";");
185             Cookie JavaDoc cookie = null;
186             while (tokens.hasMoreTokens()) {
187                 // field name is separated from value by '='
188
StringTokenizer JavaDoc t =
189                     new StringTokenizer JavaDoc(tokens.nextToken(), "=");
190                 String JavaDoc name = t.nextToken().trim();
191                 if (t.hasMoreTokens()) {
192                     String JavaDoc value = t.nextToken().trim();
193                     if (cookie != null) {
194                         if (name.equalsIgnoreCase(EXPIRES)) {
195                             cookie.setMaxAge(expiresToMaxAge(value));
196                         } else if (name.equalsIgnoreCase(DOMAIN)) {
197                             cookie.setDomain(value);
198                         } else if (name.equalsIgnoreCase(PATH)) {
199                             cookie.setPath(value);
200                         }
201                     } else { // New cookie
202
cookie = new Cookie JavaDoc(name, value);
203                         result.addElement(cookie);
204                     }
205                 } else if ((cookie != null) && name.equalsIgnoreCase(SECURE)) {
206                     cookie.setSecure(true);
207                 }
208             }
209         }
210         return result;
211     }
212
213
214     public static Cookie JavaDoc parseCookieString(String JavaDoc cookieString) {
215         cookieString = cookieString.trim();
216         // Cookie fields are separated by ';'
217
StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(cookieString, ";");
218         Cookie JavaDoc cookie = null;
219         while (tokens.hasMoreTokens()) {
220             // field name is separated from value by '='
221
StringTokenizer JavaDoc t =
222                 new StringTokenizer JavaDoc(tokens.nextToken(), "=");
223             String JavaDoc name = t.nextToken().trim();
224             if (t.hasMoreTokens()) {
225                 String JavaDoc value = t.nextToken().trim();
226                 if (cookie != null) {
227                     if (name.equalsIgnoreCase(EXPIRES)) {
228                         cookie.setMaxAge(expiresToMaxAge(value));
229                     } else if (name.equalsIgnoreCase(DOMAIN)) {
230                         cookie.setDomain(value);
231                     } else if (name.equalsIgnoreCase(PATH)) {
232                         cookie.setPath(value);
233                     } else if (name.equalsIgnoreCase(MAXAGE) ) {
234                         int maxAge = 0;
235                         try {
236                             maxAge = Integer.parseInt(value);
237                         } catch (Exception JavaDoc e) {
238                         }
239                         cookie.setMaxAge(maxAge);
240                     }
241                 } else { // New cookie
242
cookie = new Cookie JavaDoc(name, value);
243                 }
244             } else if ((cookie != null) && name.equalsIgnoreCase(SECURE)) {
245                 cookie.setSecure(true);
246             }
247         }
248         return cookie;
249     }
250
251
252     /**
253      * Append a cookie keyword/value pair, with any necessary quoting of
254      * the value.
255      *
256      * @param buf String to append cookie arguments to.
257      * @param key Keyword to append.
258      * @param value Value to append, with quoting.
259      */

260     //FIXME: Turns out, old cookies didn't support quoted strings,
261
// So we need to check the version number. Right now, just don't
262
// do quoting.
263
private static void appendCookieArg(StringBuffer JavaDoc buf, String JavaDoc key, String JavaDoc value) {
264         if (buf.length() > 0) {
265             buf.append("; ");
266         }
267         buf.append(key);
268         buf.append("=");
269         buf.append(value);
270     }
271
272     /**
273      * Append a cookie keyword/value pair, with any necessary quoting of
274      * the value. Adjust case of keyword if its a version zero cookie.
275      * This is should not be used on the cookie name, as case is honored
276      * there.
277      *
278      * @param version Cookie version.
279      * @param buf String to append cookie arguments to.
280      * @param key Keyword to append.
281      * @param value Value to append, with quoting.
282      */

283     private static void appendCookieArg(int version, StringBuffer JavaDoc buf, String JavaDoc key, String JavaDoc value) {
284         //FIXME: Don't think this is really needed; just put in as a possible
285
//hack for the page-reload problem.
286
if (version == 0) {
287             // Version 0 appears to like lower case keywords.
288
key = key.toLowerCase();
289         }
290         appendCookieArg(buf, key, value);
291     }
292
293     /**
294      * Format a Cookie for a response header.
295      *
296      * @param The cookie to format.
297      * @return The value for the header (name is not included).
298      */

299     public static String JavaDoc formatResponseCookie(Cookie JavaDoc cookie) {
300         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
301         int version = cookie.getVersion();
302
303         //FIXME: only 0.0 is supported; just got to figure out quoting.
304
if (version > 0) {
305             throw new Error JavaDoc("HttpCookieParser: only version 0 cookies supported right now");
306         }
307
308         appendCookieArg(buf, cookie.getName(), cookie.getValue());
309         if ((version > 0) && (cookie.getComment() != null)) {
310             appendCookieArg(version, buf, "Comment", cookie.getComment());
311         }
312         if (cookie.getDomain() != null) {
313             appendCookieArg(version, buf, "Domain", cookie.getDomain());
314         }
315         if (cookie.getMaxAge() >= 0) {
316             if (version > 0) {
317                 appendCookieArg(version, buf, "Max-Age", Integer.toString(cookie.getMaxAge()));
318             } else {
319                 appendCookieArg(version, buf, "Expires", maxAgeToExpires(cookie.getMaxAge()));
320             }
321         }
322         if (cookie.getPath() != null) {
323             appendCookieArg(version, buf, "Path", cookie.getPath());
324         }
325         if (cookie.getDomain() != null) {
326             appendCookieArg(version, buf, "Domain", cookie.getDomain());
327         }
328         return buf.toString();
329     }
330 }
331
Popular Tags