1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package libcore.java.net;
19
20import java.io.File;
21import java.io.FileOutputStream;
22import java.io.IOException;
23import java.io.InputStream;
24import java.net.MalformedURLException;
25import java.net.URL;
26import java.net.URLClassLoader;
27import java.security.CodeSource;
28import java.security.PermissionCollection;
29import java.util.ArrayList;
30import java.util.Enumeration;
31import java.util.List;
32import java.util.jar.Manifest;
33import tests.support.Support_TestWebData;
34import tests.support.Support_TestWebServer;
35import tests.support.resource.Support_Resources;
36
37public class OldURLClassLoaderTest extends junit.framework.TestCase {
38
39    URLClassLoader ucl;
40
41    /**
42     * java.net.URLClassLoader#URLClassLoader(java.net.URL[])
43     */
44    public void test_Constructor$Ljava_net_URL() throws MalformedURLException {
45        URL[] u = new URL[0];
46        ucl = new URLClassLoader(u);
47        assertTrue("Failed to set parent",
48                ucl.getParent() == URLClassLoader.getSystemClassLoader());
49
50
51        URL [] urls = {new URL("http://foo.com/foo"),
52                       new URL("jar:file://foo.jar!/foo.c"),
53                       new URL("ftp://foo1/foo2/foo.c")};
54
55        URLClassLoader ucl1 = new URLClassLoader(urls);
56        assertTrue(urls.length == ucl1.getURLs().length);
57
58        try {
59            Class.forName("test", false, ucl);
60            fail("Should throw ClassNotFoundException");
61        } catch (ClassNotFoundException e) {
62            // expected
63        }
64
65        try {
66            new URLClassLoader(new URL[] { null });
67        } catch(Exception e) {
68            fail("Unexpected exception was thrown: " + e.getMessage());
69        }
70    }
71
72    /**
73     * java.net.URLClassLoader#findResources(java.lang.String)
74     */
75    public void test_findResourcesLjava_lang_String() throws Exception {
76        String[] resValues = { "This is a test resource file.",
77                "This is a resource from a subdir"};
78
79        String tmp = System.getProperty("java.io.tmpdir") + "/";
80
81        File tmpDir = new File(tmp);
82        File test1 = new File(tmp + "test0");
83        test1.deleteOnExit();
84        FileOutputStream out = new FileOutputStream(test1);
85        out.write(resValues[0].getBytes());
86        out.flush();
87        out.close();
88
89        File subDir = new File(tmp + "subdir/");
90        subDir.mkdir();
91        File test2 = new File(tmp + "subdir/test0");
92        test2.deleteOnExit();
93        out = new FileOutputStream(test2);
94        out.write(resValues[1].getBytes());
95        out.flush();
96        out.close();
97
98        URL[] urls = new URL[2];
99        urls[0] = new URL("file://" + tmpDir.getAbsolutePath() + "/");
100        urls[1] = new URL("file://" + subDir.getAbsolutePath() + "/");
101
102        ucl = new URLClassLoader(urls);
103        Enumeration<URL> res = ucl.findResources("test0");
104        assertNotNull("Failed to locate resources", res);
105
106        int i = 0;
107        while (res.hasMoreElements()) {
108            StringBuffer sb = getResContent(res.nextElement());
109            assertEquals("Returned incorrect resource/or in wrong order",
110                    resValues[i++], sb.toString());
111        }
112        assertEquals("Incorrect number of resources returned", 2, i);
113    }
114
115    public void test_addURLLjava_net_URL() throws MalformedURLException {
116        URL[] u = new URL[0];
117
118        URL [] urls = {new URL("http://foo.com/foo"),
119                       new URL("jar:file://foo.jar!/foo.c"),
120                       new URL("ftp://foo1/foo2/foo.c")};
121
122        TestURLClassLoader tucl = new TestURLClassLoader(u);
123
124        for(int i = 0; i < urls.length;) {
125            tucl.addURL(urls[i]);
126            i++;
127            URL [] result = tucl.getURLs();
128            assertEquals("Result array length is incorrect: " + i,
129                                                            i, result.length);
130            for(int j = 0; j < result.length; j++) {
131                assertEquals("Result array item is incorrect: " + j,
132                                                            urls[j], result[j]);
133            }
134        }
135    }
136
137    public void test_definePackage() throws MalformedURLException {
138        Manifest manifest = new Manifest();
139        URL[] u = new URL[0];
140        TestURLClassLoader tucl = new TestURLClassLoader(u);
141
142        URL [] urls = {new URL("http://foo.com/foo"),
143                new URL("jar:file://foo.jar!/foo.c"),
144                new URL("ftp://foo1/foo2/foo.c"),
145                new URL("file://new/package/name/"),
146                null};
147
148        String packageName = "new.package.name";
149
150        for(int i = 0; i < urls.length; i++) {
151            Package pack = tucl.definePackage(packageName + i, manifest, urls[i]);
152            assertEquals(packageName + i, pack.getName());
153            assertNull("Implementation Title is not null",
154                    pack.getImplementationTitle());
155            assertNull("Implementation Vendor is not null",
156                    pack.getImplementationVendor());
157            assertNull("Implementation Version is not null.",
158                    pack.getImplementationVersion());
159        }
160
161        try {
162            tucl.definePackage(packageName + "0", manifest, null);
163            fail("IllegalArgumentException was not thrown.");
164        } catch(IllegalArgumentException iae) {
165            //expected
166        }
167    }
168
169    class TestURLClassLoader extends URLClassLoader {
170        public TestURLClassLoader(URL[] urls) {
171            super(urls);
172        }
173
174        public void addURL(URL url) {
175            super.addURL(url);
176        }
177
178        public Package definePackage(String name,
179                                     Manifest man,
180                                     URL url)
181                                     throws IllegalArgumentException {
182            return super.definePackage(name, man, url);
183        }
184
185        public Class<?> findClass(String name)
186                                        throws ClassNotFoundException {
187            return super.findClass(name);
188        }
189
190        protected PermissionCollection getPermissions(CodeSource codesource) {
191            return super.getPermissions(codesource);
192        }
193    }
194
195    // SideEffect: Support_TestWebServer requires isolation.
196    public void test_findResourceLjava_lang_String() throws Exception {
197        File tmp = File.createTempFile("test", ".txt");
198
199        Support_TestWebServer server = new Support_TestWebServer();
200        try {
201
202            int port = server.initServer(tmp.getAbsolutePath(), "text/html");
203
204            URL[] urls = { new URL("http://localhost:" + port + "/") };
205            ucl = new URLClassLoader(urls);
206            URL res = ucl.findResource("test1");
207            assertNotNull("Failed to locate resource", res);
208
209            StringBuffer sb = getResContent(res);
210            assertEquals("Returned incorrect resource", new String(Support_TestWebData.test1),
211                    sb.toString());
212        } finally {
213            server.close();
214        }
215    }
216
217    /**
218     * Regression for Harmony-2237
219     */
220    // SideEffect: Support_TestWebServer requires isolation.
221    public void test_findResource_String() throws Exception {
222        File tempFile1 = File.createTempFile("textFile", ".txt");
223        tempFile1.createNewFile();
224        tempFile1.deleteOnExit();
225        File tempFile2 = File.createTempFile("jarFile", ".jar");
226        tempFile2.delete();
227        tempFile2.deleteOnExit();
228
229        Support_TestWebServer server = new Support_TestWebServer();
230        try {
231            int port = server.initServer();
232
233            String tempPath1 = tempFile1.getParentFile().getAbsolutePath() + "/";
234            InputStream is = getClass().getResourceAsStream(
235                    "/tests/resources/hyts_patch.jar");
236            Support_Resources.copyLocalFileto(tempFile2, is);
237            String tempPath2 = tempFile2.getAbsolutePath();
238            URLClassLoader urlLoader = getURLClassLoader(tempPath1, tempPath2);
239            assertNull("Found nonexistent resource", urlLoader.findResource("XXX"));
240            assertNotNull("Couldn't find resource from directory",
241                    urlLoader.findResource(tempFile1.getName()));
242            assertNotNull("Couldn't find resource from jar", urlLoader.findResource("Blah.txt"));
243
244            String tempPath3 = "http://localhost:" + port + "/";
245            urlLoader = getURLClassLoader(tempPath1, tempPath2, tempPath3);
246            assertNotNull("Couldn't find resource from web", urlLoader.findResource("test1"));
247            // Attempt to find a resource using a URL that will produce a 404.
248            assertNull("Found nonexistent resource from web", urlLoader.findResource("test9999"));
249        } finally {
250            server.close();
251        }
252    }
253
254    private static URLClassLoader getURLClassLoader(String... classPath)
255            throws MalformedURLException {
256        List<URL> urlList = new ArrayList<URL>();
257        for (String path : classPath) {
258            String url;
259            File f = new File(path);
260            if (f.isDirectory()) {
261                url = "file:" + path;
262            } else if (path.startsWith("http")) {
263                url = path;
264            } else {
265                url = "jar:file:" + path + "!/";
266            }
267            urlList.add(new URL(url));
268        }
269        return new URLClassLoader(urlList.toArray(new URL[urlList.size()]));
270    }
271
272    private StringBuffer getResContent(URL res) throws IOException {
273        StringBuffer sb = new StringBuffer();
274        InputStream is = res.openStream();
275
276        int c;
277        while ((c = is.read()) != -1) {
278            sb.append((char) c);
279        }
280        is.close();
281        return sb;
282    }
283}
284