1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.apache.harmony.tests.java.net;
17
18import junit.framework.TestCase;
19import java.io.IOException;
20import java.net.CookieManager;
21import java.net.CookiePolicy;
22import java.net.CookieStore;
23import java.net.HttpCookie;
24import java.net.URI;
25import java.net.URISyntaxException;
26import java.util.ArrayList;
27import java.util.HashMap;
28import java.util.LinkedHashMap;
29import java.util.List;
30import java.util.Map;
31import java.util.TreeMap;
32
33public class CookieManagerTest extends TestCase {
34
35    private static void checkValidParams4Get(URI uri,
36            Map<String, List<String>> map) throws IOException {
37        CookieManager manager = new CookieManager();
38        try {
39            manager.get(uri, map);
40            fail("Should throw IllegalArgumentException");
41        } catch (IllegalArgumentException e) {
42            // expected
43        }
44
45    }
46
47    private static void checkValidParams4Put(URI uri,
48            Map<String, List<String>> map) throws IOException {
49        CookieManager manager = new CookieManager();
50        try {
51            manager.put(uri, map);
52            fail("Should throw IllegalArgumentException");
53        } catch (IllegalArgumentException e) {
54            // expected
55        }
56
57    }
58
59    /**
60     * {@link java.net.CookieManager#get(java.net.URI, java.util.Map)} &
61     * {@link java.net.CookieManager#put(java.net.URI, java.util.Map)}
62     * IllegalArgumentException
63     * @since 1.6
64     */
65    public void test_Put_Get_LURI_LMap_exception() throws IOException,
66            URISyntaxException {
67        // get
68        checkValidParams4Get(new URI(""), null);
69        checkValidParams4Get(new URI("http://www.test.com"), null);
70        checkValidParams4Get(null, null);
71        checkValidParams4Get(null, new HashMap<String, List<String>>());
72
73        // put
74        checkValidParams4Put(new URI(""), null);
75        checkValidParams4Put(new URI("http://www.test.com"), null);
76        checkValidParams4Put(null, null);
77        checkValidParams4Put(null, new HashMap<String, List<String>>());
78    }
79
80    private static Map<String, List<String>> addCookie(String[][] cookies) {
81        Map<String, List<String>> responseHeaders = new LinkedHashMap<String, List<String>>();
82        for (int i = 0; i < cookies.length; i++) {
83            List<String> fields = new ArrayList<String>();
84            for (int j = 1; j < cookies[i].length; j += 2) {
85                fields.add(cookies[i][j]);
86            }
87            responseHeaders.put(cookies[i][0], fields);
88        }
89        return responseHeaders;
90    }
91
92    private static CookieManager store(String[][] cookies,
93            Map<String, List<String>> responseHeaders, CookiePolicy policy)
94            throws IOException, URISyntaxException {
95        CookieManager manager = new CookieManager(null, policy);
96        // Put all cookies into manager
97        for (int i = 0; i < cookies.length; i++) {
98            for (int j = 2; j < cookies[i].length; j += 2) {
99                URI uri = new URI(cookies[i][j]);
100                manager.put(uri, responseHeaders);
101            }
102        }
103        return manager;
104    }
105
106    /**
107     * Unlike the RI, we flatten all matching cookies into a single Cookie header
108     * instead of sending down multiple cookie headers. Also, when no cookies match
109     * a given URI, we leave the requestHeaders unmodified.
110     *
111     * @since 1.6
112     */
113    public void test_Put_Get_LURI_LMap() throws IOException, URISyntaxException {
114        // cookie-key | (content, URI)...
115        String[][] cookies = {
116                { "Set-cookie",
117                        "Set-cookie:PREF=test;path=/;domain=.b.c;", "http://a.b.c/",
118                        "Set-cookie:PREF1=test2;path=/;domain=.beg.com;", "http://a.b.c/" },
119
120                { "Set-cookie2",
121                        "Set-cookie2:NAME1=VALUE1;path=/te;domain=.b.c;", "http://a.b.c/test" },
122
123                { "Set-cookie",
124                        "Set-cookie2:NAME=VALUE;path=/;domain=.beg.com;", "http://a.beg.com/test",
125                        "Set-cookie2:NAME1=VALUE1;path=/;domain=.beg.com;", "http://a.beg.com/test" },
126
127                { "Set-cookie2",
128                        "Set-cookie3:NAME=VALUE;path=/;domain=.test.org;", "http://a.test.org/test" },
129
130                { null,
131                        "Set-cookie3:NAME=VALUE;path=/te;domain=.test.org;", "http://a.test.org/test" },
132
133                { "Set-cookie2",
134                        "lala", "http://a.test.org/test" }
135
136        };
137
138        // requires path of cookie is the prefix of uri
139        // domain of cookie must match that of uri
140        Map<String, List<String>> responseHeaders = addCookie(new String[][] {
141                cookies[0], cookies[1] });
142        CookieManager manager = store(
143                new String[][] { cookies[0], cookies[1] }, responseHeaders,
144                null);
145
146        HashMap<String, List<String>> dummyMap = new HashMap<String, List<String>>();
147        Map<String, List<String>> map = manager.get(new URI("http://a.b.c/"),
148                dummyMap);
149
150        assertEquals(1, map.size());
151        List<String> list = map.get("Cookie");
152        assertEquals(1, list.size());
153
154        // requires path of cookie is the prefix of uri
155        map = manager.get(new URI("http://a.b.c/te"), dummyMap);
156        list = map.get("Cookie");
157        assertEquals(1, list.size());
158        assertTrue(list.get(0).contains("PREF=test"));
159        // Cookies from "/test" should *not* match the URI "/te".
160        assertFalse(list.get(0).contains("NAME=VALUE"));
161
162        // If all cookies are of version 1, then $version=1 will be added
163        // ,no matter the value cookie-key
164        responseHeaders = addCookie(new String[][] { cookies[2] });
165        manager = store(new String[][] { cookies[2] }, responseHeaders, null);
166        map = manager.get(new URI("http://a.beg.com/test"), dummyMap);
167        list = map.get("Cookie");
168        assertEquals(1, list.size());
169        assertTrue(list.get(0).startsWith("$Version=\"1\""));
170
171        // cookie-key will not have effect on determining cookie version
172        responseHeaders = addCookie(new String[][] { cookies[3] });
173        manager = store(new String[][] { cookies[3] }, responseHeaders, null);
174        map = manager.get(new URI("http://a.test.org/"), responseHeaders);
175        list = map.get("Cookie");
176        assertEquals(1, list.size());
177        assertEquals("Set-cookie3:NAME=VALUE", list.get(0));
178
179        // When key is null, no cookie can be stored/retrieved, even if policy =
180        // ACCEPT_ALL
181        responseHeaders = addCookie(new String[][] { cookies[4] });
182        manager = store(new String[][] { cookies[4] }, responseHeaders,
183                CookiePolicy.ACCEPT_ALL);
184        map = manager.get(new URI("http://a.test.org/"), responseHeaders);
185        list = map.get("Cookie");
186        assertNull(list);
187
188        // All cookies will be rejected if policy == ACCEPT_NONE
189        responseHeaders = addCookie(new String[][] { cookies[3] });
190        manager = store(new String[][] { cookies[3] }, responseHeaders,
191                CookiePolicy.ACCEPT_NONE);
192        map = manager.get(new URI("http://a.test.org/"), responseHeaders);
193        list = map.get("Cookie");
194        assertNull(list);
195
196        responseHeaders = addCookie(new String[][] { cookies[5] });
197        manager = store(new String[][] { cookies[5] }, responseHeaders,
198                CookiePolicy.ACCEPT_ALL);
199        list = map.get("Cookie");
200        assertNull(list);
201
202        try {
203            map.put(null, null);
204            fail("Should throw UnsupportedOperationException");
205        } catch (UnsupportedOperationException e) {
206            // expected
207        }
208
209    }
210
211    /**
212     * {@link java.net.CookieManager#CookieManager()}
213     * @since 1.6
214     */
215    public void test_CookieManager() {
216        CookieManager cookieManager = new CookieManager();
217        assertNotNull(cookieManager);
218        assertNotNull(cookieManager.getCookieStore());
219    }
220
221    /**
222     * {@link java.net.CookieManager#CookieManager(java.net.CookieStore, java.net.CookiePolicy)}
223     * @since 1.6
224     */
225    public void testCookieManager_LCookieStore_LCookiePolicy() {
226        class DummyStore implements CookieStore {
227            public String getName() {
228                return "A dummy store";
229            }
230
231            public void add(URI uri, HttpCookie cookie) {
232                // expected
233            }
234
235            public List<HttpCookie> get(URI uri) {
236                return null;
237            }
238
239            public List<HttpCookie> getCookies() {
240                return null;
241            }
242
243            public List<URI> getURIs() {
244                return null;
245            }
246
247            public boolean remove(URI uri, HttpCookie cookie) {
248                return false;
249            }
250
251            public boolean removeAll() {
252                return false;
253            }
254        }
255        CookieStore store = new DummyStore();
256        CookieManager cookieManager = new CookieManager(store,
257                CookiePolicy.ACCEPT_ALL);
258        assertEquals("A dummy store", ((DummyStore) cookieManager
259                .getCookieStore()).getName());
260        assertSame(store, cookieManager.getCookieStore());
261    }
262
263    /**
264     * {@link java.net.CookieManager#setCookiePolicy(java.net.CookiePolicy)}
265     * @since 1.6
266     */
267    public void test_SetCookiePolicy_LCookiePolicy() throws URISyntaxException,
268            IOException {
269
270        // Policy = ACCEPT_NONE
271        CookieManager manager = new CookieManager();
272        manager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);
273        Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>();
274        URI uri = new URI("http://a.b.c");
275        manager.put(uri, responseHeaders);
276        Map<String, List<String>> map = manager.get(uri,
277                new HashMap<String, List<String>>());
278
279        assertEquals(0, map.size());
280
281        // Policy = ACCEPT_ALL
282        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
283        responseHeaders = new TreeMap<String, List<String>>();
284        ArrayList<String> list = new ArrayList<String>();
285        list.add("test=null");
286        responseHeaders.put("Set-cookie", list);
287        uri = new URI("http://b.c.d");
288        manager.put(uri, responseHeaders);
289        map = manager.get(uri, new HashMap<String, List<String>>());
290        assertEquals(1, map.size());
291    }
292
293    /**
294     * {@link java.net.CookieManager#getCookieStore()}
295     * @since 1.6
296     */
297    public void test_GetCookieStore() {
298        CookieManager cookieManager = new CookieManager();
299        CookieStore store = cookieManager.getCookieStore();
300        assertNotNull(store);
301    }
302
303}
304