KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > htmlparser > http > Cookie


1 // HTMLParser Library $Name: v1_5_20050313 $ - A java-based parser for HTML
2
// http://sourceforge.org/projects/htmlparser
3
// Copyright (C) 2004 Derrick Oswald
4
//
5
// Revision Control Information
6
//
7
// $Source: /cvsroot/htmlparser/htmlparser/src/org/htmlparser/http/Cookie.java,v $
8
// $Author: derrickoswald $
9
// $Date: 2004/09/02 02:28:15 $
10
// $Revision: 1.1 $
11
//
12
// This library is free software; you can redistribute it and/or
13
// modify it under the terms of the GNU Lesser General Public
14
// License as published by the Free Software Foundation; either
15
// version 2.1 of the License, or (at your option) any later version.
16
//
17
// This library is distributed in the hope that it will be useful,
18
// but WITHOUT ANY WARRANTY; without even the implied warranty of
19
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20
// Lesser General Public License for more details.
21
//
22
// You should have received a copy of the GNU Lesser General Public
23
// License along with this library; if not, write to the Free Software
24
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25
//
26

27 package org.htmlparser.http;
28
29 import java.io.Serializable JavaDoc;
30 import java.util.Date JavaDoc;
31
32 /**
33  * A HTTP cookie.
34  * This class represents a "Cookie", as used for session management with HTTP
35  * and HTTPS protocols. Cookies are used to get user agents (web browsers etc)
36  * to hold small amounts of state associated with a user's web browsing. Common
37  * applications for cookies include storing user preferences, automating low
38  * security user signon facilities, and helping collect data used for "shopping
39  * cart" style applications.
40  * <P>
41  * Cookies are named, and have a single value. They may have optional
42  * attributes, including a comment presented to the user, path and domain
43  * qualifiers for which hosts see the cookie, a maximum age, and a version.
44  * Current web browsers often have bugs in how they treat those attributes, so
45  * interoperability can be improved by not relying on them heavily.
46  * <P>
47  * Cookies are assigned by servers, using fields added to HTTP response headers.
48  * Cookies are passed back to those servers using fields added to HTTP request
49  * headers.Several cookies with the same name can be returned;
50  * they have different path attributes, but those attributes
51  * will not be visible when using "old format" cookies.
52  * <P>
53  * Cookies affect the caching of the web pages used to set their values. At this
54  * time, none of the sophisticated HTTP/1.1 cache control models are supported.
55  * Standard HTTP/1.0 caches will not cache pages which contain
56  * cookies created by this class.
57  * <P>
58  * Cookies are being standardized by the IETF. This class supports the original
59  * Cookie specification (from Netscape Communications Corp.) as well as the
60  * updated <a HREF="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> specification.
61  */

62 public class Cookie
63     implements
64         Cloneable JavaDoc,
65         Serializable JavaDoc
66 {
67     //
68
// from RFC 2068, token special case characters
69
//
70
private static final String JavaDoc mSpecials = "()<>@,;:\\\"/[]?={} \t";
71
72     /**
73      * The name of the cookie.
74      */

75     protected String JavaDoc mName;
76
77     /**
78      * The cookie value.
79      */

80     protected String JavaDoc mValue; // value of NAME
81

82     /**
83      * Describes the cookie's use.
84      */

85     protected String JavaDoc mComment;
86
87     /**
88      * Domain that sees cookie.
89      */

90     protected String JavaDoc mDomain;
91
92     /**
93      * Cookie expires after this date.
94      */

95     protected Date JavaDoc mExpiry;
96
97     /**
98      * URLs that see the cookie.
99      */

100     protected String JavaDoc mPath;
101
102     /**
103      * Use SSL.
104      */

105     protected boolean mSecure;
106
107     /**
108      * If Version=1 it means RFC 2109++ style cookies.
109      */

110     protected int mVersion;
111
112     /**
113      * Defines a cookie with an initial name/value pair. The name must be an
114      * HTTP/1.1 "token" value; alphanumeric ASCII strings work. Names starting
115      * with a "$" character are reserved by RFC 2109.
116      * The path for the cookie is set to the root ("/") and there is no
117      * expiry time set.
118      * @param name
119      * name of the cookie
120      * @param value
121      * value of the cookie
122      * @throws IllegalArgumentException
123      * if the cookie name is not an HTTP/1.1 "token", or if it is
124      * one of the tokens reserved for use by the cookie protocol
125      */

126     public Cookie (String JavaDoc name, String JavaDoc value)
127     {
128         if (!isToken (name) || name.equalsIgnoreCase ("Comment") // rfc2019
129
|| name.equalsIgnoreCase ("Discard") // 2019++
130
|| name.equalsIgnoreCase ("Domain")
131                 || name.equalsIgnoreCase ("Expires") // (old cookies)
132
|| name.equalsIgnoreCase ("Max-Age") // rfc2019
133
|| name.equalsIgnoreCase ("Path")
134                 || name.equalsIgnoreCase ("Secure")
135                 || name.equalsIgnoreCase ("Version"))
136             throw new IllegalArgumentException JavaDoc ("invalid cookie name: " + name);
137         mName = name;
138         mValue = value;
139         mComment = null;
140         mDomain = null;
141         mExpiry = null; // not persisted
142
mPath = "/";
143         mSecure = false;
144         mVersion = 0;
145     }
146
147     /**
148      * If a user agent (web browser) presents this cookie to a user, the
149      * cookie's purpose will be described using this comment. This is not
150      * supported by version zero cookies.
151      *
152      * @see #getComment
153      */

154     public void setComment (String JavaDoc purpose)
155     {
156         mComment = purpose;
157     }
158
159     /**
160      * Returns the comment describing the purpose of this cookie, or null if no
161      * such comment has been defined.
162      *
163      * @see #setComment
164      */

165     public String JavaDoc getComment ()
166     {
167         return (mComment);
168     }
169
170     /**
171      * This cookie should be presented only to hosts satisfying this domain name
172      * pattern. Read RFC 2109 for specific details of the syntax. Briefly, a
173      * domain name name begins with a dot (".foo.com") and means that hosts in
174      * that DNS zone ("www.foo.com", but not "a.b.foo.com") should see the
175      * cookie. By default, cookies are only returned to the host which saved
176      * them.
177      *
178      * @see #getDomain
179      */

180     public void setDomain (String JavaDoc pattern)
181     {
182         mDomain = pattern.toLowerCase (); // IE allegedly needs this
183
}
184
185     /**
186      * Returns the domain of this cookie.
187      *
188      * @see #setDomain
189      */

190     public String JavaDoc getDomain ()
191     {
192         return (mDomain);
193     }
194
195     /**
196      * Sets the expiry date of the cookie. The cookie will expire after the
197      * date specified. A null value indicates the default behaviour:
198      * the cookie is not stored persistently, and will be deleted when the user
199      * agent (web browser) exits.
200      *
201      * @see #getExpiryDate
202      */

203     public void setExpiryDate (Date JavaDoc expiry)
204     {
205         mExpiry = expiry;
206     }
207
208     /**
209      * Returns the expiry date of the cookie. If none was specified,
210      * null is returned, indicating the default behaviour described
211      * with <em>setExpiryDate</em>.
212      *
213      * @see #setExpiryDate
214      */

215     public Date JavaDoc getExpiryDate ()
216     {
217         return (mExpiry);
218     }
219
220     /**
221      * This cookie should be presented only with requests beginning with this
222      * URL. Read RFC 2109 for a specification of the default behaviour.
223      * Basically, URLs in the same "directory" as the one which set the cookie,
224      * and in subdirectories, can all see the cookie unless a different path is
225      * set.
226      *
227      * @see #getPath
228      */

229     public void setPath (String JavaDoc uri)
230     {
231         mPath = uri;
232     }
233
234     /**
235      * Returns the prefix of all URLs for which this cookie is targetted.
236      *
237      * @see #setPath
238      */

239     public String JavaDoc getPath ()
240     {
241         return (mPath);
242     }
243
244     /**
245      * Indicates to the user agent that the cookie should only be sent using a
246      * secure protocol (https). This should only be set when the cookie's
247      * originating server used a secure protocol to set the cookie's value.
248      *
249      * @see #getSecure
250      */

251     public void setSecure (boolean flag)
252     {
253         mSecure = flag;
254     }
255
256     /**
257      * Returns the value of the 'secure' flag.
258      *
259      * @see #setSecure
260      */

261     public boolean getSecure ()
262     {
263         return (mSecure);
264     }
265
266     /**
267      * Returns the name of the cookie. This name may not be changed after the
268      * cookie is created.
269      */

270     public String JavaDoc getName ()
271     {
272         return (mName);
273     }
274
275     /**
276      * Sets the value of the cookie. BASE64 encoding is suggested for use with
277      * binary values.
278      *
279      * <P>
280      * With version zero cookies, you need to be careful about the kinds of
281      * values you use. Values with various special characters (whitespace,
282      * brackets and parentheses, the equals sign, comma, double quote, slashes,
283      * question marks, the "at" sign, colon, and semicolon) should be avoided.
284      * Empty values may not behave the same way on all browsers.
285      *
286      * @see #getValue
287      */

288     public void setValue (String JavaDoc newValue)
289     {
290         mValue = newValue;
291     }
292
293     /**
294      * Returns the value of the cookie.
295      *
296      * @see #setValue
297      */

298     public String JavaDoc getValue ()
299     {
300         return (mValue);
301     }
302
303     /**
304      * Returns the version of the cookie. Version 1 complies with RFC 2109,
305      * version 0 indicates the original version, as specified by Netscape. Newly
306      * constructed cookies use version 0 by default, to maximize
307      * interoperability. Cookies provided by a user agent will identify the
308      * cookie version used by the browser.
309      *
310      * @see #setVersion
311      */

312     public int getVersion ()
313     {
314         return (mVersion);
315     }
316
317     /**
318      * Sets the version of the cookie protocol used when this cookie saves
319      * itself. Since the IETF standards are still being finalized, consider
320      * version 1 as experimental; do not use it (yet) on production sites.
321      *
322      * @see #getVersion
323      */

324     public void setVersion (int version)
325     {
326         mVersion = version;
327     }
328
329     /*
330      * Return true iff the string counts as an HTTP/1.1 "token".
331      */

332     private boolean isToken (String JavaDoc value)
333     {
334         int length;
335         char c;
336         boolean ret;
337         
338         ret = true;
339
340         length = value.length ();
341         for (int i = 0; i < length && ret; i++)
342         {
343             c = value.charAt (i);
344             if (c < 0x20 || c >= 0x7f || mSpecials.indexOf (c) != -1)
345                 ret = false;
346         }
347
348         return (ret);
349     }
350
351     /**
352      * Returns a copy of this object.
353      */

354     public Object JavaDoc clone ()
355     {
356         try
357         {
358             return (super.clone ());
359         }
360         catch (CloneNotSupportedException JavaDoc e)
361         {
362             throw new RuntimeException JavaDoc (e.getMessage ());
363         }
364     }
365
366     /**
367      * Convert this cookie into a user friendly string.
368      * @return A short form string representing this cookie.
369      */

370     public String JavaDoc toString ()
371     {
372         StringBuffer JavaDoc ret;
373         
374         ret = new StringBuffer JavaDoc (50);
375         if (getSecure ())
376             ret.append ("secure ");
377         if (0 != getVersion ())
378         {
379             ret.append ("version ");
380             ret.append (getVersion ());
381             ret.append (" ");
382         }
383         ret.append ("cookie");
384         if (null != getDomain ())
385         {
386             ret.append (" for ");
387             ret.append (getDomain ());
388             
389             if (null != getPath ())
390                 ret.append (getPath ());
391         }
392         else
393         {
394             if (null != getPath ())
395             {
396                 ret.append (" (path ");
397                 ret.append (getPath ());
398                 ret.append (")");
399             }
400         }
401         ret.append (": ");
402         ret.append (getName ());
403         ret.append ("=");
404         if (getValue ().length () > 40)
405         {
406             ret.append (getValue ().substring (1, 40));
407             ret.append ("...");
408         }
409         else
410             ret.append (getValue ());
411         if (null != getComment ())
412         {
413             ret.append (" // ");
414             ret.append (getComment ());
415         }
416         
417         return (ret.toString ());
418     }
419 }
Popular Tags