OldURLTest.java revision 6e65088f21ac5bda5d25fade13ee360c5cba3457
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 */
16
17package libcore.java.net;
18
19import dalvik.annotation.TestLevel;
20import dalvik.annotation.TestTargetClass;
21import dalvik.annotation.TestTargetNew;
22import java.io.BufferedReader;
23import java.io.BufferedWriter;
24import java.io.File;
25import java.io.FileWriter;
26import java.io.IOException;
27import java.io.InputStream;
28import java.io.InputStreamReader;
29import java.lang.reflect.Field;
30import java.net.MalformedURLException;
31import java.net.Proxy;
32import java.net.ProxySelector;
33import java.net.SocketAddress;
34import java.net.URI;
35import java.net.URISyntaxException;
36import java.net.URL;
37import java.net.URLConnection;
38import java.net.URLStreamHandler;
39import java.net.URLStreamHandlerFactory;
40import java.security.Permission;
41import java.util.ArrayList;
42import java.util.Arrays;
43import java.util.List;
44import junit.framework.TestCase;
45
46@TestTargetClass(URL.class)
47public class OldURLTest extends TestCase {
48
49    private static final String helloWorldString = "Hello World";
50
51    @Override protected void setUp() throws Exception {
52        super.setUp();
53    }
54
55    @Override protected void tearDown() throws Exception {
56        super.tearDown();
57    }
58
59    /**
60     * @tests java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String)
61     */
62    @TestTargetNew(
63        level = TestLevel.COMPLETE,
64        notes = "Regression test.",
65        method = "URL",
66        args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class}
67    )
68    public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_String()
69            throws MalformedURLException {
70        // Regression for HARMONY-83
71        new URL("http", "apache.org", 123456789, "file");
72        try {
73            new URL("http", "apache.org", -123, "file");
74            fail("Assert 0: Negative port should throw exception");
75        } catch (MalformedURLException e) {
76            // expected
77        }
78    }
79
80    /**
81     * @tests java.net.URL#URL(java.lang.String, java.lang.String,
82     *        java.lang.String)
83     */
84    @TestTargetNew(
85        level = TestLevel.COMPLETE,
86        notes = "",
87        method = "URL",
88        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
89    )
90    public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() throws MalformedURLException {
91        // Strange behavior in reference, the hostname contains a ':' so it gets wrapped in '[', ']'
92        URL testURL = new URL("http", "www.apache.org:8082", "test.html#anch");
93        assertEquals("Assert 0: wrong protocol", "http", testURL.getProtocol());
94        assertEquals("Assert 1: wrong host", "[www.apache.org:8082]", testURL.getHost());
95        assertEquals("Assert 2: wrong port", -1, testURL.getPort());
96        assertEquals("Assert 3: wrong file", "test.html", testURL.getFile());
97        assertEquals("Assert 4: wrong anchor", "anch", testURL.getRef());
98
99        try {
100            new URL("hftp", "apache.org:8082", "test.html#anch");
101            fail("Assert 0: Invalid protocol");
102        } catch (MalformedURLException e) {
103            // expected
104        }
105    }
106
107    /**
108     * @tests java.net.URL#URL(String, String, String)
109     *
110     */
111    @TestTargetNew(
112        level = TestLevel.PARTIAL,
113        notes = "Regression test.",
114        method = "URL",
115        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
116    )
117    public void test_java_protocol_handler_pkgs_prop() throws MalformedURLException {
118        // Regression test for Harmony-3094
119        final String HANDLER_PKGS = "java.protocol.handler.pkgs";
120        System.setProperty(HANDLER_PKGS, "fake|org.apache.harmony.luni.tests.java.net");
121
122        try {
123            new URL("test_protocol", "", "fake.jar");
124        } catch (MalformedURLException e) {
125            // expected
126        }
127    }
128
129    /**
130     * Test method for {@link java.net.URL#hashCode()}.
131     */
132    @TestTargetNew(
133        level = TestLevel.COMPLETE,
134        notes = "",
135        method = "hashCode",
136        args = {}
137    )
138    public void testHashCode() throws MalformedURLException {
139        URL testURL1 = new URL("http", "www.apache.org:8080", "test.html#anch");
140        URL testURL2 = new URL("http", "www.apache.org:8080", "test.html#anch");
141        URL changedURL = new URL("http", "www.apache.org:8082",
142                "test.html#anch");
143        assertEquals("Assert 0: error in hashCode: not same",
144                testURL1.hashCode(), testURL2.hashCode());
145        assertFalse("Assert 0: error in hashCode: should be same", testURL1
146                .hashCode() == changedURL.hashCode());
147    }
148
149    /**
150     * Test method for {@link java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)}.
151     */
152    @TestTargetNew(
153        level = TestLevel.SUFFICIENT,
154        notes = "cannot test since no sophisticated StreamHandlerFactory available.",
155        method = "setURLStreamHandlerFactory",
156        args = {java.net.URLStreamHandlerFactory.class}
157    )
158    public void testSetURLStreamHandlerFactory() throws MalformedURLException, IOException, IllegalArgumentException, IllegalAccessException {
159        URLStreamHandlerFactory factory = new MyURLStreamHandlerFactory();
160        Field streamHandlerFactoryField = null;
161        int counter = 0;
162        File sampleFile = createTempHelloWorldFile();
163
164        URL fileURL = sampleFile.toURL();
165
166
167        Field[] fields = URL.class.getDeclaredFields();
168
169
170        for (Field f : fields) {
171            if (URLStreamHandlerFactory.class.equals(f.getType())) {
172                counter++;
173                streamHandlerFactoryField = f;
174            }
175        }
176
177        if (counter != 1) {
178            fail("Error in test setup: not Factory found");
179        }
180
181        streamHandlerFactoryField.setAccessible(true);
182        URLStreamHandlerFactory old = (URLStreamHandlerFactory) streamHandlerFactoryField.get(null);
183
184        try {
185            streamHandlerFactoryField.set(null, factory);
186            BufferedReader buf = new BufferedReader(new InputStreamReader(
187                    fileURL.openStream()), helloWorldString.getBytes().length);
188            String nextline;
189            while ((nextline = buf.readLine()) != null) {
190                assertEquals(helloWorldString, nextline);
191            }
192
193            buf.close();
194
195        } finally {
196
197            streamHandlerFactoryField.set(null, old);
198        }
199
200    }
201
202    /**
203     * Test method for {@link java.net.URL#URL(java.lang.String)}.
204     */
205    @TestTargetNew(
206        level = TestLevel.COMPLETE,
207        notes = "",
208        method = "URL",
209        args = {java.lang.String.class}
210    )
211    public void testURLString() throws MalformedURLException {
212        URL testURL = new URL("ftp://myname@host.dom/etc/motd");
213
214        assertEquals("Assert 0: wrong protocol", "ftp", testURL.getProtocol());
215        assertEquals("Assert 1: wrong host", "host.dom", testURL.getHost());
216        assertEquals("Assert 2: wrong port", -1, testURL.getPort());
217        assertEquals("Assert 3: wrong userInfo", "myname", testURL
218                .getUserInfo());
219        assertEquals("Assert 4: wrong path", "/etc/motd", testURL.getPath());
220
221        try {
222            new URL("ftpmyname@host.dom/etc/motd");
223            fail("Assert 0: malformed URL should throw exception");
224        } catch (MalformedURLException e) {
225            // expected
226        }
227
228    }
229
230    /**
231     * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String)}.
232     */
233    @TestTargetNew(
234        level = TestLevel.COMPLETE,
235        notes = "",
236        method = "URL",
237        args = {java.net.URL.class, java.lang.String.class}
238    )
239    public void testURLURLString() throws MalformedURLException {
240
241        URL gamelan = new URL("http://www.gamelan.com/pages/");
242
243        URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
244        URL gamelanNetworkBottom = new URL(gamelanNetwork, "#BOTTOM");
245        assertEquals("Assert 0: wrong anchor", "BOTTOM", gamelanNetworkBottom
246                .getRef());
247        assertEquals("Assert 1: wrong protocol", "http", gamelanNetworkBottom
248                .getProtocol());
249
250        // same protocol
251        URL gamelanNetworBottom2 = new URL(gamelanNetwork,
252                "http://www.gamelan.com/pages/Gamelan.net.html#BOTTOM");
253        assertEquals(gamelanNetwork.getProtocol(), gamelanNetworBottom2.getProtocol());
254
255        // changed protocol
256        URL gamelanNetworkBottom3 = new URL(gamelanNetwork,
257                "ftp://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
258        URL absoluteNew = new URL(
259                "ftp://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
260        assertEquals("Host of context URL instead of new URL", "ftp",
261                gamelanNetworkBottom3.getProtocol());
262        assertTrue("URL is context URL instead of new URL",
263                gamelanNetworkBottom3.sameFile(absoluteNew));
264
265        // exception testing
266        try {
267            u = null;
268            u1 = new URL(u, "somefile.java");
269            fail("didn't throw the expected MalFormedURLException");
270        } catch (MalformedURLException e) {
271            // ok
272        }
273
274        // Non existing protocol
275     // exception testing
276        try {
277        u  =  new URL(gamelanNetwork,
278                    "someFancyNewProt://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
279        assertTrue("someFancyNewProt".equalsIgnoreCase(u.getProtocol()));
280        } catch (MalformedURLException e) {
281            // ok
282        }
283    }
284
285    /**
286     * Test method for {@link java.net.URL#equals(java.lang.Object)}.
287     */
288    @TestTargetNew(
289        level = TestLevel.COMPLETE,
290        notes = "",
291        method = "equals",
292        args = {java.lang.Object.class}
293    )
294    public void testEqualsObject() throws MalformedURLException {
295        URL testURL1 = new URL("http", "www.apache.org:8080", "test.html");
296        URL wrongProto = new URL("ftp", "www.apache.org:8080", "test.html");
297        URL wrongPort = new URL("http", "www.apache.org:8082", "test.html");
298        URL wrongHost = new URL("http", "www.apache2.org:8080", "test.html");
299        URL wrongRef = new URL("http", "www.apache.org:8080",
300                "test2.html#BOTTOM");
301        URL testURL2 = new URL("http://www.apache.org:8080/test.html");
302
303
304        assertFalse("Assert 0: error in equals: not same", testURL1
305                .equals(wrongProto));
306        assertFalse("Assert 1: error in equals: not same", testURL1
307                .equals(wrongPort));
308        assertFalse("Assert 2: error in equals: not same", testURL1
309                .equals(wrongHost));
310        assertFalse("Assert 3: error in equals: not same", testURL1
311                .equals(wrongRef));
312
313        assertFalse("Assert 4: error in equals: not same", testURL1
314                .equals(testURL2));
315
316        URL testURL3 = new URL("http", "www.apache.org", "/test.html");
317        URL testURL4 = new URL("http://www.apache.org/test.html");
318        assertTrue("Assert 4: error in equals: same", testURL3
319                .equals(testURL4));
320    }
321
322    /**
323     * Test method for {@link java.net.URL#sameFile(java.net.URL)}.
324     */
325    @TestTargetNew(
326        level = TestLevel.COMPLETE,
327        notes = "non trivial reference test fails",
328        method = "sameFile",
329        args = {java.net.URL.class}
330    )
331    public void testSameFile() throws MalformedURLException {
332        URL gamelan = new URL("file:///pages/index.html");
333        URL gamelanFalse = new URL("file:///pages/out/index.html");
334
335        URL gamelanNetwork = new URL(gamelan, "#BOTTOM");
336        assertTrue(gamelanNetwork.sameFile(gamelan));
337
338        assertFalse(gamelanNetwork.sameFile(gamelanFalse));
339
340        // non trivial test
341        URL url = new URL("http://web2.javasoft.com/some+file.html");
342        URL url1 = new URL("http://web2.javasoft.com/some%20file.html");
343
344        assertFalse(url.sameFile(url1));
345    }
346
347    /**
348     * Test method for {@link java.net.URL#getContent()}.
349     */
350    @TestTargetNew(
351        level = TestLevel.COMPLETE,
352        notes = "image and sound content not testable: mime types",
353        method = "getContent",
354        args = {}
355    )
356    public void testGetContent() throws MalformedURLException {
357
358        File sampleFile = createTempHelloWorldFile();
359
360        // read content from file
361        URL fileURL = sampleFile.toURL();
362
363        try {
364            InputStream output = (InputStream) fileURL.getContent();
365            assertTrue(output.available() > 0);
366            // ok
367        } catch (Exception e) {
368            fail("Did not get output type from File URL");
369        }
370
371        //Exception test
372        URL invalidFile = new URL("file:///nonexistenttestdir/tstfile");
373
374        try {
375            invalidFile.getContent();
376            fail("Access to invalid file worked");
377        } catch (IOException e) {
378            //ok
379        }
380
381    }
382
383    /**
384     * Test method for {@link java.net.URL#openStream()}.
385     */
386    @TestTargetNew(
387        level = TestLevel.COMPLETE,
388        notes = "",
389        method = "openStream",
390        args = {}
391    )
392    public void testOpenStream() throws MalformedURLException, IOException {
393
394        File sampleFile = createTempHelloWorldFile();
395
396        // read content from file
397        URL fileURL = sampleFile.toURL();
398        BufferedReader dis = null;
399        String inputLine;
400        StringBuffer buf = new StringBuffer(32);
401        try {
402            dis = new BufferedReader(
403                    new InputStreamReader(fileURL.openStream()), 32);
404            while ((inputLine = dis.readLine()) != null) {
405                buf.append(inputLine);
406            }
407            dis.close();
408        } catch (IOException e) {
409            fail("Unexpected error in test setup: " + e.getMessage());
410        }
411
412        assertTrue("Assert 0: Nothing was read from file ", buf.length() > 0);
413        assertEquals("Assert 1: Wrong stream content", "Hello World", buf
414                .toString());
415
416        // exception test
417
418        URL invalidFile = new URL("file:///nonexistenttestdir/tstfile");
419
420        try {
421            dis = new BufferedReader(
422                    new InputStreamReader(invalidFile.openStream()), 32);
423            while ((inputLine = dis.readLine()) != null) {
424                buf.append(inputLine);
425            }
426            fail("Access to invalid file worked");
427        } catch (Exception e) {
428            //ok
429        } finally {
430            dis.close();
431        }
432    }
433
434    /**
435     * Test method for {@link java.net.URL#openConnection()}.
436     */
437    @TestTargetNew(
438        level = TestLevel.COMPLETE,
439        notes = "",
440        method = "openConnection",
441        args = {}
442    )
443    public void testOpenConnection() throws MalformedURLException, IOException {
444
445        File sampleFile = createTempHelloWorldFile();
446
447        byte[] ba;
448        InputStream is;
449        String s;
450        u = sampleFile.toURL();
451        u.openConnection();
452
453        is = (InputStream) u.getContent(new Class[] { Object.class });
454        is.read(ba = new byte[4096]);
455        s = new String(ba);
456        assertTrue("Incorrect content " + u
457                + " does not contain: \"Hello World\"",
458                s.indexOf("Hello World") >= 0);
459
460        try {
461            URL u = new URL("https://a.xy.com/index.html");
462            URLConnection conn = u.openConnection();
463            conn.connect();
464            fail("Should not be able to read from this site.");
465        } catch (IOException e) {
466            //ok
467        }
468
469        System.setSecurityManager(new MockSecurityManager());
470        try {
471            URL u = new URL("http://127.0.0.1");
472            URLConnection conn = u.openConnection();
473            conn.connect();
474            fail("Should not be able to read from this site.");
475        } catch (SecurityException e) {
476            //ok
477        } finally {
478            System.setSecurityManager(null);
479        }
480
481    }
482
483    /**
484     * Test method for {@link java.net.URL#toURI()}.
485     */
486    @TestTargetNew(
487        level = TestLevel.COMPLETE,
488        notes = "",
489        method = "toURI",
490        args = {}
491    )
492    public void testToURI() throws MalformedURLException, URISyntaxException {
493        String testHTTPURLString = "http://www.gamelan.com/pages/";
494        String testFTPURLString = "ftp://myname@host.dom/etc/motd";
495        URL testHTTPURL = new URL(testHTTPURLString);
496        URL testFTPURL = new URL(testFTPURLString);
497
498        URI testHTTPURI = testHTTPURL.toURI();
499        URI testFTPURI = testFTPURL.toURI();
500        assertEquals(testHTTPURI.toString(),testHTTPURLString);
501        assertEquals(testFTPURI.toString(),testFTPURLString);
502
503        //Exception test
504        String[] constructorTestsInvalid = new String[] {
505                "http:///a path#frag", // space char in path, not in escaped
506                // octet form, with no host
507                "http://host/a[path#frag", // an illegal char, not in escaped
508                // octet form, should throw an
509                // exception
510                "http://host/a%path#frag", // invalid escape sequence in path
511                "http://host/a%#frag", // incomplete escape sequence in path
512
513                "http://host#a frag", // space char in fragment, not in
514                // escaped octet form, no path
515                "http://host/a#fr#ag", // illegal char in fragment
516                "http:///path#fr%ag", // invalid escape sequence in fragment,
517                // with no host
518                "http://host/path#frag%", // incomplete escape sequence in
519                // fragment
520
521                "http://host/path?a query#frag", // space char in query, not
522                // in escaped octet form
523                "http://host?query%ag", // invalid escape sequence in query, no
524                // path
525                "http:///path?query%", // incomplete escape sequence in query,
526                // with no host
527
528                "mailto:user^name@fklkf.com" // invalid char in scheme
529        };
530
531        for (String malformedURI : Arrays.asList(constructorTestsInvalid)) {
532            try {
533                URL urlQuery = new URL("http://host/a%path#frag");
534                urlQuery.toURI();
535                fail("Exception expected");
536            } catch (URISyntaxException e) {
537                // ok
538            }
539        }
540    }
541
542    /**
543     * Test method for {@link java.net.URL#toString()}.
544     */
545    @TestTargetNew(
546        level = TestLevel.COMPLETE,
547        notes = "",
548        method = "toString",
549        args = {}
550    )
551    public void testToString() throws MalformedURLException {
552        URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
553        URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
554
555        assertEquals(testHTTPURL.toString(),testHTTPURL.toExternalForm());
556        assertEquals(testFTPURL.toString(),testFTPURL.toExternalForm());
557
558        assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toString());
559    }
560
561    /**
562     * Test method for {@link java.net.URL#toExternalForm()}.
563     */
564    @TestTargetNew(
565        level = TestLevel.PARTIAL_COMPLETE,
566        notes = "simple tests",
567        method = "toExternalForm",
568        args = {}
569    )
570    public void testToExternalForm() throws MalformedURLException {
571        URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
572        URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
573
574        assertEquals(testHTTPURL.toString(),testHTTPURL.toExternalForm());
575        assertEquals(testFTPURL.toString(),testFTPURL.toExternalForm());
576
577        assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toExternalForm());
578    }
579
580    /**
581     * Test method for {@link java.net.URL#getFile()}.
582     */
583    @TestTargetNew(
584        level = TestLevel.COMPLETE,
585        notes = "",
586        method = "getFile",
587        args = {}
588    )
589    public void testGetFile() throws MalformedURLException {
590
591        File sampleFile = createTempHelloWorldFile();
592
593        // read content from file
594        URL fileURL = sampleFile.toURL();
595        assertNotNull(fileURL);
596        assertEquals(sampleFile.getPath(),fileURL.getFile());
597    }
598
599    /**
600     * Test method for {@link java.net.URL#getPort()}.
601     */
602    @TestTargetNew(
603        level = TestLevel.COMPLETE,
604        notes = "",
605        method = "getPort",
606        args = {}
607    )
608    public void testGetPort() throws MalformedURLException {
609        URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
610        URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
611
612        assertEquals(-1,testFTPURL.getPort());
613        assertEquals(-1,testHTTPURL.getPort());
614
615        URL testHTTPURL8082 = new URL("http://www.gamelan.com:8082/pages/");
616        assertEquals(8082, testHTTPURL8082.getPort());
617
618    }
619
620    /**
621     * Test method for {@link java.net.URL#getProtocol()}.
622     */
623    @TestTargetNew(
624      level = TestLevel.COMPLETE,
625      notes = "",
626      method = "getProtocol",
627      args = {}
628    )
629    public void testGetProtocol() throws MalformedURLException {
630        URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
631        URL testHTTPSURL = new URL("https://www.gamelan.com/pages/");
632        URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
633        URL testFile = new URL("file:///pages/index.html");
634        URL testJarURL = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
635
636        assertTrue("http".equalsIgnoreCase(testHTTPURL.getProtocol()));
637        assertTrue("https".equalsIgnoreCase(testHTTPSURL.getProtocol()));
638        assertTrue("ftp".equalsIgnoreCase(testFTPURL.getProtocol()));
639        assertTrue("file".equalsIgnoreCase(testFile.getProtocol()));
640        assertTrue("jar".equalsIgnoreCase(testJarURL.getProtocol()));
641
642    }
643
644    /**
645     * Test method for {@link java.net.URL#getRef()}.
646     */
647    @TestTargetNew(
648        level = TestLevel.COMPLETE,
649        notes = "",
650        method = "getRef",
651        args = {}
652    )
653    public void testGetRef() throws MalformedURLException {
654        URL gamelan = new URL("http://www.gamelan.com/pages/");
655
656        String output = gamelan.getRef();
657        assertTrue(output == null || output.equals(""));
658
659        URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html#BOTTOM");
660        assertEquals("BOTTOM", gamelanNetwork.getRef());
661
662        URL gamelanNetwork2 = new URL("http", "www.gamelan.com",
663                "Gamelan.network.html#BOTTOM");
664
665        assertEquals("BOTTOM", gamelanNetwork2.getRef());
666
667    }
668
669    /**
670     * Test method for {@link java.net.URL#getQuery()}.
671     */
672    @TestTargetNew(
673        level = TestLevel.COMPLETE,
674        notes = "",
675        method = "getQuery",
676        args = {}
677    )
678    public void testGetQuery() throws MalformedURLException {
679        URL urlQuery = new URL(
680                "http://www.example.com/index.html?attrib1=value1&attrib2=value&attrib3#anchor");
681        URL urlNoQuery = new URL(
682        "http://www.example.com/index.html#anchor");
683
684        assertEquals("attrib1=value1&attrib2=value&attrib3", urlQuery.getQuery());
685
686        String output = urlNoQuery.getQuery();
687        assertTrue(output == null || "".equals(output));
688    }
689
690    /**
691     * Test method for {@link java.net.URL#getPath()}.
692     */
693    @TestTargetNew(
694        level = TestLevel.COMPLETE,
695        notes = "",
696        method = "getPath",
697        args = {}
698    )
699    public void testGetPath() throws MalformedURLException {
700        URL url = new URL("http://www.example.com");
701        String output = url.getPath();
702
703        assertTrue("".equals(output) || output == null);
704
705        URL url2 = new URL(url,"/foo/index.html");
706        assertEquals("/foo/index.html",url2.getPath());
707    }
708
709    /**
710     * Test method for {@link java.net.URL#getUserInfo()}.
711     */
712    @TestTargetNew(
713        level = TestLevel.COMPLETE,
714        notes = "",
715        method = "getUserInfo",
716        args = {}
717    )
718    public void testGetUserInfo() throws MalformedURLException {
719        URL urlNoUserInfo = new URL("http://www.java2s.com:8080");
720        URL url = new URL("ftp://myUser:password@host.dom/etc/motd");
721
722        assertEquals("Assert 0: Wrong user","myUser:password",url.getUserInfo());
723        String userInfo = urlNoUserInfo.getUserInfo();
724        assertTrue("".equals(userInfo) || null == userInfo);
725    }
726
727    /**
728     * Test method for {@link java.net.URL#getAuthority()}.
729     */
730    @TestTargetNew(
731        level = TestLevel.COMPLETE,
732        notes = "",
733        method = "getAuthority",
734        args = {}
735    )
736    public void testGetAuthority() throws MalformedURLException, URISyntaxException {
737        // legal authority information userInfo (user,password),domain,port
738
739        URL url = new URL("http://www.java2s.com:8080");
740        assertEquals("Assert 0: Wrong authority ", "www.java2s.com:8080", url
741                .getAuthority());
742
743        URL ftpURL = new URL("ftp://myname@host.dom/etc/motd");
744        assertEquals("Assert 1: Wrong authority ", "myname@host.dom", ftpURL
745                .getAuthority());
746
747        URI testURI = new URI("/relative/URI/with/absolute/path/to/resource.txt");
748        String output = testURI.getAuthority();
749        assertTrue("".equals(output) || null == output);
750    }
751
752    /**
753     * Test method for {@link java.net.URL#getDefaultPort()}.
754     */
755    @TestTargetNew(
756        level = TestLevel.COMPLETE,
757        notes = "",
758        method = "getDefaultPort",
759        args = {}
760    )
761    public void testGetDefaultPort() throws MalformedURLException {
762        URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
763        URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
764
765        assertEquals(21,testFTPURL.getDefaultPort());
766        assertEquals(80,testHTTPURL.getDefaultPort());
767    }
768
769    private File createTempHelloWorldFile() {
770        // create content to read
771        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
772        File sampleFile = null;
773        try {
774            if (tmpDir.isDirectory()) {
775                sampleFile = File.createTempFile("openStreamTest", ".txt",
776                        tmpDir);
777                sampleFile.deleteOnExit();
778            } else {
779                fail("Error in test setup java.io.tmpdir does not exist");
780            }
781
782            FileWriter fstream = new FileWriter(sampleFile);
783            BufferedWriter out = new BufferedWriter(fstream, 32);
784            out.write(helloWorldString);
785            // Close the output stream
786            out.close();
787        } catch (Exception e) {// Catch exception if any
788            fail("Error: in test setup" + e.getMessage());
789        }
790
791        return sampleFile;
792    }
793
794    // start HARMONY branch
795
796    public static class MyHandler extends URLStreamHandler {
797        protected URLConnection openConnection(URL u)
798                throws IOException {
799            return null;
800        }
801    }
802
803    URL u;
804
805    URL u1;
806
807    URL u2;
808
809    boolean caught = false;
810
811    static boolean isSelectCalled;
812
813
814
815    static class MockProxySelector extends ProxySelector {
816
817        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
818            System.out.println("connection failed");
819        }
820
821        public List<Proxy> select(URI uri) {
822            isSelectCalled = true;
823            ArrayList<Proxy> proxyList = new ArrayList<Proxy>(1);
824            proxyList.add(Proxy.NO_PROXY);
825            return proxyList;
826        }
827    }
828
829    static class MockSecurityManager extends SecurityManager {
830
831        public void checkConnect(String host, int port) {
832            if ("127.0.0.1".equals(host)) {
833                throw new SecurityException("permission is not allowed");
834            }
835        }
836
837        public void checkPermission(Permission permission) {
838            if ("setSecurityManager".equals(permission.getName())) {
839                return;
840            }
841            super.checkPermission(permission);
842        }
843
844    }
845
846
847    static class MyURLStreamHandler extends URLStreamHandler {
848
849        @Override
850        protected URLConnection openConnection(URL arg0) throws IOException {
851            try {
852                URLConnection con = arg0.openConnection();
853                con.setDoInput(true);
854                con.connect();
855                return con;
856            } catch (Throwable e) {
857                return null;
858            }
859        }
860
861        public void parse(URL url, String spec, int start, int end) {
862            parseURL(url, spec, start, end);
863        }
864    }
865
866    static class MyURLStreamHandlerFactory implements URLStreamHandlerFactory {
867
868        public static MyURLStreamHandler handler = new MyURLStreamHandler();
869
870        public URLStreamHandler createURLStreamHandler(String arg0) {
871            handler = new MyURLStreamHandler();
872            return handler;
873        }
874
875    }
876
877    /**
878     * URLStreamHandler implementation class necessary for tests.
879     */
880    private class TestURLStreamHandler extends URLStreamHandler {
881        public URLConnection openConnection(URL arg0) throws IOException {
882            try {
883                URLConnection con = arg0.openConnection();
884                con.setDoInput(true);
885                con.connect();
886                return con;
887            } catch (Throwable e) {
888                return null;
889            }
890        }
891
892        public URLConnection openConnection(URL arg0, Proxy proxy)
893                throws IOException {
894            return super.openConnection(u, proxy);
895        }
896    }
897
898    /**
899     * Test method for {@link java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String, java.net.URLStreamHandler)}.
900     */
901    @TestTargetNew(
902        level = TestLevel.COMPLETE,
903        notes = "From harmony branch. No meaningful MalformedURLException foundwhich doesn't end as a NullPointerException.",
904        method = "URL",
905        args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.net.URLStreamHandler.class}
906    )
907    public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
908            throws Exception {
909        u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", null);
910        assertEquals("SSISH1 returns a wrong protocol", "http", u.getProtocol());
911        assertEquals("SSISH1 returns a wrong host", "www.yahoo.com", u
912                .getHost());
913        assertEquals("SSISH1 returns a wrong port", 8080, u.getPort());
914        assertEquals("SSISH1 returns a wrong file", "test.html", u.getFile());
915        assertTrue("SSISH1 returns a wrong anchor: " + u.getRef(), u.getRef()
916                .equals("foo"));
917
918        u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
919                new MyHandler());
920        assertEquals("SSISH2 returns a wrong protocol", "http", u.getProtocol());
921        assertEquals("SSISH2 returns a wrong host", "www.yahoo.com", u
922                .getHost());
923        assertEquals("SSISH2 returns a wrong port", 8080, u.getPort());
924        assertEquals("SSISH2 returns a wrong file", "test.html", u.getFile());
925        assertTrue("SSISH2 returns a wrong anchor: " + u.getRef(), u.getRef()
926                .equals("foo"));
927
928        TestURLStreamHandler lh = new TestURLStreamHandler();
929        u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
930                lh);
931
932        try {
933            new URL(null, "1", 0, "file", lh);
934            fail("Exception expected, but nothing was thrown!");
935        } catch (MalformedURLException e) {
936            // ok
937        } catch (NullPointerException e) {
938            // Expected NullPointerException
939        }
940
941    }
942
943    /**
944     * Test method for {@link java.net.URL#getContent(java.lang.Class[])}.
945     */
946    @TestTargetNew(
947        level = TestLevel.COMPLETE,
948        notes = "throws unexpected exception: NullPointerException in first execution",
949        method = "getContent",
950        args = {java.lang.Class[].class}
951    )
952    public void test_getContent_LJavaLangClass() throws Exception {
953
954        File sampleFile = createTempHelloWorldFile();
955
956        byte[] ba;
957        String s;
958
959        InputStream is = null;
960
961        try {
962            u = new URL("file:///data/tmp/hyts_htmltest.html");
963            is = (InputStream) u.getContent(new Class[] {InputStream.class});
964            is.read(ba = new byte[4096]);
965            fail("No error occurred reading from nonexisting file");
966        } catch (IOException e) {
967            // ok
968        }
969
970        try {
971            u = new URL("file:///data/tmp/hyts_htmltest.html");
972            is = (InputStream) u.getContent(new Class[] {
973                    String.class, InputStream.class});
974            is.read(ba = new byte[4096]);
975            fail("No error occurred reading from nonexisting file");
976        } catch (IOException e) {
977            // ok
978        }
979
980        // Check for null
981        u = sampleFile.toURL();
982        u.openConnection();
983        assertNotNull(u);
984
985        s = (String) u.getContent(new Class[] {String.class});
986        assertNull(s);
987
988    }
989
990    /**
991     * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String, java.net.URLStreamHandler)}.
992     */
993    @TestTargetNew(
994        level = TestLevel.COMPLETE,
995        notes = "From harmony branch",
996        method = "URL",
997        args = {java.net.URL.class, java.lang.String.class, java.net.URLStreamHandler.class}
998    )
999    public void testURLURLStringURLStreamHandler() throws MalformedURLException {
1000        u = new URL("http://www.yahoo.com");
1001        // basic ones
1002        u1 = new URL(u, "file.java", new MyHandler());
1003        assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
1004        assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
1005        assertEquals("1 returns a wrong port", -1, u1.getPort());
1006        assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
1007        assertNull("1 returns a wrong anchor", u1.getRef());
1008
1009        u1 = new URL(u, "systemresource:/+/FILE0/test.java", new MyHandler());
1010        assertEquals("2 returns a wrong protocol", "systemresource", u1
1011                .getProtocol());
1012        assertTrue("2 returns a wrong host", u1.getHost().equals(""));
1013        assertEquals("2 returns a wrong port", -1, u1.getPort());
1014        assertEquals("2 returns a wrong file", "/+/FILE0/test.java", u1
1015                .getFile());
1016        assertNull("2 returns a wrong anchor", u1.getRef());
1017
1018        u1 = new URL(u, "dir1/dir2/../file.java", null);
1019        assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
1020        assertEquals("3 returns a wrong host", "www.yahoo.com", u1.getHost());
1021        assertEquals("3 returns a wrong port", -1, u1.getPort());
1022        assertEquals("3 returns a wrong file", "/dir1/dir2/../file.java", u1
1023                .getFile());
1024        assertNull("3 returns a wrong anchor", u1.getRef());
1025
1026        // test for question mark processing
1027        u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
1028
1029        // test for relative file and out of bound "/../" processing
1030        u1 = new URL(u, "../dir1/dir2/../file.java", new MyHandler());
1031        assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
1032                .equals("/d0/d1/dir1/file.java"));
1033
1034        // test for absolute and relative file processing
1035        u1 = new URL(u, "/../dir1/dir2/../file.java", null);
1036        assertEquals("B) returns a wrong file", "/../dir1/dir2/../file.java",
1037                u1.getFile());
1038
1039        URL one;
1040        try {
1041            one = new URL("http://www.ibm.com");
1042        } catch (MalformedURLException ex) {
1043            // Should not happen.
1044            throw new RuntimeException(ex.getMessage());
1045        }
1046        try {
1047            new URL(one, (String) null, null);
1048            fail("Specifying null spec on URL constructor should throw MalformedURLException");
1049        } catch (MalformedURLException e) {
1050            // expected
1051        }
1052
1053    }
1054
1055    /**
1056     * Test method for {@link java.net.URL#toExternalForm()}.
1057     */
1058    @TestTargetNew(
1059        level = TestLevel.PARTIAL_COMPLETE,
1060        notes = "From harmony branch",
1061        method = "toExternalForm",
1062        args = {}
1063    )
1064    public void test_toExternalForm_Relative() throws MalformedURLException {
1065        String strURL = "http://a/b/c/d;p?q";
1066        String ref = "?y";
1067        URL url = new URL(new URL(strURL), ref);
1068        assertEquals("http://a/b/c/?y", url.toExternalForm());
1069    }
1070
1071    @TestTargetNew(
1072        level = TestLevel.PARTIAL_COMPLETE,
1073        notes = "From harmony branch",
1074        method = "toExternalForm",
1075        args = {}
1076    )
1077    public void test_toExternalForm_Absolute() throws MalformedURLException {
1078        String strURL = "http://localhost?name=value";
1079        URL url = new URL(strURL);
1080        assertEquals(strURL, url.toExternalForm());
1081
1082        strURL = "http://localhost?name=value/age=12";
1083        url = new URL(strURL);
1084        assertEquals(strURL, url.toExternalForm());
1085    }
1086}
1087