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