SystemTest.java revision cc05ad238516f1303687aba4a978e24e57c0c07a
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.KnownFailure;
21import dalvik.annotation.TestTargets;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetNew;
24import dalvik.annotation.TestTargetClass;
25
26import java.io.ByteArrayInputStream;
27import java.io.ByteArrayOutputStream;
28import java.io.IOException;
29import java.io.InputStream;
30import java.io.PrintStream;
31import java.nio.channels.Channel;
32import java.nio.channels.spi.SelectorProvider;
33import java.security.Permission;
34import java.util.Map;
35import java.util.Properties;
36import java.util.Vector;
37
38@TestTargetClass(System.class)
39public class SystemTest extends junit.framework.TestCase {
40
41    static boolean flag = false;
42
43    static boolean ranFinalize = false;
44
45    /**
46     * @tests java.lang.System#setIn(java.io.InputStream)
47     */
48    @TestTargetNew(
49        level = TestLevel.COMPLETE,
50        notes = "",
51        method = "setIn",
52        args = {java.io.InputStream.class}
53    )
54    @KnownFailure("Security checking is missed. ToT fixed.")
55    public void test_setInLjava_io_InputStream() {
56        InputStream orgIn = System.in;
57        InputStream in = new ByteArrayInputStream(new byte[0]);
58        System.setIn(in);
59        assertTrue("in not set", System.in == in);
60        System.setIn(orgIn);
61
62        SecurityManager sm = new SecurityManager() {
63
64            public void checkPermission(Permission perm) {
65                if(perm.getName().equals("setIO")) {
66                    throw new SecurityException();
67                }
68            }
69        };
70
71        SecurityManager oldSm = System.getSecurityManager();
72        System.setSecurityManager(sm);
73
74        try {
75            System.setIn(in);
76            fail("SecurityException should be thrown.");
77        } catch (SecurityException e) {
78            // expected
79        } finally {
80            System.setSecurityManager(oldSm);
81        }
82    }
83
84    /**
85     * @tests java.lang.System#setOut(java.io.PrintStream)
86     */
87    @TestTargetNew(
88        level = TestLevel.COMPLETE,
89        notes = "",
90        method = "setOut",
91        args = {java.io.PrintStream.class}
92    )
93    @KnownFailure("Security checking is missed. ToT fixed.")
94    public void test_setOutLjava_io_PrintStream() {
95        PrintStream orgOut = System.out;
96        PrintStream out = new PrintStream(new ByteArrayOutputStream());
97        System.setOut(out);
98        assertTrue("out not set", System.out == out);
99        System.setOut(orgOut);
100
101        SecurityManager sm = new SecurityManager() {
102
103            public void checkPermission(Permission perm) {
104                if(perm.getName().equals("setIO")) {
105                    throw new SecurityException();
106                }
107            }
108        };
109
110        SecurityManager oldSm = System.getSecurityManager();
111        System.setSecurityManager(sm);
112
113        try {
114            System.setOut(out);
115            fail("SecurityException should be thrown.");
116        } catch (SecurityException e) {
117            // expected
118        } finally {
119            System.setSecurityManager(oldSm);
120        }
121    }
122
123    /**
124     * @tests java.lang.System#setErr(java.io.PrintStream)
125     */
126    @TestTargetNew(
127        level = TestLevel.COMPLETE,
128        notes = "",
129        method = "setErr",
130        args = {java.io.PrintStream.class}
131    )
132    @KnownFailure("Security checking is missed. ToT fixed.")
133    public void test_setErrLjava_io_PrintStream() {
134        PrintStream orgErr = System.err;
135        PrintStream err = new PrintStream(new ByteArrayOutputStream());
136        System.setErr(err);
137        assertTrue("err not set", System.err == err);
138        System.setErr(orgErr);
139
140        SecurityManager sm = new SecurityManager() {
141
142            public void checkPermission(Permission perm) {
143                if(perm.getName().equals("setIO")) {
144                    throw new SecurityException();
145                }
146            }
147        };
148
149        SecurityManager oldSm = System.getSecurityManager();
150        System.setSecurityManager(sm);
151
152        try {
153            System.setErr(err);
154            fail("SecurityException should be thrown.");
155        } catch (SecurityException e) {
156            // expected
157        } finally {
158            System.setSecurityManager(oldSm);
159        }
160    }
161
162    /**
163     * @tests java.lang.System#arraycopy(java.lang.Object, int,
164     *        java.lang.Object, int, int)
165     */
166    @TestTargetNew(
167        level = TestLevel.COMPLETE,
168        notes = "",
169        method = "arraycopy",
170        args = {java.lang.Object.class, int.class, java.lang.Object.class,
171                int.class, int.class}
172    )
173    @KnownFailure("Doesn't throw IndexOutOfBoundsException for boundary value " +
174            "of src position. Failure in native code, doesn't check overflow.")
175    public void test_arraycopyLjava_lang_ObjectILjava_lang_ObjectII() {
176        // Test for method void java.lang.System.arraycopy(java.lang.Object,
177        // int, java.lang.Object, int, int)
178        Integer a[] = new Integer[20];
179        Integer b[] = new Integer[20];
180        int i = 0;
181        while (i < a.length) {
182            a[i] = new Integer(i);
183            ++i;
184        }
185        System.arraycopy(a, 0, b, 0, a.length);
186        for (i = 0; i < a.length; i++)
187            assertTrue("Copied elements incorrectly", a[i].equals(b[i]));
188
189        /* Non primitive array types don't need to be identical */
190        String[] source1 = new String[] { "element1" };
191        Object[] dest1 = new Object[1];
192        System.arraycopy(source1, 0, dest1, 0, dest1.length);
193        assertTrue("Invalid copy 1", dest1[0] == source1[0]);
194
195        char[][] source = new char[][] { { 'H', 'e', 'l', 'l', 'o' },
196                { 'W', 'o', 'r', 'l', 'd' } };
197        char[][] dest = new char[2][];
198        System.arraycopy(source, 0, dest, 0, dest.length);
199        assertTrue("Invalid copy 2", dest[0] == source[0]
200                && dest[1] == source[1]);
201
202        try {
203            // copy from non array object into Object array
204            System.arraycopy(new Object(), 0, b, 0, 0);
205            fail("ArrayStoreException is not thrown.");
206        } catch(ArrayStoreException  ase) {
207            //expected
208        }
209
210        try {
211            // copy from Object array into non array object
212            System.arraycopy(a, 0, new Object(), 0, 0);
213            fail("ArrayStoreException is not thrown.");
214        } catch(ArrayStoreException  ase) {
215            //expected
216        }
217
218        try {
219            // copy from primitive array into object array
220            System.arraycopy(new char[] {'a'}, 0, new String[1], 0, 1);
221            fail("ArrayStoreException is not thrown.");
222        } catch(ArrayStoreException  ase) {
223            //expected
224        }
225
226        try {
227            // copy from object array into primitive array
228            System.arraycopy(new String[] {"a"}, 0, new char[1], 0, 1);
229            fail("ArrayStoreException is not thrown.");
230        } catch(ArrayStoreException  ase) {
231            //expected
232        }
233
234        try {
235            // copy from primitive array into an array of another primitive type
236            System.arraycopy(new char[] {'a'}, 0, new int[1], 0, 1);
237            fail("ArrayStoreException is not thrown.");
238        } catch(ArrayStoreException  ase) {
239            //expected
240        }
241
242        try {
243            // copy from object array into an array of another Object type
244            System.arraycopy(new Character[] {'a'}, 0, new Integer[1], 0, 1);
245            fail("ArrayStoreException is not thrown.");
246        } catch(ArrayStoreException  ase) {
247            //expected
248        }
249
250        try {
251            // copy from null into an array of a primitive type
252            System.arraycopy(null, 0, new int[1], 0, 1);
253            fail("NullPointerException is not thrown.");
254        } catch(NullPointerException npe) {
255            //expected
256        }
257
258        try {
259            // copy from a primitive array into null
260            System.arraycopy(new int[]{'1'}, 0, null, 0, 1);
261            fail("NullPointerException is not thrown.");
262        } catch(NullPointerException npe) {
263            //expected
264        }
265
266        try {
267            System.arraycopy(a, a.length + 1, b, 0, 1);
268            fail("IndexOutOfBoundsException is not thrown.");
269        } catch(IndexOutOfBoundsException ioobe) {
270            //expected
271        }
272
273        try {
274            System.arraycopy(a, -1, b, 0, 1);
275            fail("IndexOutOfBoundsException is not thrown.");
276        } catch(IndexOutOfBoundsException ioobe) {
277            //expected
278        }
279
280        try {
281            System.arraycopy(a, 0, b, -1, 1);
282            fail("IndexOutOfBoundsException is not thrown.");
283        } catch(IndexOutOfBoundsException ioobe) {
284            //expected
285        }
286
287        try {
288            System.arraycopy(a, 0, b, 0, -1);
289            fail("IndexOutOfBoundsException is not thrown.");
290        } catch(IndexOutOfBoundsException ioobe) {
291            //expected
292        }
293
294        try {
295            System.arraycopy(a, 11, b, 0, 10);
296            fail("IndexOutOfBoundsException is not thrown.");
297        } catch(IndexOutOfBoundsException ioobe) {
298            //expected
299        }
300
301        try {
302            System.arraycopy(a, Integer.MAX_VALUE, b, 0, 10);
303            fail("IndexOutOfBoundsException is not thrown.");
304        } catch(IndexOutOfBoundsException ioobe) {
305            //expected
306        }
307
308        try {
309            System.arraycopy(a, 0, b, Integer.MAX_VALUE, 10);
310            fail("IndexOutOfBoundsException is not thrown.");
311        } catch(IndexOutOfBoundsException ioobe) {
312            //expected
313        }
314
315        try {
316            System.arraycopy(a, 0, b, 10, Integer.MAX_VALUE);
317            fail("IndexOutOfBoundsException is not thrown.");
318        } catch(IndexOutOfBoundsException ioobe) {
319            //expected
320        }
321    }
322
323    /**
324     * @tests java.lang.System#currentTimeMillis()
325     */
326    @TestTargetNew(
327        level = TestLevel.COMPLETE,
328        notes = "",
329        method = "currentTimeMillis",
330        args = {}
331    )
332    public void test_currentTimeMillis() {
333        // Test for method long java.lang.System.currentTimeMillis()
334        try {
335            long firstRead = System.currentTimeMillis();
336            try {
337                Thread.sleep(150);
338            } catch (InterruptedException e) {
339            }
340            long secondRead = System.currentTimeMillis();
341            assertTrue("Incorrect times returned: " + firstRead + ", "
342                    + secondRead, firstRead < secondRead);
343        } catch (Exception e) {
344            fail("Exception during test: " + e.toString());
345        }
346    }
347
348    /**
349     * @tests java.lang.System#exit(int)
350     */
351    @TestTargetNew(
352        level = TestLevel.COMPLETE,
353        notes = "Verifies SecurityException.",
354        method = "exit",
355        args = {int.class}
356    )
357    public void test_exitI() {
358        SecurityManager sm = new SecurityManager() {
359
360            final String forbidenPermissionName = "user.dir";
361
362            public void checkPermission(Permission perm) {
363                if (perm.getName().equals(forbidenPermissionName)) {
364                    throw new SecurityException();
365                }
366            }
367
368            public void checkExit(int status) {
369                if(status == -1)
370                    throw new SecurityException();
371            }
372
373        };
374
375        SecurityManager oldSm = System.getSecurityManager();
376        System.setSecurityManager(sm);
377        try {
378            System.exit(-1);
379            fail("Should throw SecurityException");
380        } catch (SecurityException e) {
381            // expected
382        } finally {
383            System.setSecurityManager(oldSm);
384        }
385    }
386
387    /**
388     * @tests java.lang.System#getProperties()
389     */
390    @TestTargetNew(
391        level = TestLevel.COMPLETE,
392        notes = "",
393        method = "getProperties",
394        args = {}
395    )
396    public void test_getProperties() {
397
398       // Test for method java.util.Properties java.lang.System.getProperties()
399       /* String[] props = { "java.version", "java.vendor", "java.vendor.url",
400                "java.home", "java.vm.specification.version",
401                "java.vm.specification.vendor", "java.vm.specification.name",
402                "java.vm.version", "java.vm.vendor", "java.vm.name",
403                "java.specification.name", "java.specification.vendor",
404                "java.specification.name", "java.class.version",
405                "java.class.path", "java.ext.dirs", "os.name", "os.arch",
406                "os.version", "file.separator", "path.separator",
407                "line.separator", "user.name", "user.home", "user.dir", };
408        */
409
410        String [] props = {"java.vendor.url",
411                "java.class.path", "user.home",
412                "java.class.version", "os.version",
413                "java.vendor", "user.dir",
414                /*"user.timezone",*/ "path.separator",
415                "os.name", "os.arch",
416                "line.separator", "file.separator",
417                "user.name", "java.version", "java.home" };
418
419        /* Available properties.
420        String [] props = {"java.boot.class.path", "java.class.path",
421                "java.class.version", "java.compiler", "java.ext.dirs",
422                "java.home", "java.io.tmpdir", "java.library.path",
423                "java.vendor", "java.vendor.url", "java.version",
424                "java.vm.name", "java.vm.specification.name",
425                "java.vm.specification.vendor", "java.vm.specification.version",
426                "java.vm.vendor", "java.vm.version", "java.specification.name",
427                "java.specification.vendor", "java.specification.version",
428                "os.arch", "os.name", "os.version", "user.home", "user.name",
429                "user.dir", "file.separator", "line.separator",
430                "path.separator", "java.runtime.name", "java.runtime.version",
431                "java.vm.vendor.url", "file.encoding","user.language",
432                "user.region"};
433        */
434
435        Properties p = System.getProperties();
436        assertTrue(p.size() > 0);
437
438        // Ensure spec'ed properties are non-null. See System.getProperties()
439        // spec.
440
441        for (int i = 0; i < props.length; i++) {
442            assertNotNull("There is no property among returned properties: "
443                    + props[i], p.getProperty(props[i]));
444            assertNotNull("System property is null: " + props[i],
445                    System.getProperty(props[i]));
446        }
447
448        SecurityManager sm = new SecurityManager() {
449
450            public void checkPermission(Permission perm) {
451            }
452
453            public void checkPropertiesAccess() {
454                throw new SecurityException();
455            }
456        };
457
458        SecurityManager oldSm = System.getSecurityManager();
459        System.setSecurityManager(sm);
460
461        try {
462            System.getProperties();
463            fail("SecurityException should be thrown.");
464        } catch (SecurityException e) {
465            // expected
466        } finally {
467            System.setSecurityManager(oldSm);
468        }
469    }
470
471    /**
472     * @tests java.lang.System#getProperty(java.lang.String)
473     */
474    @TestTargetNew(
475        level = TestLevel.COMPLETE,
476        notes = "",
477        method = "getProperty",
478        args = {java.lang.String.class}
479    )
480    public void test_getPropertyLjava_lang_String() {
481        // Test for method java.lang.String
482        // java.lang.System.getProperty(java.lang.String)
483        assertTrue("Failed to return correct property value", System
484                .getProperty("line.separator").indexOf("\n", 0) >= 0);
485
486        boolean is8859_1 = true;
487        String encoding = System.getProperty("file.encoding");
488        byte[] bytes = new byte[128];
489        char[] chars = new char[128];
490        for (int i = 0; i < bytes.length; i++) {
491            bytes[i] = (byte) (i + 128);
492            chars[i] = (char) (i + 128);
493        }
494        String charResult = new String(bytes);
495        byte[] byteResult = new String(chars).getBytes();
496        if (charResult.length() == 128 && byteResult.length == 128) {
497            for (int i = 0; i < bytes.length; i++) {
498                if (charResult.charAt(i) != (char) (i + 128)
499                        || byteResult[i] != (byte) (i + 128))
500                    is8859_1 = false;
501            }
502        } else
503            is8859_1 = false;
504        String[] possibles = new String[] { "ISO8859_1", "8859_1", "ISO8859-1",
505                "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1978", "ISO-IR-100",
506                "LATIN1", "CSISOLATIN1" };
507        boolean found8859_1 = false;
508        for (int i = 0; i < possibles.length; i++) {
509            if (possibles[i].equals(encoding)) {
510                found8859_1 = true;
511                break;
512            }
513        }
514        assertTrue("Wrong encoding: " + encoding, !is8859_1 || found8859_1);
515
516        try {
517            System.getProperty(null);
518            fail("NullPointerException should be thrown.");
519        } catch(NullPointerException npe) {
520            //expected
521        }
522
523        try {
524            System.getProperty("");
525            fail("IllegalArgumentException should be thrown.");
526        } catch(IllegalArgumentException  iae) {
527            //expected
528        }
529
530        SecurityManager sm = new SecurityManager() {
531
532            public void checkPermission(Permission perm) {
533            }
534
535            @SuppressWarnings("unused")
536            public void checkPropertyAccess(String key) {
537                throw new SecurityException();
538            }
539        };
540
541        SecurityManager oldSm = System.getSecurityManager();
542        System.setSecurityManager(sm);
543
544        try {
545            System.getProperty("user.name");
546            fail("SecurityException should be thrown.");
547        } catch (SecurityException e) {
548            // expected
549        } finally {
550            System.setSecurityManager(oldSm);
551        }
552    }
553
554    /**
555     * @tests java.lang.System#getProperty(java.lang.String, java.lang.String)
556     */
557    @TestTargetNew(
558        level = TestLevel.COMPLETE,
559        notes = "",
560        method = "getProperty",
561        args = {java.lang.String.class, java.lang.String.class}
562    )
563    public void test_getPropertyLjava_lang_StringLjava_lang_String() {
564        // Test for method java.lang.String
565        // java.lang.System.getProperty(java.lang.String, java.lang.String)
566        assertTrue("Failed to return correct property value: "
567                + System.getProperty("line.separator", "99999"), System
568                .getProperty("line.separator", "99999").indexOf("\n", 0) >= 0);
569        assertEquals("Failed to return correct property value", "bogus", System
570                .getProperty("bogus.prop", "bogus"));
571
572        try {
573            System.getProperty(null, "0.0");
574            fail("NullPointerException should be thrown.");
575        } catch(NullPointerException npe) {
576            //expected
577        }
578
579        try {
580            System.getProperty("", "0");
581            fail("IllegalArgumentException should be thrown.");
582        } catch(IllegalArgumentException  iae) {
583            //expected
584        }
585
586        SecurityManager sm = new SecurityManager() {
587
588            public void checkPermission(Permission perm) {
589            }
590
591            @SuppressWarnings("unused")
592            public void checkPropertyAccess(String key) {
593                throw new SecurityException();
594            }
595        };
596
597        SecurityManager oldSm = System.getSecurityManager();
598        System.setSecurityManager(sm);
599
600        try {
601            System.getProperty("java.version", "0");
602            fail("SecurityException should be thrown.");
603        } catch (SecurityException e) {
604            // expected
605        } finally {
606            System.setSecurityManager(oldSm);
607        }
608    }
609
610    /**
611     * @tests java.lang.System#setProperty(java.lang.String, java.lang.String)
612     */
613    @TestTargetNew(
614        level = TestLevel.COMPLETE,
615        notes = "",
616        method = "setProperty",
617        args = {java.lang.String.class, java.lang.String.class}
618    )
619    public void test_setPropertyLjava_lang_StringLjava_lang_String() {
620        // Test for method java.lang.String
621        // java.lang.System.setProperty(java.lang.String, java.lang.String)
622
623        assertNull("Failed to return null", System.setProperty("testing",
624                "value1"));
625        assertTrue("Failed to return old value", System.setProperty("testing",
626                "value2") == "value1");
627        assertTrue("Failed to find value",
628                System.getProperty("testing") == "value2");
629
630        boolean exception = false;
631        try {
632            System.setProperty("", "default");
633        } catch (IllegalArgumentException e) {
634            exception = true;
635        }
636        assertTrue("Expected IllegalArgumentException", exception);
637    }
638
639    /**
640     * @tests java.lang.System#getSecurityManager()
641     */
642    @TestTargetNew(
643        level = TestLevel.PARTIAL,
644        notes = "Doesn't check positive functionality.",
645        method = "getSecurityManager",
646        args = {}
647    )
648    public void test_getSecurityManager() {
649        // Test for method java.lang.SecurityManager
650        // java.lang.System.getSecurityManager()
651        assertNull("Returned incorrect SecurityManager", System
652                .getSecurityManager());
653    }
654
655    /**
656     * @tests java.lang.System#identityHashCode(java.lang.Object)
657     */
658    @TestTargetNew(
659        level = TestLevel.COMPLETE,
660        notes = "",
661        method = "identityHashCode",
662        args = {java.lang.Object.class}
663    )
664    public void test_identityHashCodeLjava_lang_Object() {
665        // Test for method int
666        // java.lang.System.identityHashCode(java.lang.Object)
667        Object o = new Object();
668        String s = "Gabba";
669        assertEquals("Nonzero returned for null",
670                0, System.identityHashCode(null));
671        assertTrue("Nonequal has returned for Object", System
672                .identityHashCode(o) == o.hashCode());
673        assertTrue("Same as usual hash returned for String", System
674                .identityHashCode(s) != s.hashCode());
675    }
676
677    /**
678     * @throws IOException
679     * @tests java.lang.System#inheritedChannel()
680     */
681    @TestTargetNew(
682        level = TestLevel.COMPLETE,
683        notes = "",
684        method = "inheritedChannel",
685        args = {}
686    )
687    @KnownFailure("Security checking is missed. ToT fixed.")
688    public void test_inheritedChannel() throws IOException {
689        Channel iChannel = System.inheritedChannel();
690        assertNull("Incorrect value of channel", iChannel);
691        SelectorProvider sp = SelectorProvider.provider();
692        assertEquals("Incorrect value of channel",
693                sp.inheritedChannel(), iChannel);
694
695        SecurityManager sm = new SecurityManager() {
696
697            public void checkPermission(Permission perm) {
698                if(perm.getName().equals("inheritedChannel")) {
699                    throw new SecurityException();
700                }
701            }
702        };
703
704        SecurityManager oldSm = System.getSecurityManager();
705        System.setSecurityManager(sm);
706
707        try {
708            System.inheritedChannel();
709            fail("SecurityException should be thrown.");
710        } catch (SecurityException e) {
711            // expected
712        } finally {
713            System.setSecurityManager(oldSm);
714        }
715    }
716
717    /**
718     * @tests java.lang.System#runFinalization()
719     */
720    @TestTargetNew(
721        level = TestLevel.COMPLETE,
722        notes = "",
723        method = "runFinalization",
724        args = {}
725    )
726    public void test_runFinalization() {
727        // Test for method void java.lang.System.runFinalization()
728
729        flag = true;
730        createInstance();
731        int count = 10;
732        // the gc below likely bogosifies the test, but will have to do for
733        // the moment
734        while (!ranFinalize && count-- > 0) {
735            System.gc();
736            System.runFinalization();
737        }
738        assertTrue("Failed to run finalization", ranFinalize);
739    }
740
741    /**
742     * @tests java.lang.System#runFinalizersOnExit(boolean)
743     */
744    @TestTargetNew(
745        level = TestLevel.COMPLETE,
746        notes = "",
747        method = "runFinalizersOnExit",
748        args = {boolean.class}
749    )
750    @KnownFailure("Security checking is missed. ToT fixed.")
751    @SuppressWarnings("deprecation")
752    public void test_runFinalizersOnExitZ() {
753        // Can we call the method at least?
754        try {
755            System.runFinalizersOnExit(false);
756        } catch (Throwable t) {
757            fail("Failed to set runFinalizersOnExit");
758        }
759
760        try {
761            System.runFinalizersOnExit(true);
762        } catch (Throwable t) {
763            fail("Failed to set runFinalizersOnExit");
764        }
765
766        SecurityManager sm = new SecurityManager() {
767
768            public void checkPermission(Permission perm) {
769            }
770
771            public void checkExit(int status) {
772                throw new SecurityException();
773            }
774        };
775
776        SecurityManager oldSm = System.getSecurityManager();
777        System.setSecurityManager(sm);
778
779        try {
780            System.runFinalizersOnExit(true);
781            fail("SecurityException should be thrown.");
782        } catch (SecurityException e) {
783            // expected
784        } finally {
785            System.setSecurityManager(oldSm);
786        }
787    }
788
789    /**
790     * @tests java.lang.System#setProperties(java.util.Properties)
791     */
792    @TestTargetNew(
793        level = TestLevel.COMPLETE,
794        notes = "",
795        method = "setProperties",
796        args = {java.util.Properties.class}
797    )
798    public void test_setPropertiesLjava_util_Properties() {
799        // Test for method void
800        // java.lang.System.setProperties(java.util.Properties)
801
802        Properties orgProps = System.getProperties();
803        java.util.Properties tProps = new java.util.Properties();
804        tProps.put("test.prop", "this is a test property");
805        tProps.put("bogus.prop", "bogus");
806        System.setProperties(tProps);
807        try {
808            assertEquals("Failed to set properties", "this is a test property", System.getProperties()
809                    .getProperty("test.prop"));
810        } finally {
811            // restore the original properties
812            System.setProperties(orgProps);
813        }
814    }
815
816    //Regression Test for Harmony-2356
817    @TestTargetNew(
818        level = TestLevel.COMPLETE,
819        notes = "",
820        method = "getenv",
821        args = {}
822    )
823    public void testEnvUnmodifiable() {
824        Map map = System.getenv();
825        try {
826            map.containsKey(null);
827            fail("Should throw NullPointerExcepiton.");
828        } catch (NullPointerException e) {
829            // expected
830        }
831
832        try {
833            map.containsKey(new Integer(10));
834            fail("Should throw ClassCastException.");
835        } catch (ClassCastException e) {
836            // expected
837        }
838
839        try {
840            map.containsValue(null);
841            fail("Should throw NullPointerExcepiton.");
842        } catch (NullPointerException e) {
843            // expected
844        }
845
846        try {
847            map.containsValue(new Integer(10));
848            fail("Should throw ClassCastException.");
849        } catch (ClassCastException e) {
850            // expected
851        }
852
853        try {
854            map.get(null);
855            fail("Should throw NullPointerExcepiton.");
856        } catch (NullPointerException e) {
857            // expected
858        }
859
860        try {
861            map.get(new Integer(10));
862            fail("Should throw ClassCastException.");
863        } catch (ClassCastException e) {
864            // expected
865        }
866
867        try {
868            map.put(null, "AAA");
869            fail("Should throw UnsupportedOperationExcepiton.");
870        } catch (UnsupportedOperationException e) {
871            // expected
872        }
873
874        try {
875            map.put("AAA", new Integer(10));
876            fail("Should throw UnsupportedOperationException.");
877        } catch (UnsupportedOperationException e) {
878            // expected
879        }
880
881        try {
882            map.put("AAA", "BBB");
883            fail("Should throw UnsupportedOperationException.");
884        } catch (UnsupportedOperationException e) {
885            // expected
886        }
887
888        try {
889            map.clear();
890            fail("Should throw UnsupportedOperationException.");
891        } catch (UnsupportedOperationException e) {
892            // expected
893        }
894
895        try {
896            map.remove(null);
897            fail("Should throw UnsupportedOperationException.");
898        } catch (UnsupportedOperationException e) {
899            // expected
900        }
901
902    }
903    @TestTargets({
904        @TestTargetNew(
905            level = TestLevel.COMPLETE,
906            notes = "",
907            method = "setSecurityManager",
908            args = {java.lang.SecurityManager.class}
909        ),
910        @TestTargetNew(
911            level = TestLevel.COMPLETE,
912            notes = "",
913            method = "getSecurityManager",
914            args = {}
915        )
916    })
917    public void test_setSecurityManagerLjava_lang_SecurityManager() {
918        assertEquals("Incorrect SecurityManager",
919                null, System.getSecurityManager());
920        try {
921            SecurityManager localManager = new MockSecurityManager();
922            System.setSecurityManager(localManager);
923            assertEquals("Incorrect SecurityManager",
924                    localManager, System.getSecurityManager());
925        } finally {
926            System.setSecurityManager(null);
927        }
928    }
929
930    @TestTargetNew(
931        level = TestLevel.COMPLETE,
932        notes = "",
933        method = "clearProperty",
934        args = {java.lang.String.class}
935    )
936    public void test_clearProperty() {
937        System.setProperty("test", "value");
938        System.clearProperty("test");
939        assertNull("Property was not deleted.", System.getProperty("test"));
940
941        try {
942            System.clearProperty(null);
943            fail("NullPointerException is not thrown.");
944        } catch(NullPointerException npe) {
945            //expected
946        }
947
948        try {
949            System.clearProperty("");
950            fail("IllegalArgumentException is not thrown.");
951        } catch(IllegalArgumentException iae) {
952            //expected
953        }
954
955        SecurityManager sm = new SecurityManager() {
956
957            public void checkPermission(Permission perm) {
958                if (perm.getName().equals("test")) {
959                    throw new SecurityException();
960                }
961            }
962        };
963
964        SecurityManager oldSm = System.getSecurityManager();
965        System.setSecurityManager(sm);
966        try {
967            System.clearProperty("test");
968            fail("SecurityException should be thrown.");
969        } catch (SecurityException e) {
970            // expected
971        } finally {
972            System.setSecurityManager(oldSm);
973        }
974    }
975
976    @TestTargetNew(
977        level = TestLevel.COMPLETE,
978        notes = "",
979        method = "gc",
980        args = {}
981    )
982    public void test_gc() {
983        Runtime rt =  Runtime.getRuntime();
984        Vector<StringBuffer> vec = new Vector<StringBuffer>();
985        long beforeTest = rt.freeMemory();
986        while(rt.freeMemory() < beforeTest * 2/3) {
987             vec.add(new StringBuffer(1000));
988        }
989        vec = null;
990        long beforeGC = rt.freeMemory();
991        System.gc();
992        long afterGC = rt.freeMemory();
993        assertTrue("memory was not released after calling System.gc()." +
994                "before gc: " + beforeGC + "; after gc: " + afterGC,
995                beforeGC < afterGC);
996    }
997
998    @TestTargetNew(
999        level = TestLevel.COMPLETE,
1000        notes = "",
1001        method = "getenv",
1002        args = {}
1003    )
1004    @KnownFailure("getenv() method returns empty map, " +
1005            "because getEnvByIndex always returns null. " +
1006            "ToT fixed.")
1007    public void test_getenv() {
1008
1009        // String[] props = { "PATH", "HOME", "USER"};
1010        // only PATH of these three exists on android
1011        String[] props = { "PATH" };
1012
1013        Map<String,String> envMap = System.getenv();
1014        assertFalse("environment map is empty.", envMap.isEmpty());
1015        assertTrue("env map contains less than 3 keys.",
1016                props.length < envMap.keySet().size());
1017        for(int i = 0; i < props.length; i++) {
1018           assertNotNull("There is no property: " + props[i],
1019                   envMap.get(props[i]));
1020        }
1021
1022        SecurityManager sm = new SecurityManager() {
1023
1024            public void checkPermission(Permission perm) {
1025                if(perm.getName().equals("getenv.*")) {
1026                    throw new SecurityException();
1027                }
1028            }
1029        };
1030
1031        SecurityManager oldSm = System.getSecurityManager();
1032        System.setSecurityManager(sm);
1033
1034        try {
1035            System.getenv();
1036            fail("SecurityException should be thrown.");
1037        } catch (SecurityException e) {
1038            // expected
1039        } finally {
1040            System.setSecurityManager(oldSm);
1041        }
1042    }
1043
1044    @TestTargetNew(
1045        level = TestLevel.COMPLETE,
1046        notes = "",
1047        method = "getenv",
1048        args = {java.lang.String.class}
1049    )
1050    public void test_getenvLString() {
1051
1052        assertNotNull("PATH environment variable is not found",
1053                  System.getenv("PATH"));
1054
1055        assertNull("Doesn't return NULL for non existent property",
1056                  System.getenv("nonexistent.property"));
1057
1058        SecurityManager sm = new SecurityManager() {
1059
1060            public void checkPermission(Permission perm) {
1061                if(perm.getName().equals("getenv.PATH")) {
1062                    throw new SecurityException();
1063                }
1064            }
1065        };
1066
1067        SecurityManager oldSm = System.getSecurityManager();
1068        System.setSecurityManager(sm);
1069
1070        try {
1071            System.getenv("PATH");
1072            fail("SecurityException should be thrown.");
1073        } catch (SecurityException e) {
1074            // expected
1075        } finally {
1076            System.setSecurityManager(oldSm);
1077        }
1078
1079        try {
1080            System.getenv(null);
1081            fail("NullPointerException is not thrown.");
1082        } catch(NullPointerException npe) {
1083            //expected
1084        }
1085    }
1086
1087    @TestTargetNew(
1088        level = TestLevel.COMPLETE,
1089        notes = "",
1090        method = "load",
1091        args = {java.lang.String.class}
1092    )
1093    @KnownFailure("UnsatisfiedLinkError is not thrown. ToT fixed.")
1094    public void test_load() {
1095        try {
1096            new TestLibrary().checkString();
1097            fail("UnsatisfiedLinkError was not thrown.");
1098        } catch(UnsatisfiedLinkError  e) {
1099            //expected
1100        }
1101
1102        try {
1103            System.load("nonExistentLibrary");
1104            fail("UnsatisfiedLinkError was not thrown.");
1105        } catch(UnsatisfiedLinkError ule) {
1106            //expected
1107        }
1108
1109        try {
1110            System.load(null);
1111            fail("NullPointerException was not thrown.");
1112        } catch(NullPointerException npe) {
1113            //expected
1114        }
1115
1116        SecurityManager sm = new SecurityManager() {
1117
1118            public void checkPermission(Permission perm) {
1119
1120            }
1121
1122            public void checkLink(String lib) {
1123                throw new SecurityException();
1124            }
1125        };
1126
1127        SecurityManager oldSm = System.getSecurityManager();
1128        System.setSecurityManager(sm);
1129        try {
1130            System.load("libTestLibrary.so");
1131            fail("SecurityException should be thrown.");
1132        } catch (SecurityException e) {
1133            // expected
1134        } finally {
1135            System.setSecurityManager(oldSm);
1136        }
1137    }
1138
1139    @TestTargetNew(
1140        level = TestLevel.COMPLETE,
1141        notes = "",
1142        method = "loadLibrary",
1143        args = {java.lang.String.class}
1144    )
1145    @KnownFailure("Security checking is missed. ToT fixed.")
1146    public void test_loadLibrary() {
1147
1148        try {
1149            System.loadLibrary("nonExistentLibrary");
1150            fail("UnsatisfiedLinkError was not thrown.");
1151        } catch(UnsatisfiedLinkError ule) {
1152            //expected
1153        }
1154
1155        try {
1156            System.loadLibrary(null);
1157            fail("NullPointerException was not thrown.");
1158        } catch(NullPointerException npe) {
1159            //expected
1160        }
1161
1162        SecurityManager sm = new SecurityManager() {
1163
1164            public void checkPermission(Permission perm) {
1165            }
1166
1167            public void checkLink(String lib) {
1168                throw new SecurityException();
1169            }
1170         };
1171
1172         SecurityManager oldSm = System.getSecurityManager();
1173         System.setSecurityManager(sm);
1174         try {
1175             System.loadLibrary("libTestLibrary.so");
1176             fail("SecurityException should be thrown.");
1177         } catch (SecurityException e) {
1178             // expected
1179         } finally {
1180             System.setSecurityManager(oldSm);
1181         }
1182    }
1183
1184    @TestTargetNew(
1185        level = TestLevel.COMPLETE,
1186        notes = "",
1187        method = "mapLibraryName",
1188        args = {java.lang.String.class}
1189    )
1190    public void test_mapLibraryName() {
1191        assertEquals("libname.so", System.mapLibraryName("name"));
1192
1193        try {
1194            System.mapLibraryName(null);
1195            fail("NullPointerException is not thrown.");
1196        } catch(NullPointerException npe) {
1197            //expected
1198        }
1199    }
1200
1201    @TestTargetNew(
1202        level = TestLevel.COMPLETE,
1203        notes = "",
1204        method = "nanoTime",
1205        args = {}
1206    )
1207    public void test_nanoTime() {
1208        long sleepTime = 5000;
1209        long beginTime = System.nanoTime();
1210        try {
1211            Thread.sleep(sleepTime);
1212        } catch(Exception e) {
1213            fail("Unknown exception was thrown.");
1214        }
1215        long endTime = System.nanoTime();
1216        assertTrue((endTime - beginTime) > sleepTime * 1000000);
1217    }
1218
1219    @Override
1220    protected void setUp() {
1221        flag = false;
1222        ranFinalize = false;
1223    }
1224
1225    protected SystemTest createInstance() {
1226        return new SystemTest("FT");
1227    }
1228
1229    @Override
1230    protected void finalize() {
1231        if (flag)
1232            ranFinalize = true;
1233    }
1234
1235    public SystemTest() {
1236    }
1237
1238    public SystemTest(String name) {
1239        super(name);
1240    }
1241
1242    private class MockSecurityManager extends SecurityManager {
1243        @Override
1244        public void checkPermission(Permission perm) {
1245            if (perm.equals(new RuntimePermission("inheritedChannel")))
1246                throw new SecurityException("Incorrect permission");
1247        }
1248    }
1249}
1250