1   /*
2    * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/Attic/TestCookie.java,v 1.22.2.4 2004/06/05 16:32:01 olegk Exp $
3    * $Revision: 1.22.2.4 $
4    * $Date: 2004/06/05 16:32:01 $
5    * ====================================================================
6    *
7    *  Copyright 1999-2004 The Apache Software Foundation
8    *
9    *  Licensed under the Apache License, Version 2.0 (the "License");
10   *  you may not use this file except in compliance with the License.
11   *  You may obtain a copy of the License at
12   *
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   *
15   *  Unless required by applicable law or agreed to in writing, software
16   *  distributed under the License is distributed on an "AS IS" BASIS,
17   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   *  See the License for the specific language governing permissions and
19   *  limitations under the License.
20   * ====================================================================
21   *
22   * This software consists of voluntary contributions made by many
23   * individuals on behalf of the Apache Software Foundation.  For more
24   * information on the Apache Software Foundation, please see
25   * <http://www.apache.org/>.
26   *
27   * [Additional notices, if required by prior licensing conditions]
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import junit.framework.Test;
34  import junit.framework.TestCase;
35  import junit.framework.TestSuite;
36  import java.util.Date;
37  import java.util.Vector;
38  import java.util.SortedSet;
39  import java.util.TreeSet;
40  import java.util.Iterator;
41  import org.apache.commons.httpclient.cookie.*;
42  
43  
44  /***
45   * Test cases for Cookie
46   *
47   * @author BC Holmes
48   * @author Rod Waldhoff
49   * @author dIon Gillard
50   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
51   * @author Marc A. Saegesser
52   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
53   * @version $Revision: 1.22.2.4 $
54   */
55  public class TestCookie extends TestCase {
56  
57  
58      // -------------------------------------------------------------- Constants
59  
60      private static final String DOMAIN_NAME = "www.apache.org";
61      private static final String TEST_COOKIE = "cookie-name=cookie-value";
62      private static final String OLD_EXPIRY = "Expires=Thu, 01-Jan-1970 00:00:10 GMT";
63      private static final String SEP = ";";
64      private static final String ROOT_PATH = "/";
65      private static final int DEFAULT_PORT = 80;
66  
67      private String[] testName = { "custno", "name", "name" };
68      private String[] testValue = { "12345", "John", "Doe, John" };
69      private String[] testDomain = { "www.apache.org", ".apache.org",
70          ".apache.org" };
71  
72      // ------------------------------------------------------------ Constructor
73  
74  
75      public TestCookie(String name) {
76          super(name);
77      }
78  
79  
80      // ------------------------------------------------------- TestCase Methods
81  
82  
83      public static Test suite() {
84          return new TestSuite(TestCookie.class);
85      }
86  
87  
88      // ------------------------------------------------------- Helper Methods
89  
90  	private static Cookie[] cookieParse(int policy, String host, String path, boolean isSecure, Header setHeader)
91  	  throws MalformedCookieException 
92  	{
93  		CookieSpec parser = CookiePolicy.getSpecByPolicy(policy);
94  		Cookie[] cookies = parser.parse(host, DEFAULT_PORT, path, isSecure, setHeader);
95  		if (cookies != null)
96  		{
97  			for(int i = 0; i < cookies.length; i++)
98  			{
99  				parser.validate(host, DEFAULT_PORT, path, isSecure, cookies[i]);
100 			}
101 		}
102 		return cookies;
103 	}
104 
105 
106 	private static Cookie[] cookieParse(String host, String path, boolean isSecure, Header setHeader)
107 	  throws MalformedCookieException 
108 	{
109 		return cookieParse(CookiePolicy.RFC2109, host, path, isSecure, setHeader);
110 	}
111 
112 
113 	private static Cookie[] cookieParse(String host, String path, Header setHeader)
114 	  throws MalformedCookieException 
115 	{
116 		return cookieParse(CookiePolicy.RFC2109, host, path, false, setHeader);
117 	}
118 
119 
120 	private static Cookie[] netscapeCcookieParse(String host, String path, Header setHeader)
121 	  throws MalformedCookieException 
122 	{
123 		return cookieParse(CookiePolicy.NETSCAPE_DRAFT, host, path, false, setHeader);
124 	}
125 
126 
127     public static Header cookieCreateHeader(int policy, String domain, int port, String path, boolean secure, Cookie[] cookies)
128     {
129         CookieSpec matcher = CookiePolicy.getSpecByPolicy(policy);
130         cookies = matcher.match(domain, port, path, secure, cookies);
131         if ((cookies != null) && (cookies.length > 0))
132         {
133             return matcher.formatCookieHeader(cookies);
134         }
135         else
136         {
137             return null;
138         } 
139     }
140 
141     public static Header cookieCreateHeader(String domain, int port, String path, boolean secure, Cookie[] cookies)
142     {
143     	return cookieCreateHeader(CookiePolicy.RFC2109, domain, port, path, secure, cookies);
144     }
145 
146 
147     public boolean cookieMatch(int policy, String domain, int port, String path, boolean secure, Cookie cookie)
148     {
149         CookieSpec matcher = CookiePolicy.getSpecByPolicy(policy);
150         return matcher.match(domain, port, path, secure, cookie);
151     }
152 
153 
154     public boolean cookieMatch(String domain, int port, String path, boolean secure, Cookie cookie)
155     {
156         return cookieMatch(CookiePolicy.RFC2109, domain, port, path, secure, cookie);
157     }
158 
159     // ------------------------------------------------------------ Parse1 Test
160 
161 
162     /***
163      * Test basic parse (with various spacings
164      */
165     public void testParse1() throws Exception {
166         String headerValue = "custno = 12345; comment=test; version=1," +
167             " name=John; version=1; max-age=600; secure; domain=.apache.org";
168         Cookie[] cookies = cookieParse(DOMAIN_NAME,"/", true, new Header(
169             "set-cookie", headerValue));
170         checkResultsOfParse(cookies, 2, 0);
171     }
172 
173 
174     protected void checkResultsOfParse(
175         Cookie[] cookies, int length, int offset) throws Exception {
176 
177         assertTrue("number of cookies should be " + length + ", but is " +
178                cookies.length + " instead.", cookies.length == length);
179 
180         for (int i = 0; i < cookies.length; i++) {
181 
182             assertTrue("Name of cookie " + i + " should be \"" +
183                    testName[i+offset] + "\", but is " + cookies[i].getName() +
184                    " instead.",
185                    testName[i+offset].equals(cookies[i].getName()));
186             assertTrue("Value of cookie " + i + " should be \"" +
187                    testValue[i+offset] + "\", but is " +
188                    cookies[i].getValue() + " instead.",
189                    testValue[i+offset].equals(cookies[i].getValue()));
190             assertTrue("Domain of cookie " + i + " should be \"" +
191                    testDomain[i+offset] + "\", but is " +
192                    cookies[i].getDomain() + " instead.",
193                    testDomain[i+offset].equalsIgnoreCase(
194                        cookies[i].getDomain()));
195         }
196     }
197 
198 
199     // ------------------------------------------------------------ Parse2 Test
200 
201 
202     /***
203      * Test no spaces
204      */
205     public void testParse2() throws Exception {
206         String headerValue = "custno=12345;comment=test; version=1," +
207             "name=John;version=1;max-age=600;secure;domain=.apache.org";
208         Cookie[] cookies = cookieParse(DOMAIN_NAME, "/", true, new Header(
209             "set-cookie", headerValue));
210         checkResultsOfParse(cookies, 2, 0);
211     }
212 
213 
214     // ------------------------------------------------------------ Parse3 Test
215 
216 
217     /***
218      * Test parse with quoted text
219      */
220     public void testParse3() throws Exception {
221         String headerValue =
222             "name=\"Doe, John\";version=1;max-age=600;secure;domain=.apache.org";
223         Cookie[] cookies = cookieParse(DOMAIN_NAME,"/", true, new Header(
224             "set-cookie", headerValue));
225         checkResultsOfParse(cookies, 1, 2);
226     }
227 
228     // ------------------------------------------------------------- More Tests
229 
230     // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=5279
231     public void testQuotedExpiresAttribute() throws Exception {
232         String headerValue = "custno=12345;Expires='Thu, 01-Jan-2070 00:00:10 GMT'";
233         Cookie[] cookies = cookieParse(DOMAIN_NAME,"/",true,new Header(
234             "set-cookie", headerValue));
235         assertNotNull("Expected some cookies",cookies);
236         assertEquals("Expected 1 cookie",1,cookies.length);
237         assertNotNull("Expected cookie to have getExpiryDate",cookies[0].getExpiryDate());
238     }
239 
240     public void testSecurityError() throws Exception {
241         String headerValue = "custno=12345;comment=test; version=1," +
242             "name=John;version=1;max-age=600;secure;domain=jakarta.apache.org";
243         try {
244             Cookie[] cookies = cookieParse(DOMAIN_NAME, "/", new Header(
245                 "set-cookie", headerValue));
246             fail("HttpException exception should have been thrown");
247         } catch (HttpException e) {
248             // expected
249         }
250     }
251 
252     public void testParseSimple() throws Exception {
253         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value");
254         Cookie[] parsed = cookieParse("127.0.0.1","/path/path",setCookie);
255         assertEquals("Found 1 cookie.",1,parsed.length);
256         assertEquals("Name","cookie-name",parsed[0].getName());
257         assertEquals("Value","cookie-value",parsed[0].getValue());
258         assertTrue("Comment",null == parsed[0].getComment());
259         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
260         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
261         assertTrue("isPersistent",!parsed[0].isPersistent());
262         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
263         assertEquals("Path","/path",parsed[0].getPath());
264         assertTrue("Secure",!parsed[0].getSecure());
265         assertEquals("Version",0,parsed[0].getVersion());
266     }
267  
268  
269     public void testParseSimple2() throws Exception {
270         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value");
271         Cookie[] parsed = cookieParse("127.0.0.1","/path",setCookie);
272         assertEquals("Found 1 cookie.",1,parsed.length);
273         assertEquals("Name","cookie-name",parsed[0].getName());
274         assertEquals("Value","cookie-value",parsed[0].getValue());
275         assertTrue("Comment",null == parsed[0].getComment());
276         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
277         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
278         assertTrue("isPersistent",!parsed[0].isPersistent());
279         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
280         assertEquals("Path","/",parsed[0].getPath());
281         assertTrue("Secure",!parsed[0].getSecure());
282         assertEquals("Version",0,parsed[0].getVersion());
283     }
284  
285  
286     public void testParseNoValue() throws Exception {
287         Header setCookie = new Header("Set-Cookie","cookie-name=");
288         Cookie[] parsed = cookieParse("127.0.0.1","/",setCookie);
289         assertEquals("Found 1 cookie.",1,parsed.length);
290         assertEquals("Name","cookie-name",parsed[0].getName());
291         assertTrue("Value",null == parsed[0].getValue());
292         assertTrue("Comment",null == parsed[0].getComment());
293         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
294         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
295         assertTrue("isPersistent",!parsed[0].isPersistent());
296         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
297         assertEquals("Path","/",parsed[0].getPath());
298         assertTrue("Secure",!parsed[0].getSecure());
299         assertEquals("Version",0,parsed[0].getVersion());
300     }
301 
302     public void testParseWithWhiteSpace() throws Exception {
303         Header setCookie = new Header("Set-Cookie"," cookie-name  =    cookie-value  ");
304         Cookie[] parsed = cookieParse("127.0.0.1","/",setCookie);
305         assertEquals("Found 1 cookie.",1,parsed.length);
306         assertEquals("Name","cookie-name",parsed[0].getName());
307         assertEquals("Value","cookie-value",parsed[0].getValue());
308         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
309         assertEquals("Path","/",parsed[0].getPath());
310         assertTrue("Secure",!parsed[0].getSecure());
311         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
312         assertTrue("Comment",null == parsed[0].getComment());
313     }
314 
315     public void testParseWithQuotes() throws Exception {
316         Header setCookie = new Header("Set-Cookie"," cookie-name  =  \" cookie-value \" ;path=/");
317         Cookie[] parsed = cookieParse("127.0.0.1","/",setCookie);
318         assertEquals("Found 1 cookie.",1,parsed.length);
319         assertEquals("Name","cookie-name",parsed[0].getName());
320         assertEquals("Value"," cookie-value ",parsed[0].getValue());
321         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
322         assertEquals("Path","/",parsed[0].getPath());
323         assertTrue("Secure",!parsed[0].getSecure());
324         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
325         assertTrue("Comment",null == parsed[0].getComment());
326     }
327 
328     public void testParseWithPath() throws Exception {
329         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; Path=/path/");
330         Cookie[] parsed = cookieParse("127.0.0.1","/path/path",setCookie);
331         assertEquals("Found 1 cookie.",1,parsed.length);
332         assertEquals("Name","cookie-name",parsed[0].getName());
333         assertEquals("Value","cookie-value",parsed[0].getValue());
334         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
335         assertEquals("Path","/path/",parsed[0].getPath());
336         assertTrue("Secure",!parsed[0].getSecure());
337         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
338         assertTrue("Comment",null == parsed[0].getComment());
339     }
340 
341     public void testParseWithDomain() throws Exception {
342         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; Domain=127.0.0.1");
343         Cookie[] parsed = cookieParse("127.0.0.1","/",setCookie);
344         assertEquals("Found 1 cookie.",1,parsed.length);
345         assertEquals("Name","cookie-name",parsed[0].getName());
346         assertEquals("Value","cookie-value",parsed[0].getValue());
347         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
348         assertEquals("Path","/",parsed[0].getPath());
349         assertTrue("Secure",!parsed[0].getSecure());
350         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
351         assertTrue("Comment",null == parsed[0].getComment());
352     }
353 
354     public void testParseWithSecure() throws Exception {
355         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; secure");
356         Cookie[] parsed = cookieParse("127.0.0.1","/",true,setCookie);
357         assertEquals("Found 1 cookie.",1,parsed.length);
358         assertEquals("Name","cookie-name",parsed[0].getName());
359         assertEquals("Value","cookie-value",parsed[0].getValue());
360         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
361         assertEquals("Path","/",parsed[0].getPath());
362         assertTrue("Secure",parsed[0].getSecure());
363         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
364         assertTrue("Comment",null == parsed[0].getComment());
365     }
366 
367     public void testParseWithComment() throws Exception {
368         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; comment=\"This is a comment.\"");
369         Cookie[] parsed = cookieParse("127.0.0.1","/",true,setCookie);
370         assertEquals("Found 1 cookie.",1,parsed.length);
371         assertEquals("Name","cookie-name",parsed[0].getName());
372         assertEquals("Value","cookie-value",parsed[0].getValue());
373         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
374         assertEquals("Path","/",parsed[0].getPath());
375         assertTrue("Secure",!parsed[0].getSecure());
376         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
377         assertEquals("Comment","This is a comment.",parsed[0].getComment());
378     }
379 
380     public void testParseWithExpires() throws Exception {
381         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
382         Cookie[] parsed = cookieParse("127.0.0.1","/",true,setCookie);
383         assertEquals("Found 1 cookie.",1,parsed.length);
384         assertEquals("Name","cookie-name",parsed[0].getName());
385         assertEquals("Value","cookie-value",parsed[0].getValue());
386         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
387         assertEquals("Path","/",parsed[0].getPath());
388         assertTrue("Secure",!parsed[0].getSecure());
389         assertEquals(new Date(10000L),parsed[0].getExpiryDate());
390         assertTrue("Comment",null == parsed[0].getComment());
391     }
392 
393     public void testParseWithAll() throws Exception {
394         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Version=1;Path=/commons;Domain=.apache.org;Comment=This is a comment.;secure;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
395         Cookie[] parsed = cookieParse(".apache.org","/commons/httpclient",true,setCookie);
396         assertEquals("Found 1 cookie.",1,parsed.length);
397         assertEquals("Name","cookie-name",parsed[0].getName());
398         assertEquals("Value","cookie-value",parsed[0].getValue());
399         assertEquals("Domain",".apache.org",parsed[0].getDomain());
400         assertEquals("Path","/commons",parsed[0].getPath());
401         assertTrue("Secure",parsed[0].getSecure());
402         assertEquals(new Date(10000L),parsed[0].getExpiryDate());
403         assertEquals("Comment","This is a comment.",parsed[0].getComment());
404         assertEquals("Version",1,parsed[0].getVersion());
405     }
406 
407     public void testParseMultipleDifferentPaths() throws Exception {
408         Header setCookie = new Header("Set-Cookie","name1=value1;Version=1;Path=/commons,name1=value2;Version=1;Path=/commons/httpclient;Version=1");
409         Cookie[] parsed = cookieParse(".apache.org","/commons/httpclient",true,setCookie);
410         HttpState state = new HttpState();
411         state.addCookies(parsed);
412         Cookie[] cookies = state.getCookies();
413         assertEquals("Wrong number of cookies.",2,cookies.length);
414         assertEquals("Name","name1",cookies[0].getName());
415         assertEquals("Value","value1",cookies[0].getValue());
416         assertEquals("Name","name1",cookies[1].getName());
417         assertEquals("Value","value2",cookies[1].getValue());
418     }
419 
420     public void testParseMultipleSamePaths() throws Exception {
421         Header setCookie = new Header("Set-Cookie","name1=value1;Version=1;Path=/commons,name1=value2;Version=1;Path=/commons");
422         Cookie[] parsed = cookieParse(".apache.org","/commons/httpclient",true,setCookie);
423         HttpState state = new HttpState();
424         state.addCookies(parsed);
425         Cookie[] cookies = state.getCookies();
426         assertEquals("Found 1 cookies.",1,cookies.length);
427         assertEquals("Name","name1",cookies[0].getName());
428         assertEquals("Value","value2",cookies[0].getValue());
429     }
430 
431     public void testParseWithWrongDomain() throws Exception {
432         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=127.0.0.1; version=1");
433         try {
434             Cookie[] parsed = cookieParse("127.0.0.2","/",setCookie);
435             fail("HttpException exception should have been thrown");
436         } catch (HttpException e) {
437             // expected
438         }
439     }
440 
441     public void testParseWithWrongDomain2() throws Exception {
442         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=.c.com; version=1");
443         try {
444             Cookie[] parsed = cookieParse("a.b.c.com","/",setCookie);
445             fail("HttpException exception should have been thrown");
446         } catch (HttpException e) {
447             // expected
448         }
449     }
450 
451     /***
452      * Domain has no embedded dots
453      */
454     public void testParseWithIllegalDomain() throws Exception {
455         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=.com; version=1");
456         try {
457             Cookie[] parsed = cookieParse("b.com","/",setCookie);
458             fail("HttpException exception should have been thrown");
459         } catch (HttpException e) {
460             // expected
461         }
462     }
463 
464     /***
465      * Domain has no embedded dots again
466      */
467     public void testParseWithIllegalDomain2() throws Exception {
468         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=.com.; version=1");
469         try {
470             Cookie[] parsed = cookieParse("b.com","/",setCookie);
471             fail("HttpException exception should have been thrown");
472         } catch (HttpException e) {
473             // expected
474         }
475     }
476 
477     public void testParseWithIllegalNetscapeDomain1() throws Exception {
478         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=.com");
479         try {
480             Cookie[] parsed = netscapeCcookieParse("a.com","/",setCookie);
481             fail("HttpException exception should have been thrown");
482         } catch (HttpException e) {
483             // expected
484         }
485     }
486 
487     public void testParseWithWrongNetscapeDomain2() throws Exception {
488         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=.y.z");
489         try {
490             Cookie[] parsed = netscapeCcookieParse("x.y.z","/",setCookie);
491             fail("HttpException exception should have been thrown");
492         } catch (HttpException e) {
493             // expected
494         }
495     }
496 
497     public void testParseWithWrongPath() throws Exception {
498         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=127.0.0.1; path=/not/just/root");
499         try {
500             Cookie[] parsed = cookieParse("127.0.0.1","/",setCookie);
501             fail("HttpException exception should have been thrown");
502         } catch (HttpException e) {
503             // expected
504         }
505     }
506 
507     public void testParseWithNullDomain() {
508         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
509         try {
510             Cookie[] parsed = cookieParse(null,"/",false,setCookie);
511             fail("IllegalArgumentException should have been thrown");
512         } catch (IllegalArgumentException e) {
513             // expected
514         } catch (Exception e){
515             fail("Should have thrown IllegalArgumentException.");
516         }
517     }
518 
519     public void testParseWithNullPath() {
520         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
521         try {
522             Cookie[] parsed = cookieParse("127.0.0.1",null,false,setCookie);
523             fail("IllegalArgumentException should have been thrown");
524         } catch (IllegalArgumentException e) {
525             // expected
526         } catch (Exception e){
527             fail("Should have thrown IllegalArgumentException.");
528         }
529     }
530 
531     public void testParseWithNullDomainAndPath() {
532         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
533         try {
534             Cookie[] parsed = cookieParse(null,null,false,setCookie);
535             fail("IllegalArgumentException should have been thrown");
536         } catch (IllegalArgumentException e) {
537             // expected
538         } catch (Exception e){
539             fail("Should have thrown IllegalArgumentException.");
540         }
541     }
542     
543     public void testParseWithPathMismatch() {
544         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; path=/path/path/path");
545         try {
546             Cookie[] parsed = cookieParse("127.0.0.1","/path",false,setCookie);
547             fail("HttpException should have been thrown.");
548         } catch (HttpException e) {
549             // expected
550         } catch (Exception e){
551             fail("Should have thrown HttpException.");
552         }
553     }
554     
555     public void testParseWithPathMismatch2() {
556         Header setCookie = new Header("Set-Cookie","cookie-name=cookie-value; path=/foobar");
557         try {
558             Cookie[] parsed = cookieParse("127.0.0.1","/foo",false,setCookie);
559             fail("HttpException should have been thrown.");
560         } catch (HttpException e) {
561             // expected
562         } catch (Exception e){
563             fail("Should have thrown HttpException.");
564         }
565     }
566     
567     public void testComparator() throws Exception {
568         Header setCookie = null;
569         Cookie[] parsed = null;
570         Vector cookies = new Vector();
571         // Cookie 0
572         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
573         parsed = cookieParse(".apache.org", "/commons/httpclient", true,
574                               setCookie);
575         cookies.add(parsed[0]);
576         // Cookie 1
577         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
578         parsed = cookieParse(".apache.org","/commons/bif/httpclient",true,setCookie);
579         cookies.add(parsed[0]);
580         // Cookie 2
581         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
582         parsed = cookieParse(".baz.org","/commons/httpclient",true,setCookie);
583         cookies.add(parsed[0]);
584         // Cookie 3
585         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
586         parsed = cookieParse(".baz.org","/commons/bif/httpclient",true,setCookie);
587         cookies.add(parsed[0]);
588         // Cookie 4
589         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.com;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
590         parsed = cookieParse(".baz.com","/commons/httpclient",true,setCookie);
591         cookies.add(parsed[0]);
592         // The order should be:
593         // 1, 0, 3, 2, 4
594         parsed = (Cookie[])cookies.toArray(new Cookie[0]);
595         SortedSet set = new TreeSet(parsed[0]);
596         int pass = 0;
597         for (Iterator itr = set.iterator(); itr.hasNext();) {
598             Cookie cookie = (Cookie)itr.next();
599             switch (pass) {
600                 case 0:
601                     assertTrue("0th cookie should be cookie[1]", cookie == parsed[1]);
602                     break;
603                 case 1:
604                     assertTrue("1st cookie should be cookie[0]", cookie == parsed[0]);
605                     break;
606                 case 2:
607                     assertTrue("2nd cookie should be cookie[3]", cookie == parsed[3]);
608                     break;
609                 case 3:
610                     assertTrue("3rd cookie should be cookie[2]", cookie == parsed[2]);
611                     break;
612                 case 4:
613                     assertTrue("4th cookie should be cookie[4]", cookie == parsed[4]);
614                     break;
615                 default:
616                     fail("This should never happen.");
617             }
618             pass++;
619         }
620         try {
621             parsed[0].compare("foo", "bar");
622             fail("Should have thrown an exception trying to compare non-cookies");
623         }
624         catch (ClassCastException ex) {
625             // expected
626         }
627     }
628     
629     /*** Call Cookie.createCookieHeader providing null for domain to match on
630      */
631     public void testCreateCookieHeaderWithNullDomain() throws Exception {
632         Header setCookie = new Header("Set-Cookie",
633                                       TEST_COOKIE + SEP + OLD_EXPIRY);
634         Cookie[] parsed = cookieParse(DOMAIN_NAME, ROOT_PATH, true, setCookie);
635 
636         try{
637             Header header = cookieCreateHeader(null, DEFAULT_PORT, ROOT_PATH, false, parsed);
638             fail("IllegalArgumentException should have been thrown.");
639         }catch(IllegalArgumentException e){
640             // Expected
641         }catch(Exception e){
642             fail("Threw wrong type of exception.  Expected IllegalArgumentException.");
643         }
644     }
645     
646     /*** Call Cookie.createCookieHeader providing null for path to match on
647      */
648     public void testCreateCookieHeaderWithNullPath() throws Exception{
649         Header setCookie = new Header("Set-Cookie",
650                                       TEST_COOKIE + SEP + OLD_EXPIRY);
651         Cookie[] parsed = cookieParse(DOMAIN_NAME, ROOT_PATH, false, setCookie);
652 
653         try{
654             Header header = cookieCreateHeader(DOMAIN_NAME, DEFAULT_PORT, null, false, parsed);
655             fail("IllegalArgumentException should have been thrown.");
656         }catch(IllegalArgumentException e){
657             // Expected
658         }catch(Exception e){
659             fail("Threw wrong type of exception.  Expected IllegalArgumentException.");
660         }
661     }
662 
663     /***
664      * Verify that cookies with no domain or path don't get added to a cookie header.
665      */
666     public void testCreateCookieHeaderWithUninitializedCookies() throws Exception {
667         Cookie cookies[] = new Cookie[2];
668         cookies[0] = new Cookie(null, "name0", "value0");
669         cookies[1] = new Cookie(null, "name1", "value1", null, null, false);
670 
671         Header header = cookieCreateHeader(DOMAIN_NAME, DEFAULT_PORT, ROOT_PATH, false, cookies);
672         assertEquals("createCookieHeader added cookies with null domains or paths", null, header);
673     }
674 
675     /*** Call Cookie.createCookieHeader providing null for domain and path to
676      * match on
677      */
678     public void testCreateCookieHeaderWithNullDomainAndPath() throws Exception {
679         Header setCookie = new Header("Set-Cookie",
680                                       TEST_COOKIE + SEP + OLD_EXPIRY);
681         Cookie[] parsed = cookieParse(DOMAIN_NAME, ROOT_PATH, true, setCookie);
682 
683         try{
684             Header header = cookieCreateHeader(null, DEFAULT_PORT, null, false, parsed);
685             fail("IllegalArgumentException should have been thrown.");
686         }catch(IllegalArgumentException e){
687             // Expected
688         }catch(Exception e){
689             fail("Threw wrong type of exception.  Expected IllegalArgumentException.");
690         }
691     }
692 
693     /***
694      * Tests several date formats.
695      */
696     public void testDateFormats() throws Exception {
697         //comma, dashes
698         checkDate("Thu, 01-Jan-70 00:00:10 GMT");
699         checkDate("Thu, 01-Jan-2070 00:00:10 GMT");
700         //no comma, dashes
701         checkDate("Thu 01-Jan-70 00:00:10 GMT");
702         checkDate("Thu 01-Jan-2070 00:00:10 GMT");
703         //comma, spaces
704         checkDate("Thu, 01 Jan 70 00:00:10 GMT");
705         checkDate("Thu, 01 Jan 2070 00:00:10 GMT");
706         //no comma, spaces
707         checkDate("Thu 01 Jan 70 00:00:10 GMT");
708         checkDate("Thu 01 Jan 2070 00:00:10 GMT");
709         //weird stuff
710         checkDate("Wed, 20-Nov-2002 09-38-33 GMT");
711 
712 
713         try {
714             checkDate("this aint a date");
715             fail("Date check is bogous");
716         } catch(Exception e) {
717             /* must fail */
718         }
719     }
720 
721     private void checkDate(String date) throws Exception {
722         Header setCookie = new Header("Set-Cookie", "custno=12345;Expires='"+date+"'");
723         cookieParse("localhost","/",setCookie);
724     }
725     
726     
727     /***
728      * Tests default constructor.
729      */
730     public void testDefaultConsttuctor() {
731         Cookie dummy = new Cookie();
732         assertEquals( "noname=", dummy.toExternalForm() );
733     }
734 
735     /***
736      * Tests whether domain attribute check is case-insensitive.
737      */
738     public void testDomainCaseInsensitivity() throws Exception {
739         Header setCookie = new Header(
740           "Set-Cookie", "name=value; path=/; domain=.whatever.com");
741         try {
742             Cookie[] parsed = cookieParse("www.WhatEver.com", "/", false, setCookie );
743         }
744         catch(HttpException e) {
745             e.printStackTrace();
746             fail("Unexpected exception: " + e.toString());
747         }
748     }
749     
750 
751     /***
752      * Tests if cookie constructor rejects cookie name containing blanks.
753      */
754     public void testCookieNameWithBlanks() throws Exception {
755         Header setcookie = new Header("Set-Cookie", "invalid name=");
756         cookieParse(CookiePolicy.COMPATIBILITY, "localhost", "/", false, setcookie); 
757         try {
758             cookieParse(CookiePolicy.RFC2109, "localhost", "/", false, setcookie);
759             fail("MalformedCookieException must have been thrown");
760         }
761         catch(MalformedCookieException e) {
762             // Expected            
763         }
764     }
765 
766 
767     /***
768      * Tests if cookie constructor rejects cookie name starting with $.
769      */
770     public void testCookieNameStartingWithDollarSign() throws Exception {
771         Header setcookie = new Header("Set-Cookie", "$invalid_name=");
772         cookieParse(CookiePolicy.COMPATIBILITY, "localhost", "/", false, setcookie); 
773         try {
774             cookieParse(CookiePolicy.RFC2109, "localhost", "/", false, setcookie); 
775             fail("MalformedCookieException must have been thrown");
776         }
777         catch(MalformedCookieException e) {
778             // Expected            
779         }
780     }
781 
782     /***
783      * Tests if default cookie validator rejects cookies originating from a host without domain
784      * where domain attribute does not match the host of origin 
785      */
786     
787     public void testInvalidDomainWithSimpleHostName() {    
788         CookieSpec parser = CookiePolicy.getDefaultSpec();
789         Header setCookie = null;
790         Cookie[] cookies = null;
791         try {
792             setCookie = new Header(
793             "Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
794             cookies = parser.parse("host", 80, "/", false, setCookie );
795             try {
796                 parser.validate("host", 80, "/", false, cookies[0]);
797                 fail("MalformedCookieException must have thrown");
798             }
799             catch(MalformedCookieException expected) {
800             }
801         }
802         catch(HttpException e) {
803             e.printStackTrace();
804             fail("Unexpected exception: " + e.toString());
805         }
806         try {
807             setCookie = new Header(
808             "Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\"host1\"");
809             cookies = parser.parse("host2", 80, "/", false, setCookie );
810             try {
811                 parser.validate("host2", 80, "/", false, cookies[0]);
812                 fail("MalformedCookieException must have thrown");
813             }
814             catch(MalformedCookieException expected) {
815             }
816         }
817         catch(HttpException e) {
818             e.printStackTrace();
819             fail("Unexpected exception: " + e.toString());
820         }
821     }
822 
823     /***
824      * Makes sure that a cookie matches with a path of the same value.
825      */
826     public void testMatchWithEqualPaths() {
827         
828         Cookie cookie = new Cookie(".test.com", "test", "1", "/test", null, false);
829         
830         try {
831             boolean match = cookieMatch(
832                 "test.test.com", 
833                 80, 
834                 "/test", 
835                 false,
836                 cookie
837             );
838             
839             assertTrue("Cookie paths did not match", match);
840         } catch ( Exception e ) {
841             e.printStackTrace();
842             fail("Unexpected exception: " + e);
843         }
844                    
845     }
846 
847 
848     /***
849      * Tests generic cookie formatting.
850      */
851     
852     public void testGenericCookieFormatting() {
853         Header setCookie = new Header(
854           "Set-Cookie", "name=value; path=/; domain=.mydomain.com");
855         try {
856             CookieSpec parser = CookiePolicy.getSpecByPolicy(CookiePolicy.COMPATIBILITY);
857             Cookie[] cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
858             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
859             String s = parser.formatCookie(cookies[0]);
860             assertEquals("name=value", s);
861         }
862         catch(HttpException e) {
863             e.printStackTrace();
864             fail("Unexpected exception: " + e.toString());
865         }
866     }    
867 
868     /***
869      * Tests Netscape specific cookie formatting.
870      */
871     
872     public void testNetscapeCookieFormatting() {
873         Header setCookie = new Header(
874           "Set-Cookie", "name=value; path=/; domain=.mydomain.com");
875         try {
876             CookieSpec parser = CookiePolicy.getSpecByPolicy(CookiePolicy.NETSCAPE_DRAFT);
877             Cookie[] cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
878             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
879             String s = parser.formatCookie(cookies[0]);
880             assertEquals("name=value", s);
881         }
882         catch(HttpException e) {
883             e.printStackTrace();
884             fail("Unexpected exception: " + e.toString());
885         }
886     }
887     
888 
889     /***
890      * Tests RFC 2109 compiant cookie formatting.
891      */
892     
893     public void testRFC2109CookieFormatting() {
894         CookieSpec parser = CookiePolicy.getSpecByPolicy(CookiePolicy.RFC2109);
895         Header setCookie = null;
896         Cookie[] cookies = null;
897         try {
898             setCookie = new Header(
899             "Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
900             cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
901             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
902             String s1 = parser.formatCookie(cookies[0]);
903             assertEquals(s1, "$Version=\"1\"; name=\"value\"; $Domain=\".mydomain.com\"; $Path=\"/\"");
904 
905             setCookie = new Header(
906             "Set-Cookie", "name=value; path=/; domain=.mydomain.com");
907             cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
908             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
909             String s2 = parser.formatCookie(cookies[0]);
910             assertEquals(s2, "$Version=0; name=value; $Domain=.mydomain.com; $Path=/");
911         }
912         catch(HttpException e) {
913             e.printStackTrace();
914             fail("Unexpected exception: " + e.toString());
915         }
916     }
917 
918 
919     /***
920      * Tests Netscape specific expire attribute parsing.
921      */
922     
923     public void testNetscapeCookieExpireAttribute() {
924         CookieSpec parser = CookiePolicy.getSpecByPolicy(CookiePolicy.NETSCAPE_DRAFT);
925         Header setCookie = null;
926         Cookie[] cookies = null;
927         try {
928             setCookie = new Header(
929               "Set-Cookie", "name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; comment=no_comment");
930             cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
931             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
932         }
933         catch(MalformedCookieException e) {
934             e.printStackTrace();
935             fail("Unexpected exception: " + e.toString());
936         }
937         try {
938             setCookie = new Header(
939               "Set-Cookie", "name=value; path=/; domain=.mydomain.com; expires=Thu 01-Jan-2070 00:00:10 GMT; comment=no_comment");
940             cookies = parser.parse("myhost.mydomain.com", 80, "/", false, setCookie );
941             parser.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
942             fail("MalformedCookieException must have been thrown");
943         }
944         catch(MalformedCookieException e) {
945             //expected
946         }
947     }
948     
949 
950     /***
951      * Tests if null cookie values are handled correctly.
952      */
953     public void testNullCookieValueFormatting() {
954         Cookie cookie = new Cookie(".whatever.com", "name", null, "/", null, false); 
955         cookie.setDomainAttributeSpecified(true);
956         cookie.setPathAttributeSpecified(true);
957 
958         CookieSpec parser = null;
959         String s = null;
960 
961         parser = CookiePolicy.getSpecByPolicy(CookiePolicy.COMPATIBILITY);
962         s = parser.formatCookie(cookie);
963         assertEquals("name=", s);
964 
965         parser = CookiePolicy.getSpecByPolicy(CookiePolicy.RFC2109);
966         s = parser.formatCookie(cookie);
967         assertEquals("$Version=0; name=; $Domain=.whatever.com; $Path=/", s);
968     }
969     
970     /***
971      * Tests if that invalid second domain level cookie gets 
972      * rejected in the strict mode, but gets accepted in the
973      * browser compatibility mode.
974      */
975     public void testSecondDomainLevelCookie() throws Exception {
976         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
977         cookie.setDomainAttributeSpecified(true);
978         cookie.setPathAttributeSpecified(true);
979 
980         CookieSpec parser = null;
981 
982         parser = CookiePolicy.getSpecByPolicy(CookiePolicy.COMPATIBILITY);
983         parser.validate("sourceforge.net", 80, "/", false, cookie);
984 
985         parser = CookiePolicy.getSpecByPolicy(CookiePolicy.RFC2109);
986         try {
987             parser.validate("sourceforge.net", 80, "/", false, cookie);
988             fail("MalformedCookieException should have been thrown");
989         } catch (MalformedCookieException e) {
990             // Expected
991         }
992     }
993 }
994