ClassLoaderTest.java revision 743fc438ecba5ee39e44e4e8b36dfbe9381340bd
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 org.apache.harmony.luni.tests.java.lang;
19
20import dalvik.annotation.AndroidOnly;
21import dalvik.annotation.BrokenTest;
22import dalvik.annotation.KnownFailure;
23import dalvik.annotation.TestTargets;
24import dalvik.annotation.TestLevel;
25import dalvik.annotation.TestTargetNew;
26import dalvik.annotation.TestTargetClass;
27
28import junit.framework.TestCase;
29
30import java.io.File;
31import java.io.FileInputStream;
32import java.io.IOException;
33import java.io.InputStream;
34import java.net.MalformedURLException;
35import java.net.URL;
36import java.nio.ByteBuffer;
37import java.security.CodeSource;
38import java.security.Permission;
39import java.security.PermissionCollection;
40import java.security.Policy;
41import java.security.ProtectionDomain;
42import java.util.Enumeration;
43import java.util.NoSuchElementException;
44
45@TestTargetClass(ClassLoader.class)
46public class ClassLoaderTest extends TestCase {
47
48    public static volatile int flag;
49
50    @TestTargetNew(
51        level = TestLevel.COMPLETE,
52        notes = "",
53        method = "ClassLoader",
54        args = {}
55    )
56    public void test_ClassLoader() {
57        PublicClassLoader pcl = new PublicClassLoader();
58        SecurityManager sm = new SecurityManager() {
59            RuntimePermission rp = new RuntimePermission("getProtectionDomain");
60
61            public void checkCreateClassLoader() {
62                throw new SecurityException();
63            }
64
65            public void checkPermission(Permission perm) {
66                if (perm.equals(rp)) {
67                    throw new SecurityException();
68                }
69            }
70        };
71
72        SecurityManager oldSm = System.getSecurityManager();
73        System.setSecurityManager(sm);
74        try {
75            new PublicClassLoader();
76            fail("SecurityException should be thrown.");
77        } catch (SecurityException e) {
78            // expected
79        } finally {
80            System.setSecurityManager(oldSm);
81        }
82    }
83
84    @TestTargetNew(
85        level = TestLevel.COMPLETE,
86        notes = "",
87        method = "ClassLoader",
88        args = {java.lang.ClassLoader.class}
89    )
90    @BrokenTest("Infinite loop in classloader. Actually a known failure.")
91    public void test_ClassLoaderLClassLoader() {
92      PublicClassLoader pcl = new PublicClassLoader(
93                                            ClassLoader.getSystemClassLoader());
94      assertEquals(ClassLoader.getSystemClassLoader(), pcl.getParent());
95
96      SecurityManager sm = new SecurityManager() {
97          RuntimePermission rp = new RuntimePermission("getProtectionDomain");
98
99          public void checkCreateClassLoader() {
100              throw new SecurityException();
101          }
102
103          public void checkPermission(Permission perm) {
104              if (perm.equals(rp)) {
105                  throw new SecurityException();
106              }
107          }
108      };
109
110      SecurityManager oldSm = System.getSecurityManager();
111      System.setSecurityManager(sm);
112      try {
113          new PublicClassLoader(ClassLoader.getSystemClassLoader());
114          fail("SecurityException should be thrown.");
115      } catch (SecurityException e) {
116          // expected
117      } finally {
118          System.setSecurityManager(oldSm);
119      }
120    }
121
122    @TestTargetNew(
123        level = TestLevel.NOT_NECESSARY,
124        notes = "",
125        method = "clearAssertionStatus",
126        args = {}
127    )
128    @KnownFailure("Android doesn't support assertions to be activated " +
129            "through the api")
130    public void test_clearAssertionStatus() {
131        String className = getClass().getPackage().getName() + ".TestAssertions";
132        String className1 = getClass().getPackage().getName() + ".TestAssertions1";
133        ClassLoader cl = getClass().getClassLoader();
134        cl.setClassAssertionStatus("TestAssertions", true);
135        cl.setDefaultAssertionStatus(true);
136        try {
137
138            Class clazz = cl.loadClass(className);
139
140              TestAssertions ta = (TestAssertions) clazz.newInstance();
141              try {
142                  ta.test();
143                  fail("AssertionError should be thrown.");
144              } catch(AssertionError ae) {
145                  //expected
146              }
147              cl.clearAssertionStatus();
148              clazz = cl.loadClass(className1);
149
150              TestAssertions1 ta1 = (TestAssertions1) clazz.newInstance();
151              try {
152                  ta1.test();
153              } catch(AssertionError ae) {
154                  fail("AssertionError should not be thrown.");
155              }
156
157        } catch(Exception cnfe) {
158            fail("Unexpected exception: " + cnfe.toString());
159        }
160    }
161
162    @TestTargetNew(
163        level = TestLevel.COMPLETE,
164        notes = "This method is not supported. " +
165                "UnsupportedOperationException should be thrown.",
166        method = "defineClass",
167        args = {byte[].class, int.class, int.class}
168    )
169    @AndroidOnly("define methods re not supported on Android. " +
170            "UnsupportedOperationException should be thrown.")
171    public void test_defineClassLbyteArrayLintLint() throws Exception {
172
173        try {
174            Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_1);
175            //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
176            fail("UnsupportedOperationException was not thrown.");
177        } catch(UnsupportedOperationException uoe) {
178            //expected
179        }
180
181        try {
182            new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_1);
183            fail("IndexOutOfBoundsException is not thrown.");
184        } catch(IndexOutOfBoundsException  ioobe) {
185            fail("UnsupportedOperationException should be thrown.");
186        } catch(UnsupportedOperationException uoe) {
187            //expected
188        }
189    }
190
191    @TestTargetNew(
192        level = TestLevel.COMPLETE,
193        notes = "This method is not supported. UnsupportedOperationException should be thrown.",
194        method = "defineClass",
195        args = {java.lang.String.class, byte[].class, int.class, int.class, java.security.ProtectionDomain.class}
196    )
197    @AndroidOnly("define methods re not supported on Android. " +
198            "UnsupportedOperationException should be thrown.")
199    public void test_defineClassLjava_lang_StringLbyteArrayLintLintLProtectionDomain()
200                    throws Exception {
201
202        try {
203            Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_2);
204            //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
205            //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
206            fail("UnsupportedOperationException was not thrown.");
207        } catch(UnsupportedOperationException uoe) {
208            //expected
209        }
210
211        try {
212            new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_2);
213            fail("IndexOutOfBoundsException is not thrown.");
214        } catch(IndexOutOfBoundsException  ioobe) {
215            fail("UnsupportedOperationException should be thrown.");
216        } catch(UnsupportedOperationException uoe) {
217            //expected
218        }
219
220      /*try {
221            ErrorLdr loader = new ErrorLdr();
222
223            try {
224                loader.define("WrongFormatClass", Ldr.TEST_CASE_DEFINE_2);
225                fail("ClassFormatError should be thrown.");
226            } catch (ClassFormatError le) {
227                //expected
228            } catch(UnsupportedOperationException uoe) {
229                //expected
230            }
231
232            try {
233                loader.defineWrongName("TestClass", 0);
234                fail("NoClassDefFoundError should be thrown.");
235            } catch (NoClassDefFoundError ncdfe) {
236                //expected
237            } catch(UnsupportedOperationException uoe) {
238                //expected
239            }
240
241            try {
242                Class<?> clazz = loader.defineNullDomain("TestClass", 0);
243                assertEquals(getClass().getProtectionDomain(),
244                        clazz.getProtectionDomain());
245            } catch(UnsupportedOperationException uoe) {
246                //expected
247            }
248
249        } catch(Exception e) {
250            fail("Unexpected exception was thrown: " + e.toString());
251        }
252        */
253    }
254
255    @TestTargetNew(
256        level = TestLevel.COMPLETE,
257        notes = "This method is not supported. UnsupportedOperationException should be thrown.",
258        method = "defineClass",
259        args = {java.lang.String.class, java.nio.ByteBuffer.class, java.security.ProtectionDomain.class}
260    )
261    @AndroidOnly("define methods re not supported on Android. " +
262            "UnsupportedOperationException should be thrown.")
263    public void test_defineClassLjava_lang_StringLByteBufferLProtectionDomain() {
264
265        try {
266            try {
267                Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_3);
268                //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
269                //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
270                fail("UnsupportedOperationException was not thrown.");
271            } catch(UnsupportedOperationException uoe) {
272                //expected
273            }
274
275            try {
276                new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_3);
277                fail("IndexOutOfBoundsException is not thrown.");
278            } catch(IndexOutOfBoundsException  ioobe) {
279                fail("UnsupportedOperationException should be thrown.");
280            } catch(UnsupportedOperationException uoe) {
281                //expected
282            }
283
284        } catch(Exception e) {
285            fail("Unexpected exception was thrown: " + e.toString());
286        }
287    }
288
289    /**
290     * Tests that Classloader.defineClass() assigns appropriate
291     * default domains to the defined classes.
292     */
293    @TestTargetNew(
294        level = TestLevel.COMPLETE,
295        notes = "This method is not supported. " +
296                "UnsupportedOperationException should be thrown.",
297        method = "defineClass",
298        args = {java.lang.String.class, byte[].class, int.class, int.class}
299    )
300    @AndroidOnly("define methods re not supported on Android. " +
301            "UnsupportedOperationException should be thrown.")
302    public void test_defineClass_defaultDomain() throws Exception {
303        try {
304            Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_0);
305            fail("UnsupportedOperationException was not thrown.");
306        } catch(UnsupportedOperationException uoe) {
307            //expected
308        }
309
310        try {
311            new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_0);
312            fail("IndexOutOfBoundsException is not thrown.");
313        } catch(IndexOutOfBoundsException  ioobe) {
314            fail("UnsupportedOperationException should be thrown.");
315        } catch(UnsupportedOperationException uoe) {
316            //expected
317        }
318    }
319
320    static class SyncTestClassLoader extends ClassLoader {
321        Object lock;
322        volatile int numFindClassCalled;
323
324        SyncTestClassLoader(Object o) {
325            this.lock = o;
326            numFindClassCalled = 0;
327        }
328
329        /*
330         * Byte array of bytecode equivalent to the following source code:
331         * public class TestClass {
332         * }
333         */
334        private byte[] classData = new byte[] {
335            -54, -2, -70, -66, 0, 0, 0, 49, 0, 13,
336            10, 0, 3, 0, 10, 7, 0, 11, 7, 0,
337            12, 1, 0, 6, 60, 105, 110, 105, 116, 62,
338            1, 0, 3, 40, 41, 86, 1, 0, 4, 67,
339            111, 100, 101, 1, 0, 15, 76, 105, 110, 101,
340            78, 117, 109, 98, 101, 114, 84, 97, 98, 108,
341            101, 1, 0, 10, 83, 111, 117, 114, 99, 101,
342            70, 105, 108, 101, 1, 0, 14, 84, 101, 115,
343            116, 67, 108, 97, 115, 115, 46, 106, 97, 118,
344            97, 12, 0, 4, 0, 5, 1, 0, 9, 84,
345            101, 115, 116, 67, 108, 97, 115, 115, 1, 0,
346            16, 106, 97, 118, 97, 47, 108, 97, 110, 103,
347            47, 79, 98, 106, 101, 99, 116, 0, 33, 0,
348            2, 0, 3, 0, 0, 0, 0, 0, 1, 0,
349            1, 0, 4, 0, 5, 0, 1, 0, 6, 0,
350            0, 0, 29, 0, 1, 0, 1, 0, 0, 0,
351            5, 42, -73, 0, 1, -79, 0, 0, 0, 1,
352            0, 7, 0, 0, 0, 6, 0, 1, 0, 0,
353            0, 1, 0, 1, 0, 8, 0, 0, 0, 2,
354            0, 9 };
355
356        protected Class findClass(String name) throws ClassNotFoundException {
357            try {
358                while (flag != 2) {
359                    synchronized (lock) {
360                        lock.wait();
361                    }
362                }
363            } catch (InterruptedException ie) {}
364
365            if (name.equals("TestClass")) {
366                numFindClassCalled++;
367                return defineClass(null, classData, 0, classData.length);
368            } else {
369                throw new ClassNotFoundException("Class " + name + " not found.");
370            }
371        }
372    }
373
374    static class SyncLoadTestThread extends Thread {
375        volatile boolean started;
376        ClassLoader cl;
377        Class cls;
378
379        SyncLoadTestThread(ClassLoader cl) {
380            this.cl = cl;
381        }
382
383        public void run() {
384            try {
385                started = true;
386                cls = Class.forName("TestClass", false, cl);
387            } catch (Exception ex) {
388                ex.printStackTrace();
389            }
390        }
391    }
392
393    /**
394     * Regression test for HARMONY-1939:
395     * 2 threads simultaneously run Class.forName() method for the same classname
396     * and the same classloader. It is expected that both threads succeed but
397     * class must be defined just once.
398     */
399    @TestTargetNew(
400        level = TestLevel.PARTIAL,
401        notes = "Regression test.",
402        method = "loadClass",
403        args = {java.lang.String.class}
404    )
405    @BrokenTest("Defining classes not supported, unfortunately the test appears"
406            + " to succeed, which is not true, so marking it broken.")
407    public void test_loadClass_concurrentLoad() throws Exception
408    {
409        Object lock = new Object();
410        SyncTestClassLoader cl = new SyncTestClassLoader(lock);
411        SyncLoadTestThread tt1 = new SyncLoadTestThread(cl);
412        SyncLoadTestThread tt2 = new SyncLoadTestThread(cl);
413        flag = 1;
414        tt1.start();
415        tt2.start();
416
417        while (!tt1.started && !tt2.started) {
418            Thread.sleep(100);
419        }
420
421        flag = 2;
422        synchronized (lock) {
423            lock.notifyAll();
424        }
425        tt1.join();
426        tt2.join();
427
428        assertSame("Bad or redefined class", tt1.cls, tt2.cls);
429        assertEquals("Both threads tried to define class", 1, cl.numFindClassCalled);
430    }
431
432    @TestTargetNew(
433        level = TestLevel.COMPLETE,
434        notes = "",
435        method = "loadClass",
436        args = {java.lang.String.class}
437    )
438    public void test_loadClassLjava_lang_String() {
439
440        String [] classNames = {"org.apache.harmony.luni.tests.java.lang.TestClass1",
441                "org.apache.harmony.luni.tests.java.lang.TestClass3",
442                "org.apache.harmony.luni.tests.java.lang.A"};
443
444        ClassLoader cl = getClass().getClassLoader();
445        for(String str:classNames) {
446            try {
447                Class<?> clazz = cl.loadClass(str);
448                assertNotNull(clazz);
449                assertEquals(str, clazz.getName());
450                if(str.endsWith("A"))
451                    clazz.newInstance();
452                if(str.endsWith("TestClass1")) {
453                    try {
454                        clazz.newInstance();
455                        fail("ExceptionInInitializerError was not thrown.");
456                    } catch(ExceptionInInitializerError eiine) {
457                        //expected
458                    }
459                }
460                if(str.endsWith("TestClass3")) {
461                    try {
462                        clazz.newInstance();
463                        fail("IllegalAccessException was not thrown.");
464                    } catch(IllegalAccessException ie) {
465                        //expected
466                    }
467                }
468            } catch (ClassNotFoundException e) {
469                fail("ClassNotFoundException was thrown." + e.getMessage());
470            } catch (InstantiationException e) {
471                fail("InstantiationException was thrown.");
472            } catch (IllegalAccessException e) {
473                fail("IllegalAccessException was thrown.");
474            }
475        }
476
477        try {
478            Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass4");
479            fail("ClassNotFoundException was not thrown.");
480        } catch (ClassNotFoundException e) {
481            //expected
482        }
483
484        try {
485            Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass5");
486            fail("ClassNotFoundException was not thrown.");
487        } catch (ClassNotFoundException e) {
488            //expected
489        }
490    }
491
492    @TestTargetNew(
493        level = TestLevel.COMPLETE,
494        notes = "",
495        method = "loadClass",
496        args = {java.lang.String.class, boolean.class}
497    )
498    public void test_loadClassLjava_lang_StringLZ() throws
499            IllegalAccessException, InstantiationException,
500            ClassNotFoundException {
501        PackageClassLoader pcl = new PackageClassLoader(
502                getClass().getClassLoader());
503        String className = getClass().getPackage().getName() + ".A";
504
505        Class<?> clazz = pcl.loadClass(className, false);
506        assertEquals(className, clazz.getName());
507        assertNotNull(clazz.newInstance());
508
509        clazz = pcl.loadClass(className, true);
510        assertEquals(className, clazz.getName());
511        assertNotNull(clazz.newInstance());
512
513        try {
514            clazz = pcl.loadClass("UnknownClass", false);
515            assertEquals("TestClass", clazz.getName());
516            fail("ClassNotFoundException was not thrown.");
517        } catch (ClassNotFoundException e) {
518            //expected
519        }
520    }
521
522    /**
523     * @tests java.lang.ClassLoader#getResource(java.lang.String)
524     */
525    @TestTargetNew(
526        level = TestLevel.COMPLETE,
527        notes = "",
528        method = "getResource",
529        args = {java.lang.String.class}
530    )
531    public void test_getResourceLjava_lang_String() {
532        // Test for method java.net.URL
533        // java.lang.ClassLoader.getResource(java.lang.String)
534        java.net.URL u = getClass().getClassLoader().getResource("hyts_Foo.c");
535        assertNotNull("Unable to find resource", u);
536        java.io.InputStream is = null;
537        try {
538            is = u.openStream();
539            assertNotNull("Resource returned is invalid", is);
540            is.close();
541        } catch (java.io.IOException e) {
542            fail("IOException getting stream for resource : " + e.getMessage());
543        }
544
545
546
547        assertNull(getClass().getClassLoader()
548                .getResource("not.found.resource"));
549    }
550
551    /**
552     * @tests java.lang.ClassLoader#getResourceAsStream(java.lang.String)
553     */
554    @TestTargetNew(
555        level = TestLevel.COMPLETE,
556        notes = "",
557        method = "getResourceAsStream",
558        args = {java.lang.String.class}
559    )
560    public void test_getResourceAsStreamLjava_lang_String() {
561        // Test for method java.io.InputStream
562        // java.lang.ClassLoader.getResourceAsStream(java.lang.String)
563        // Need better test...
564
565        java.io.InputStream is = null;
566        assertNotNull("Failed to find resource: HelloWorld.txt",
567                (is = getClass().getClassLoader()
568                        .getResourceAsStream("HelloWorld.txt")));
569
570        byte [] array = new byte[13];
571        try {
572            is.read(array);
573        } catch(IOException ioe) {
574            fail("IOException was not thrown.");
575        } finally {
576            try {
577                is.close();
578            } catch(IOException ioe) {}
579        }
580
581        assertEquals("Hello, World.", new String(array));
582
583
584        try {
585            is.close();
586        } catch (java.io.IOException e) {
587            fail("Exception during getResourceAsStream: " + e.toString());
588        }
589
590        assertNull(getClass().getClassLoader().
591                getResourceAsStream("unknownResource.txt"));
592    }
593
594    /**
595     * @tests java.lang.ClassLoader#getSystemClassLoader()
596     */
597    @TestTargetNew(
598        level = TestLevel.SUFFICIENT,
599        notes = "",
600        method = "getSystemClassLoader",
601        args = {}
602    )
603    @BrokenTest("Infinite loop in classloader. Actually a known failure.")
604    public void test_getSystemClassLoader() {
605        // Test for method java.lang.ClassLoader
606        // java.lang.ClassLoader.getSystemClassLoader()
607        ClassLoader cl = ClassLoader.getSystemClassLoader();
608
609        java.io.InputStream is = cl.getResourceAsStream("classes.dex");
610        assertNotNull("Failed to find resource from system classpath", is);
611        try {
612            is.close();
613        } catch (java.io.IOException e) {
614        }
615
616        SecurityManager sm = new SecurityManager() {
617            public void checkPermission(Permission perm) {
618                if(perm.getName().equals("getClassLoader")) {
619                   throw new SecurityException();
620                }
621            }
622        };
623
624        SecurityManager oldManager = System.getSecurityManager();
625        System.setSecurityManager(sm);
626        try {
627            ClassLoader.getSystemClassLoader();
628        } catch(SecurityException se) {
629            //expected
630        } finally {
631            System.setSecurityManager(oldManager);
632        }
633/*
634 *       // java.lang.Error is not thrown on RI, but it's specified.
635 *
636 *       String keyProp = "java.system.class.loader";
637 *       String oldProp = System.getProperty(keyProp);
638 *       System.setProperty(keyProp, "java.test.UnknownClassLoader");
639 *       boolean isFailed = false;
640 *       try {
641 *           ClassLoader.getSystemClassLoader();
642 *           isFailed = true;
643 *       } catch(java.lang.Error e) {
644 *           //expected
645 *       } finally {
646 *           if(oldProp == null) {
647 *               System.clearProperty(keyProp);
648 *           }  else {
649 *               System.setProperty(keyProp, oldProp);
650 *           }
651 *       }
652 *       assertFalse("java.lang.Error was not thrown.", isFailed);
653 */
654    }
655
656    /**
657     * @tests java.lang.ClassLoader#getSystemResource(java.lang.String)
658     */
659    @TestTargetNew(
660        level = TestLevel.COMPLETE,
661        notes = "",
662        method = "getSystemResource",
663        args = {java.lang.String.class}
664    )
665    @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
666            + "core-tests.jar. Also on Android this file is the only one "
667            + "that is sure to exist.")
668    public void test_getSystemResourceLjava_lang_String() throws IOException {
669        // java.lang.ClassLoader.getSystemResource(java.lang.String)
670        // Need better test...
671
672
673        //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
674        //                        getClass().getSimpleName()  + ".class";
675        //assertNotNull("Failed to find resource: " + classResource,
676        //        ClassLoader.getSystemResource(classResource));
677
678        URL url = getClass().getClassLoader().getSystemResource("classes.dex");
679        assertNotNull("Failed to find resource: classes.dex", url);
680        java.io.InputStream is = url.openStream();
681
682        assertTrue("System resource not found", is.available() > 0);
683        assertNull("Doesn't return null for unknown resource.",
684                getClass().getClassLoader().getSystemResource("NotFound"));
685    }
686
687    @TestTargetNew(
688        level = TestLevel.COMPLETE,
689        notes = "",
690        method = "getSystemResourceAsStream",
691        args = {java.lang.String.class}
692    )
693    @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
694            + "core-tests.jar. Also on Android this file is the only one "
695            + "that is sure to exist.")
696    public void test_getSystemResourceAsStreamLjava_lang_String()
697            throws IOException {
698
699        //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
700        //                    getClass().getSimpleName()  + ".class";
701        //assertNotNull("Failed to find resource: " + classResource,
702        //            ClassLoader.getSystemResourceAsStream(classResource));
703
704        java.io.InputStream is = getClass().getClassLoader()
705                .getSystemResourceAsStream("classes.dex");
706        assertNotNull("Failed to find resource: classes.dex", is);
707
708        assertTrue("System resource not found", is.available() > 0);
709
710        assertNull(ClassLoader.getSystemResourceAsStream("NotFoundResource"));
711    }
712
713    @TestTargetNew(
714        level = TestLevel.COMPLETE,
715        notes = "",
716        method = "getSystemResources",
717        args = {java.lang.String.class}
718    )
719    @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
720            + "core-tests.jar. Also on Android this file is the only one "
721            + "that is sure to exist.")
722    public void test_getSystemResources() {
723
724        String textResource = "classes.dex";
725
726        try {
727            Enumeration<URL> urls = ClassLoader.getSystemResources(textResource);
728            assertNotNull(urls);
729            assertTrue(urls.nextElement().getPath().endsWith(textResource));
730            while (urls.hasMoreElements()) {
731                assertNotNull(urls.nextElement());
732            }
733            try {
734                urls.nextElement();
735                fail("NoSuchElementException was not thrown.");
736            } catch(NoSuchElementException nse) {
737                //expected
738            }
739        } catch(IOException ioe) {
740            fail("IOException was thrown.");
741        }
742    }
743
744    @TestTargetNew(
745        level = TestLevel.COMPLETE,
746        notes = "",
747        method = "getPackage",
748        args = {java.lang.String.class}
749    )
750    @KnownFailure("PackageClassLoader.getPackage returns null.")
751    public void test_getPackageLjava_lang_String() {
752        PackageClassLoader pcl = new PackageClassLoader(
753                getClass().getClassLoader());
754
755        String [] packageProperties = { "test.package", "title", "1.0",
756                "Vendor", "Title", "1.1", "implementation vendor"};
757
758        URL url = null;
759        try {
760            url = new URL("file:");
761        } catch (MalformedURLException e) {
762            fail("MalformedURLException was thrown.");
763        }
764        pcl.definePackage(packageProperties[0],
765                          packageProperties[1],
766                          packageProperties[2],
767                          packageProperties[3],
768                          packageProperties[4],
769                          packageProperties[5],
770                          packageProperties[6],
771                          url);
772
773       assertNotNull(pcl.getPackage(packageProperties[0]));
774
775       assertEquals("should define current package", getClass().getPackage(),
776               pcl.getPackage(getClass().getPackage().getName()));
777
778       assertNull(pcl.getPackage("not.found.package"));
779    }
780
781    @TestTargetNew(
782        level = TestLevel.COMPLETE,
783        notes = "",
784        method = "getPackages",
785        args = {}
786    )
787    @KnownFailure("The package canot be found. Seems like the cache is not " +
788            "shared between the class loaders. But this test seems to " +
789            "expect exactly that. this tests works on the RI.")
790    public void test_getPackages() {
791
792        PackageClassLoader pcl = new PackageClassLoader(
793                getClass().getClassLoader());
794
795        String [] packageProperties = { "test.package", "title", "1.0",
796                "Vendor", "Title", "1.1", "implementation vendor"};
797
798        URL url = null;
799        try {
800            url = new URL("file:");
801        } catch (MalformedURLException e) {
802            fail("MalformedURLException was thrown.");
803        }
804        pcl.definePackage(packageProperties[0],
805                          packageProperties[1],
806                          packageProperties[2],
807                          packageProperties[3],
808                          packageProperties[4],
809                          packageProperties[5],
810                          packageProperties[6],
811                          url);
812
813        Package [] packages = pcl.getPackages();
814        assertTrue(packages.length != 0);
815
816        pcl = new PackageClassLoader(getClass().getClassLoader());
817        packages = pcl.getPackages();
818        assertNotNull(packages);
819
820        boolean isThisFound = false;
821        for(Package p:packages) {
822            if(p.equals(getClass().getPackage())) {
823                isThisFound = true;
824            }
825        }
826        assertTrue(isThisFound);
827    }
828
829    @TestTargetNew(
830        level = TestLevel.COMPLETE,
831        notes = "",
832        method = "getParent",
833        args = {}
834    )
835    public void test_getParent() {
836        PublicClassLoader pcl = new PublicClassLoader();
837        assertNotNull(pcl.getParent());
838        ClassLoader cl = getClass().getClassLoader().getParent();
839        assertNotNull(cl);
840
841        SecurityManager sm = new SecurityManager() {
842
843            final String perName = "getClassLoader";
844
845            public void checkPermission(Permission perm) {
846                if (perm.getName().equals(perName)) {
847                    throw new SecurityException();
848                }
849            }
850        };
851
852        SecurityManager oldSm = System.getSecurityManager();
853        System.setSecurityManager(sm);
854        try {
855            getClass().getClassLoader().getParent();
856            fail("Should throw SecurityException");
857        } catch (SecurityException e) {
858            // expected
859        } finally {
860            System.setSecurityManager(oldSm);
861        }
862    }
863
864    @TestTargetNew(
865        level = TestLevel.COMPLETE,
866        notes = "",
867        method = "getResources",
868        args = {java.lang.String.class}
869    )
870    public void test_getResourcesLjava_lang_String() {
871        Enumeration<java.net.URL> urls = null;
872        FileInputStream fis = null;
873        try {
874            urls = getClass().getClassLoader().getResources("HelloWorld.txt");
875            URL url = urls.nextElement();
876            fis = new FileInputStream(url.getFile());
877            byte [] array = new byte[13];
878            fis.read(array);
879            assertEquals("Hello, World.", new String(array));
880        } catch (IOException e) {
881
882        } finally {
883            try {
884                fis.close();
885            } catch(Exception e) {}
886        }
887
888        assertNull(getClass().getClassLoader()
889                .getResource("not.found.resource"));
890
891    }
892
893    @TestTargetNew(
894        level = TestLevel.COMPLETE,
895        notes = "",
896        method = "definePackage",
897        args = {java.lang.String.class, java.lang.String.class,
898                java.lang.String.class, java.lang.String.class,
899                java.lang.String.class, java.lang.String.class,
900                java.lang.String.class, java.net.URL.class }
901    )
902    public void test_definePackage() {
903
904        PackageClassLoader pcl = new PackageClassLoader(
905                getClass().getClassLoader());
906
907        String [] packageProperties = { "test.package", "title", "1.0",
908                "Vendor", "Title", "1.1", "implementation vendor"};
909
910        URL url = null;
911        try {
912            url = new URL("file:");
913        } catch (MalformedURLException e) {
914            fail("MalformedURLException was thrown.");
915        }
916        pcl.definePackage(packageProperties[0],
917                          packageProperties[1],
918                          packageProperties[2],
919                          packageProperties[3],
920                          packageProperties[4],
921                          packageProperties[5],
922                          packageProperties[6],
923                          url);
924
925       Package pack = pcl.getPackage(packageProperties[0]);
926       assertEquals(packageProperties[1], pack.getSpecificationTitle());
927       assertEquals(packageProperties[2], pack.getSpecificationVersion());
928       assertEquals(packageProperties[3], pack.getSpecificationVendor());
929       assertEquals(packageProperties[4], pack.getImplementationTitle());
930       assertEquals(packageProperties[5], pack.getImplementationVersion());
931       assertEquals(packageProperties[6], pack.getImplementationVendor());
932       assertTrue(pack.isSealed(url));
933       assertTrue(pack.isSealed());
934
935       try {
936           pcl.definePackage(packageProperties[0],
937                   packageProperties[1],
938                   packageProperties[2],
939                   packageProperties[3],
940                   packageProperties[4],
941                   packageProperties[5],
942                   packageProperties[6],
943                   null);
944           fail("IllegalArgumentException was not thrown.");
945       } catch(IllegalArgumentException  iae) {
946           //expected
947       }
948
949       pcl.definePackage("test.package.test", null, null, null, null,
950               null, null, null);
951       pack = pcl.getPackage("test.package.test");
952       assertNull(pack.getSpecificationTitle());
953       assertNull(pack.getSpecificationVersion());
954       assertNull(pack.getSpecificationVendor());
955       assertNull(pack.getImplementationTitle());
956       assertNull(pack.getImplementationVersion());
957       assertNull(pack.getImplementationVendor());
958       assertFalse(pack.isSealed());
959    }
960
961    @TestTargetNew(
962        level = TestLevel.COMPLETE,
963        notes = "",
964        method = "findClass",
965        args = {java.lang.String.class}
966    )
967    @AndroidOnly("findClass method throws ClassNotFoundException exception.")
968    public void test_findClass(){
969
970        try {
971            PackageClassLoader pcl = new PackageClassLoader(
972                    getClass().getClassLoader());
973            pcl.findClass(getClass().getPackage().getName() + ".A");
974            fail("ClassNotFoundException was not thrown.");
975        } catch(ClassNotFoundException cnfe) {
976            //expected
977        }
978
979       try {
980           PackageClassLoader pcl = new PackageClassLoader(
981                   getClass().getClassLoader());
982           pcl.findClass("TestClass");
983           fail("ClassNotFoundException was not thrown.");
984       } catch(ClassNotFoundException cnfe) {
985           //expected
986       }
987    }
988
989    @TestTargetNew(
990        level = TestLevel.COMPLETE,
991        notes = "",
992        method = "findLibrary",
993        args = {java.lang.String.class}
994    )
995    @AndroidOnly("findLibrary method is not supported, it returns null.")
996    public void test_findLibrary() {
997        PackageClassLoader pcl = new PackageClassLoader(
998                getClass().getClassLoader());
999        assertNull(pcl.findLibrary("libjvm.so"));
1000    }
1001
1002    @TestTargetNew(
1003        level = TestLevel.COMPLETE,
1004        notes = "",
1005        method = "findResource",
1006        args = {java.lang.String.class}
1007    )
1008    @AndroidOnly("findResource method is not supported, it returns null.")
1009    public void test_findResourceLjava_lang_String() {
1010        assertNull(new PackageClassLoader(
1011                getClass().getClassLoader()).findResource("hyts_Foo.c"));
1012    }
1013
1014    @TestTargetNew(
1015        level = TestLevel.COMPLETE,
1016        notes = "",
1017        method = "findResources",
1018        args = {java.lang.String.class}
1019    )
1020    @AndroidOnly("findResources method is not supported, it returns " +
1021            "empty Enumeration.")
1022    public void test_findResourcesLjava_lang_String() throws IOException {
1023        assertFalse(new PackageClassLoader(
1024                getClass().getClassLoader()).findResources("hyts_Foo.c").
1025                hasMoreElements());
1026    }
1027
1028    @TestTargetNew(
1029        level = TestLevel.COMPLETE,
1030        notes = "",
1031        method = "findSystemClass",
1032        args = {java.lang.String.class}
1033    )
1034    public void test_findSystemClass() {
1035        PackageClassLoader pcl = new PackageClassLoader(
1036                getClass().getClassLoader());
1037
1038        Class [] classes = { String.class, Integer.class, Object.class,
1039                Object[].class };
1040
1041        for(Class clazz:classes) {
1042            try {
1043                String className = clazz.getName();
1044                assertEquals(clazz, pcl.findSystemClazz(className));
1045            } catch(ClassNotFoundException cnfe) {
1046                fail("ClassNotFoundException was thrown: " + cnfe.getMessage());
1047            }
1048        }
1049        try {
1050            pcl.findSystemClazz("unknownClass");
1051            fail("ClassNotFoundException was not thrown.");
1052        } catch(ClassNotFoundException cnfe) {
1053            //expected
1054        }
1055    }
1056
1057   @TestTargetNew(
1058       level = TestLevel.COMPLETE,
1059       notes = "",
1060       method = "findLoadedClass",
1061       args = {java.lang.String.class }
1062    )
1063    public void test_findLoadedClass() {
1064       PackageClassLoader pcl = new PackageClassLoader(
1065               getClass().getClassLoader());
1066
1067       Class [] classes = { A.class, PublicTestClass.class,
1068               TestAnnotation.class, TestClass1.class };
1069
1070       for(Class clazz:classes) {
1071           String className = clazz.getName();
1072           assertNull(pcl.findLoadedClazz(className));
1073       }
1074
1075       assertNull(pcl.findLoadedClazz("unknownClass"));
1076    }
1077
1078    @TestTargets({
1079        @TestTargetNew(
1080            level = TestLevel.NOT_NECESSARY,
1081            notes = "setClassAssertionStatus is not supported.",
1082            method = "setClassAssertionStatus",
1083            args = {java.lang.String.class, boolean.class}
1084        ),
1085        @TestTargetNew(
1086            level = TestLevel.NOT_NECESSARY,
1087            notes = "setDefaultAssertionStatus is not supported.",
1088            method = "setDefaultAssertionStatus",
1089            args = {boolean.class}
1090        ),
1091        @TestTargetNew(
1092            level = TestLevel.NOT_NECESSARY,
1093            notes = "setPackageAssertionStatus is not supported.",
1094            method = "setPackageAssertionStatus",
1095            args = {java.lang.String.class, boolean.class}
1096        ),
1097        @TestTargetNew(
1098            level = TestLevel.NOT_NECESSARY,
1099            notes = "resolveClass is not supported.",
1100            method = "resolveClass",
1101            args = {java.lang.Class.class}
1102        ),
1103        @TestTargetNew(
1104            level = TestLevel.NOT_NECESSARY,
1105            notes = "setSigners is not supported.",
1106            method = "setSigners",
1107            args = {java.lang.Class.class, java.lang.Object[].class}
1108        )
1109    })
1110    public void test_notSupported() {
1111        getClass().getClassLoader().setClassAssertionStatus(getName(), true);
1112        getClass().getClassLoader().setDefaultAssertionStatus(true);
1113        getClass().getClassLoader().setPackageAssertionStatus(
1114                getClass().getPackage().getName(), true);
1115    }
1116}
1117
1118class DynamicPolicy extends Policy {
1119
1120    public PermissionCollection pc;
1121
1122    @Override
1123    public PermissionCollection getPermissions(ProtectionDomain pd) {
1124        return pc;
1125    }
1126
1127    @Override
1128    public PermissionCollection getPermissions(CodeSource codesource) {
1129        return pc;
1130    }
1131
1132    @Override
1133    public void refresh() {
1134    }
1135}
1136
1137class A {
1138}
1139
1140class Ldr extends ClassLoader {
1141
1142    /*
1143     * These bytes are the content of the file
1144     * /org/apache/harmony/luni/tests/java/lang/A.class
1145     */
1146    byte[] classBytes = new byte[] { -54, -2, -70, -66, 0, 0, 0, 49, 0, 16, 7,
1147            0, 2, 1, 0, 41, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
1148            104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
1149            101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
1150            65, 7, 0, 4, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
1151            79, 98, 106, 101, 99, 116, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1,
1152            0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 10, 0, 3, 0, 9, 12, 0,
1153            5, 0, 6, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114,
1154            84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114,
1155            105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105,
1156            115, 1, 0, 43, 76, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
1157            104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
1158            101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
1159            65, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1,
1160            0, 20, 67, 108, 97, 115, 115, 76, 111, 97, 100, 101, 114, 84, 101,
1161            115, 116, 46, 106, 97, 118, 97, 0, 32, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1,
1162            0, 0, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 47, 0, 1, 0, 1, 0, 0, 0, 5,
1163            42, -73, 0, 8, -79, 0, 0, 0, 2, 0, 10, 0, 0, 0, 6, 0, 1, 0, 0, 4,
1164            -128, 0, 11, 0, 0, 0, 12, 0, 1, 0, 0, 0, 5, 0, 12, 0, 13, 0, 0, 0,
1165            1, 0, 14, 0, 0, 0, 2, 0, 15 };
1166
1167    public static final int TEST_CASE_DEFINE_0 = 0;
1168    public static final int TEST_CASE_DEFINE_1 = 1;
1169    public static final int TEST_CASE_DEFINE_2 = 2;
1170    public static final int TEST_CASE_DEFINE_3 = 3;
1171
1172    @SuppressWarnings("deprecation")
1173    public Class<?> define(int len, int testCase) throws Exception {
1174
1175        if(len < 0) len = classBytes.length;
1176        Class<?> clazz = null;
1177        String className = "org.apache.harmony.luni.tests.java.lang.A";
1178        switch(testCase) {
1179            case TEST_CASE_DEFINE_0:
1180                clazz = defineClass(className, classBytes, 0, len);
1181                break;
1182            case TEST_CASE_DEFINE_1:
1183                clazz = defineClass(classBytes, 0, len);
1184                break;
1185            case TEST_CASE_DEFINE_2:
1186                clazz = defineClass(className, classBytes, 0, len,
1187                        getClass().getProtectionDomain());
1188                break;
1189            case TEST_CASE_DEFINE_3:
1190                ByteBuffer bb = ByteBuffer.wrap(classBytes);
1191                clazz = defineClass(className,
1192                        bb, getClass().getProtectionDomain());
1193                break;
1194        }
1195        return clazz;
1196    }
1197
1198    public Class<?> define(int testCase) throws Exception {
1199        return  define(-1, testCase);
1200    }
1201
1202}
1203
1204class PackageClassLoader extends ClassLoader {
1205    public PackageClassLoader() {
1206        super();
1207    }
1208
1209    public PackageClassLoader(ClassLoader parent) {
1210        super(parent);
1211    }
1212
1213    public Package definePackage(String name,
1214            String specTitle,
1215            String specVersion,
1216            String specVendor,
1217            String implTitle,
1218            String implVersion,
1219            String implVendor,
1220            URL sealBase)
1221     throws IllegalArgumentException {
1222        return super.definePackage(name, specTitle, specVersion,
1223                specVendor, implTitle, implVersion, implVendor, sealBase);
1224    }
1225
1226    public Package getPackage(String name) {
1227        return super.getPackage(name);
1228    }
1229
1230    public Package[] getPackages() {
1231        return super.getPackages();
1232    }
1233
1234    public Class<?> findClass(String name)
1235        throws ClassNotFoundException {
1236       return super.findClass(name);
1237    }
1238
1239    public String findLibrary(String libname) {
1240        return super.findLibrary(libname);
1241    }
1242
1243    public Class<?> loadClass(String name, boolean resolve)
1244                                            throws ClassNotFoundException {
1245        return super.loadClass(name, resolve);
1246    }
1247
1248    public URL findResource(String name) {
1249        return super.findResource(name);
1250    }
1251
1252    public Enumeration<URL> findResources(String resName)
1253                                            throws IOException {
1254        return super.findResources(resName);
1255    }
1256
1257    public Class<?> findSystemClazz(String name) throws ClassNotFoundException {
1258        return super.findSystemClass(name);
1259    }
1260
1261    public Class<?> findLoadedClazz(String name) {
1262        return super.findLoadedClass(name);
1263    }
1264}
1265