OldURLClassLoaderTest.java revision 686dd6f676dc348ac260f54e544cf8d813df64a9
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 dalvik.annotation.SideEffect;
21import java.io.File;
22import java.io.FileOutputStream;
23import java.io.IOException;
24import java.io.InputStream;
25import java.net.MalformedURLException;
26import java.net.URL;
27import java.net.URLClassLoader;
28import java.security.CodeSource;
29import java.security.Permission;
30import java.security.PermissionCollection;
31import java.security.cert.Certificate;
32import java.util.ArrayList;
33import java.util.Enumeration;
34import java.util.List;
35import java.util.jar.Manifest;
36import org.apache.harmony.security.tests.support.TestCertUtils;
37import tests.support.Support_Configuration;
38import tests.support.Support_PortManager;
39import tests.support.Support_TestWebData;
40import tests.support.Support_TestWebServer;
41import tests.support.resource.Support_Resources;
42
43public class OldURLClassLoaderTest extends junit.framework.TestCase {
44
45    URLClassLoader ucl;
46    SecurityManager sm = new SecurityManager() {
47
48        public void checkPermission(Permission perm) {
49        }
50
51        public void checkCreateClassLoader() {
52            throw new SecurityException();
53        }
54    };
55
56    /**
57     * java.net.URLClassLoader#URLClassLoader(java.net.URL[])
58     */
59    public void test_Constructor$Ljava_net_URL() throws MalformedURLException {
60        URL[] u = new URL[0];
61        ucl = new URLClassLoader(u);
62        assertTrue("Failed to set parent", ucl != null
63                && ucl.getParent() == URLClassLoader.getSystemClassLoader());
64
65
66        URL [] urls = {new URL("http://foo.com/foo"),
67                       new URL("jar:file://foo.jar!/foo.c"),
68                       new URL("ftp://foo1/foo2/foo.c")};
69
70        URLClassLoader ucl1 = new URLClassLoader(urls);
71        assertTrue(urls.length == ucl1.getURLs().length);
72
73        try {
74            Class.forName("test", false, ucl);
75            fail("Should throw ClassNotFoundException");
76        } catch (ClassNotFoundException e) {
77            // expected
78        }
79
80        try {
81            new URLClassLoader(new URL[] { null });
82        } catch(Exception e) {
83            fail("Unexpected exception was thrown: " + e.getMessage());
84        }
85    }
86
87    /**
88     * java.net.URLClassLoader#findResources(java.lang.String)
89     */
90    public void test_findResourcesLjava_lang_String() throws Exception {
91        Enumeration<URL> res = null;
92        String[] resValues = { "This is a test resource file.",
93                "This is a resource from a subdir"};
94
95        String tmp = System.getProperty("java.io.tmpdir") + "/";
96
97        File tmpDir = new File(tmp);
98        File test1 = new File(tmp + "test0");
99        test1.deleteOnExit();
100        FileOutputStream out = new FileOutputStream(test1);
101        out.write(resValues[0].getBytes());
102        out.flush();
103        out.close();
104
105        File subDir = new File(tmp + "subdir/");
106        subDir.mkdir();
107        File test2 = new File(tmp + "subdir/test0");
108        test2.deleteOnExit();
109        out = new FileOutputStream(test2);
110        out.write(resValues[1].getBytes());
111        out.flush();
112        out.close();
113
114        URL[] urls = new URL[2];
115        urls[0] = new URL("file://" + tmpDir.getAbsolutePath() + "/");
116        urls[1] = new URL("file://" + subDir.getAbsolutePath() + "/");
117
118        ucl = new URLClassLoader(urls);
119        res = ucl.findResources("test0");
120        assertNotNull("Failed to locate resources", res);
121
122        int i = 0;
123        while (res.hasMoreElements()) {
124            StringBuffer sb = getResContent(res.nextElement());
125            assertEquals("Returned incorrect resource/or in wrong order",
126                    resValues[i++], sb.toString());
127        }
128        assertEquals("Incorrect number of resources returned", 2, i);
129    }
130
131    public void test_addURLLjava_net_URL() throws MalformedURLException {
132        URL[] u = new URL[0];
133
134        URL [] urls = {new URL("http://foo.com/foo"),
135                       new URL("jar:file://foo.jar!/foo.c"),
136                       new URL("ftp://foo1/foo2/foo.c"), null};
137
138        TestURLClassLoader tucl = new TestURLClassLoader(u);
139
140        for(int i = 0; i < urls.length;) {
141            tucl.addURL(urls[i]);
142            i++;
143            URL [] result = tucl.getURLs();
144            assertEquals("Result array length is incorrect: " + i,
145                                                            i, result.length);
146            for(int j = 0; j < result.length; j++) {
147                assertEquals("Result array item is incorrect: " + j,
148                                                            urls[j], result[j]);
149            }
150        }
151    }
152
153    public void test_definePackage() throws MalformedURLException {
154        Manifest manifest = new Manifest();
155        URL[] u = new URL[0];
156        TestURLClassLoader tucl = new TestURLClassLoader(u);
157
158        URL [] urls = {new URL("http://foo.com/foo"),
159                new URL("jar:file://foo.jar!/foo.c"),
160                new URL("ftp://foo1/foo2/foo.c"),
161                new URL("file://new/package/name/"),
162                null};
163
164        String packageName = "new.package.name";
165
166        for(int i = 0; i < urls.length; i++) {
167            Package pack = tucl.definePackage(packageName + i, manifest, urls[i]);
168            assertEquals(packageName + i, pack.getName());
169            assertNull("Implementation Title is not null",
170                    pack.getImplementationTitle());
171            assertNull("Implementation Vendor is not null",
172                    pack.getImplementationVendor());
173            assertNull("Implementation Version is not null.",
174                    pack.getImplementationVersion());
175        }
176
177        try {
178            tucl.definePackage(packageName + "0", manifest, null);
179            fail("IllegalArgumentException was not thrown.");
180        } catch(IllegalArgumentException iae) {
181            //expected
182        }
183    }
184
185    class TestURLClassLoader extends URLClassLoader {
186        public TestURLClassLoader(URL[] urls) {
187            super(urls);
188        }
189
190        public void addURL(URL url) {
191            super.addURL(url);
192        }
193
194        public Package definePackage(String name,
195                                     Manifest man,
196                                     URL url)
197                                     throws IllegalArgumentException {
198            return super.definePackage(name, man, url);
199        }
200
201        public Class<?> findClass(String name)
202                                        throws ClassNotFoundException {
203            return super.findClass(name);
204        }
205
206        protected PermissionCollection getPermissions(CodeSource codesource) {
207            return super.getPermissions(codesource);
208        }
209    }
210
211    @SideEffect("Support_TestWebServer requires isolation.")
212    public void test_findResourceLjava_lang_String() throws Exception {
213        int port = Support_PortManager.getNextPort();
214        File tmp = File.createTempFile("test", ".txt");
215
216        Support_TestWebServer server = new Support_TestWebServer();
217        try {
218
219            server.initServer(port, tmp.getAbsolutePath(), "text/html");
220
221            URL[] urls = { new URL("http://localhost:" + port + "/") };
222            ucl = new URLClassLoader(urls);
223            URL res = ucl.findResource("test1");
224            assertNotNull("Failed to locate resource", res);
225
226            StringBuffer sb = getResContent(res);
227            assertEquals("Returned incorrect resource", new String(Support_TestWebData.test1),
228                    sb.toString());
229        } finally {
230            server.close();
231        }
232    }
233
234    /**
235     * Regression for Harmony-2237
236     */
237    @SideEffect("Support_TestWebServer requires isolation.")
238    public void test_findResource_String() throws Exception {
239        File tempFile1 = File.createTempFile("textFile", ".txt");
240        tempFile1.createNewFile();
241        tempFile1.deleteOnExit();
242        File tempFile2 = File.createTempFile("jarFile", ".jar");
243        tempFile2.delete();
244        tempFile2.deleteOnExit();
245
246        Support_TestWebServer server = new Support_TestWebServer();
247        int port = Support_PortManager.getNextPort();
248        try {
249            server.initServer(port, false);
250
251            String tempPath1 = tempFile1.getParentFile().getAbsolutePath() + "/";
252            InputStream is = getClass().getResourceAsStream(
253                    "/tests/resources/hyts_patch.jar");
254            Support_Resources.copyLocalFileto(tempFile2, is);
255            String tempPath2 = tempFile2.getAbsolutePath();
256            String tempPath3 = "http://localhost:" + port + "/";
257            URLClassLoader urlLoader = getURLClassLoader(tempPath1, tempPath2);
258            assertNull("Found inexistant resource",
259                    urlLoader.findResource("XXX"));
260            assertNotNull("Couldn't find resource from directory",
261                    urlLoader.findResource(tempFile1.getName()));
262            assertNotNull("Couldn't find resource from jar",
263                    urlLoader.findResource("Blah.txt"));
264            urlLoader = getURLClassLoader(tempPath1, tempPath2, tempPath3);
265            assertNotNull("Couldn't find resource from web",
266                    urlLoader.findResource("test1"));
267            assertNull("Found inexistant resource from web",
268                    urlLoader.findResource("test3"));
269        } finally {
270            server.close();
271        }
272    }
273
274    private static URLClassLoader getURLClassLoader(String... classPath)
275            throws MalformedURLException {
276        List<URL> urlList = new ArrayList<URL>();
277        for (String path : classPath) {
278            String url;
279            File f = new File(path);
280            if (f.isDirectory()) {
281                url = "file:" + path;
282            } else if (path.startsWith("http")) {
283                url = path;
284            } else {
285                url = "jar:file:" + path + "!/";
286            }
287            urlList.add(new URL(url));
288        }
289        return new URLClassLoader(urlList.toArray(new URL[urlList.size()]));
290    }
291
292    private StringBuffer getResContent(URL res) throws IOException {
293        StringBuffer sb = new StringBuffer();
294        InputStream is = res.openStream();
295
296        int c;
297        while ((c = is.read()) != -1) {
298            sb.append((char) c);
299        }
300        is.close();
301        return sb;
302    }
303}
304