summaryrefslogtreecommitdiff
path: root/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java
blob: e96ace1ada11993928702080d7db1c32bc1309a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.harmony.logging.tests.java.util.logging;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.security.Permission;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.LoggingPermission;

import junit.framework.TestCase;

import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream;
import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper;

/**
 * add/get logger(dot)
 */
public class LogManagerTest extends TestCase {

    private static final String FOO = "LogManagerTestFoo";

    LogManager mockManager;

    LogManager manager = LogManager.getLogManager();

    MockPropertyChangeListener listener;

    Properties props;

    private static String className = LogManagerTest.class.getName();

    static Handler handler = null;

    static final String CONFIG_CLASS = "java.util.logging.config.class";

    static final String CONFIG_FILE = "java.util.logging.config.file";

    static final String MANAGER_CLASS = "java.util.logging.config.manager";

    static final String clearPath = System.getProperty("clearpath");


    /*
      * @see TestCase#setUp()
      */
    protected void setUp() throws Exception {
        super.setUp();
        mockManager = new MockLogManager();
        listener = new MockPropertyChangeListener();
        handler = new MockHandler();
        props = initProps();
    }

    static Properties initProps() throws Exception {
        Properties props = new Properties();
        props.put("handlers", className + "$MockHandler " + className
                + "$MockHandler");
        props.put("java.util.logging.FileHandler.pattern", "%h/java%u.log");
        props.put("java.util.logging.FileHandler.limit", "50000");
        props.put("java.util.logging.FileHandler.count", "5");
        props.put("java.util.logging.FileHandler.formatter",
                "java.util.logging.XMLFormatter");
        props.put(".level", "FINE");
        props.put("java.util.logging.ConsoleHandler.level", "OFF");
        props.put("java.util.logging.ConsoleHandler.formatter",
                "java.util.logging.SimpleFormatter");
        props.put("LogManagerTestFoo.handlers", "java.util.logging.ConsoleHandler");
        props.put("LogManagerTestFoo.level", "WARNING");
        return props;
    }

    /*
      * @see TestCase#tearDown()
      */
    protected void tearDown() throws Exception {
        super.tearDown();
        manager.reset();
        handler = null;
    }

    public void testAddGetLogger() {
        Logger log = new MockLogger(FOO, null);
        Logger foo = mockManager.getLogger(FOO);
        assertNull(foo);
        assertTrue(mockManager.addLogger(log));
        foo = mockManager.getLogger(FOO);
        assertSame(foo, log);
        assertNull(foo.getParent());

        try {
            mockManager.addLogger(null);
            fail("add null should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            mockManager.getLogger(null);
            fail("get null should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        assertNull(mockManager.getLogger("bad name"));

        Enumeration<String> enumar = mockManager.getLoggerNames();
        int i = 0;
        while (enumar.hasMoreElements()) {
            String name = (String) enumar.nextElement();
            i++;
            assertEquals(FOO, name);
        }
        assertEquals(i, 1);
    }

    public void testAddGetLogger_duplicateName() {
        // add logger with duplicate name has no effect
        Logger foo = new MockLogger(FOO, null);
        Logger foo2 = new MockLogger(FOO, null);
        assertTrue(mockManager.addLogger(foo));
        assertSame(foo, mockManager.getLogger(FOO));
        assertFalse(mockManager.addLogger(foo2));
        assertSame(foo, mockManager.getLogger(FOO));
        Enumeration<String> enumar = mockManager.getLoggerNames();
        int i = 0;
        while (enumar.hasMoreElements()) {
            enumar.nextElement();
            i++;
        }
        assertEquals(1, i);
    }

    public void testAddGetLogger_Hierachy() {
        Logger foo = new MockLogger("testAddGetLogger_Hierachy.foo", null);
        Logger child = new MockLogger("testAddGetLogger_Hierachy.foo.child",
                null);
        Logger fakeChild = new MockLogger(
                "testAddGetLogger_Hierachy.foo2.child", null);
        Logger grandson = new MockLogger(
                "testAddGetLogger_Hierachy.foo.child.grandson", null);
        Logger otherChild = new MockLogger(
                "testAddGetLogger_Hierachy.foo.child", null);
        assertNull(foo.getParent());
        assertNull(child.getParent());
        assertNull(grandson.getParent());
        assertNull(otherChild.getParent());

        // whenever a logger is added to a LogManager, hierarchy will be updated
        // accordingly
        assertTrue(mockManager.addLogger(child));
        assertNull(child.getParent());

        assertTrue(mockManager.addLogger(fakeChild));
        assertNull(fakeChild.getParent());

        assertTrue(mockManager.addLogger(grandson));
        assertSame(child, grandson.getParent());

        assertTrue(mockManager.addLogger(foo));
        assertSame(foo, child.getParent());
        assertNull(foo.getParent());
        assertNull(fakeChild.getParent());

        // but for non-mock LogManager, foo's parent should be root
        assertTrue(manager.addLogger(foo));
        assertSame(manager.getLogger(""), manager.getLogger(
                "testAddGetLogger_Hierachy.foo").getParent());

        // if we add one logger to two LogManager, parent will changed
        assertTrue(manager.addLogger(otherChild));
        assertTrue(manager.addLogger(grandson));
        assertSame(foo, otherChild.getParent());
        assertSame(otherChild, grandson.getParent());
    }

    public void testAddLoggerReverseOrder() {
        Logger root = new MockLogger("testAddLoggerReverseOrder", null);
        Logger foo = new MockLogger("testAddLoggerReverseOrder.foo", null);
        Logger fooChild = new MockLogger("testAddLoggerReverseOrder.foo.child",
                null);
        Logger fooGrandChild = new MockLogger(
                "testAddLoggerReverseOrder.foo.child.grand", null);
        Logger fooGrandChild2 = new MockLogger(
                "testAddLoggerReverseOrder.foo.child.grand2", null);

        Logger realRoot = manager.getLogger("");

        manager.addLogger(fooGrandChild);
        assertEquals(realRoot, fooGrandChild.getParent());

        manager.addLogger(root);
        assertSame(root, fooGrandChild.getParent());
        assertSame(realRoot, root.getParent());

        manager.addLogger(foo);
        assertSame(root, foo.getParent());
        assertSame(foo, fooGrandChild.getParent());

        manager.addLogger(fooGrandChild2);
        assertSame(foo, fooGrandChild2.getParent());
        assertSame(foo, fooGrandChild.getParent());

        manager.addLogger(fooChild);
        assertSame(fooChild, fooGrandChild2.getParent());
        assertSame(fooChild, fooGrandChild.getParent());
        assertSame(foo, fooChild.getParent());
        assertSame(root, foo.getParent());
        assertSame(realRoot, root.getParent());
    }

    public void testAddSimiliarLogger() {
        Logger root = new MockLogger("testAddSimiliarLogger", null);
        Logger foo = new MockLogger("testAddSimiliarLogger.foo", null);
        Logger similiarFoo = new MockLogger("testAddSimiliarLogger.fop", null);
        Logger fooo = new MockLogger("testAddSimiliarLogger.fooo", null);
        Logger fooChild = new MockLogger("testAddSimiliarLogger.foo.child",
                null);
        Logger similiarFooChild = new MockLogger(
                "testAddSimiliarLogger.fop.child", null);
        Logger foooChild = new MockLogger("testAddSimiliarLogger.fooo.child",
                null);

        manager.addLogger(root);
        manager.addLogger(fooChild);
        manager.addLogger(similiarFooChild);
        manager.addLogger(foooChild);
        assertSame(root, fooChild.getParent());
        assertSame(root, similiarFooChild.getParent());
        assertSame(root, foooChild.getParent());

        manager.addLogger(foo);
        assertSame(foo, fooChild.getParent());
        assertSame(root, similiarFooChild.getParent());
        assertSame(root, foooChild.getParent());

        manager.addLogger(similiarFoo);
        assertSame(foo, fooChild.getParent());
        assertSame(similiarFoo, similiarFooChild.getParent());
        assertSame(root, foooChild.getParent());

        manager.addLogger(fooo);
        assertSame(fooo, foooChild.getParent());
    }

    public void testAddGetLogger_nameWithSpace() {
        Logger foo = new MockLogger(FOO, null);
        Logger fooBeforeSpace = new MockLogger(FOO + " ", null);
        Logger fooAfterSpace = new MockLogger(" " + FOO, null);
        Logger fooWithBothSpace = new MockLogger(" " + FOO + " ", null);
        assertTrue(mockManager.addLogger(foo));
        assertTrue(mockManager.addLogger(fooBeforeSpace));
        assertTrue(mockManager.addLogger(fooAfterSpace));
        assertTrue(mockManager.addLogger(fooWithBothSpace));

        assertSame(foo, mockManager.getLogger(FOO));
        assertSame(fooBeforeSpace, mockManager.getLogger(FOO + " "));
        assertSame(fooAfterSpace, mockManager.getLogger(" " + FOO));
        assertSame(fooWithBothSpace, mockManager.getLogger(" " + FOO + " "));
    }

    public void testAddGetLogger_addRoot() throws IOException {
        Logger foo = new MockLogger(FOO, null);
        Logger fooChild = new MockLogger(FOO + ".child", null);
        Logger other = new MockLogger("other", null);
        Logger root = new MockLogger("", null);
        assertNull(foo.getParent());
        assertNull(root.getParent());
        assertNull(other.getParent());

        // add root to mock logmanager and it works as "root" logger
        assertTrue(mockManager.addLogger(foo));
        assertTrue(mockManager.addLogger(other));
        assertTrue(mockManager.addLogger(fooChild));
        assertNull(foo.getParent());
        assertNull(other.getParent());
        assertSame(foo, fooChild.getParent());

        assertTrue(mockManager.addLogger(root));
        assertSame(root, foo.getParent());
        assertSame(root, other.getParent());
        assertNull(root.getParent());

        // try to add root logger to non-mock LogManager, no effect
        assertFalse(manager.addLogger(root));
        assertNotSame(root, manager.getLogger(""));
    }

    public void testDefaultLoggerProperties() throws Exception {
        // mock LogManager has no default logger
        assertNull(mockManager.getLogger(""));
        assertNull(mockManager.getLogger("global"));

        // non-mock LogManager has two default logger
        Logger global = manager.getLogger("global");
        Logger root = manager.getLogger("");

        assertSame(global, Logger.global);
        assertSame(root, global.getParent());

        // root properties
        manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertNull(root.getFilter());
        assertEquals(2, root.getHandlers().length);
        assertEquals(Level.FINE, root.getLevel());
        assertEquals("", root.getName());
        assertSame(root.getParent(), null);
        assertNull(root.getResourceBundle());
        assertNull(root.getResourceBundleName());
        assertTrue(root.getUseParentHandlers());

    }

    public void testMockGetProperty() throws Exception {
        // mock manager doesn't read configuration until you call
        // readConfiguration()
        Logger root = new MockLogger("", null);
        assertTrue(mockManager.addLogger(root));
        root = mockManager.getLogger("");
        checkPropertyNull(mockManager);
        assertEquals(0, root.getHandlers().length);
        assertNull(root.getLevel());
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertEquals(Level.FINE, root.getLevel());
        checkProperty(mockManager);
        mockManager.reset();
        checkPropertyNull(mockManager);
        assertEquals(Level.INFO, root.getLevel());
        assertEquals(0, mockManager.getLogger("").getHandlers().length);
    }

    public void testGetProperty() throws SecurityException, IOException {
//      //FIXME: move it to exec
        //        manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
//		Logger root = manager.getLogger("");
////		checkProperty(manager);
//		assertEquals(Level.FINE, root.getLevel());
//		assertEquals(2, root.getHandlers().length);

        // but non-mock manager DO read it from the very beginning
        Logger root = manager.getLogger("");
        manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        checkProperty(manager);
        assertEquals(2, root.getHandlers().length);
        assertEquals(Level.FINE, root.getLevel());

        manager.reset();
        checkPropertyNull(manager);
        assertEquals(0, root.getHandlers().length);
        assertEquals(Level.INFO, root.getLevel());
        manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
    }

    public void testReadConfiguration_null() throws SecurityException,
            IOException {
        try {
            manager.readConfiguration(null);
            fail("should throw null pointer exception");
        } catch (NullPointerException e) {
        }

    }

    public void testReadConfiguration() throws SecurityException,
            IOException {

        MockConfigLogManager lm = new MockConfigLogManager();
        assertFalse(lm.isCalled);

        lm.readConfiguration();
        assertTrue(lm.isCalled);
    }

    private static void checkPropertyNull(LogManager m) {
        // assertNull(m.getProperty(".level"));
        assertNull(m.getProperty("java.util.logging.FileHandler.limit"));
        assertNull(m.getProperty("java.util.logging.ConsoleHandler.formatter"));
        // assertNull(m.getProperty("handlers"));
        assertNull(m.getProperty("java.util.logging.FileHandler.count"));
        assertNull(m.getProperty("com.xyz.foo.level"));
        assertNull(m.getProperty("java.util.logging.FileHandler.formatter"));
        assertNull(m.getProperty("java.util.logging.ConsoleHandler.level"));
        assertNull(m.getProperty("java.util.logging.FileHandler.pattern"));
    }

    private static void checkProperty(LogManager m) {
        // assertEquals(m.getProperty(".level"), "INFO");
        assertEquals(m.getProperty("java.util.logging.FileHandler.limit"),
                "50000");
        assertEquals(m
                .getProperty("java.util.logging.ConsoleHandler.formatter"),
                "java.util.logging.SimpleFormatter");
        // assertEquals(m.getProperty("handlers"),
        // "java.util.logging.ConsoleHandler");
        assertEquals(m.getProperty("java.util.logging.FileHandler.count"), "5");
        assertEquals(m.getProperty("LogManagerTestFoo.level"), "WARNING");
        assertEquals(m.getProperty("java.util.logging.FileHandler.formatter"),
                "java.util.logging.XMLFormatter");
        assertEquals(m.getProperty("java.util.logging.ConsoleHandler.level"),
                "OFF");
        assertEquals(m.getProperty("java.util.logging.FileHandler.pattern"),
                "%h/java%u.log");
    }

//	public void testReadConfiguration() throws SecurityException, IOException {
//          FIXME: move the support_exec
//			Logger foo = new MockLogger("foo", null);
//			assertNull(foo.getLevel());
//			assertTrue(mockManager.addLogger(foo));
//
//			Logger fo = new MockLogger("foo2", null);
//			fo.setLevel(Level.ALL);
//			assertTrue(mockManager.addLogger(fo));
//
//			Handler h = new ConsoleHandler();
//			Level l = h.getLevel();
//			assertNotSame(Level.OFF, h.getLevel());
//
//			// read configuration
//			mockManager.readConfiguration();
//			// level DO has effect
//			assertEquals(Level.WARNING, foo.getLevel());
//			// for non specified logger, level is reset to null
//			assertNull(fo.getLevel());
//
//			// read properties don't affect handler
//			assertNotSame(Level.OFF, h.getLevel());
//			assertSame(l, h.getLevel());
//
//	}

    /*
      * Class under test for void readConfiguration(InputStream)
      */
    public void testReadConfigurationInputStream() throws IOException {
        // mock LogManager
        InputStream stream = EnvironmentHelper.PropertiesToInputStream(props);

        Logger foo = new MockLogger(FOO, null);
        assertNull(foo.getLevel());
        assertTrue(mockManager.addLogger(foo));

        Logger fo = new MockLogger("LogManagerTestFoo2", null);
        fo.setLevel(Level.ALL);
        assertTrue(mockManager.addLogger(fo));

        Handler h = new ConsoleHandler();
        Level l = h.getLevel();
        assertNotSame(Level.OFF, h.getLevel());

        // read configuration from stream
        mockManager.readConfiguration(stream);
        stream.close();

        // level DO has effect
        assertEquals(Level.WARNING, foo.getLevel());

        // for non specified logger, level is reset to null
        assertNull(fo.getLevel());

        // read properties don't affect handler
        assertNotSame(Level.OFF, h.getLevel());
        assertSame(l, h.getLevel());
    }

    public void testReadConfigurationInputStream_null()
            throws SecurityException, IOException {
        try {
            mockManager.readConfiguration(null);
            fail("should throw null pointer exception");
        } catch (NullPointerException e) {
        }

    }

    public void testReadConfigurationInputStream_root() throws IOException {
        InputStream stream = EnvironmentHelper.PropertiesToInputStream(props);
        manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));

        Logger logger = new MockLogger(
                "testReadConfigurationInputStream_root.foo", null);
        Logger root = manager.getLogger("");
        Logger logger2 = Logger
                .getLogger("testReadConfigurationInputStream_root.foo2");

        manager.addLogger(logger);
        assertNull(logger.getLevel());
        assertEquals(0, logger.getHandlers().length);
        assertSame(root, logger.getParent());

        assertNull(logger2.getLevel());
        assertEquals(0, logger2.getHandlers().length);
        assertSame(root, logger2.getParent());
        // if (!hasConfigClass) {
        assertEquals(Level.FINE, root.getLevel());
        assertEquals(2, root.getHandlers().length);
        // }

        // after read stream
        manager.readConfiguration(stream);
        assertEquals(Level.FINE, root.getLevel());
        assertEquals(2, root.getHandlers().length);
        assertNull(logger.getLevel());
        assertEquals(0, logger.getHandlers().length);
        stream.close();
    }

    public void testReadConfigurationUpdatesRootLoggersHandlers()
            throws IOException {
        Properties properties = new Properties();
        LogManager.getLogManager().readConfiguration(
                EnvironmentHelper.PropertiesToInputStream(properties));

        Logger root = Logger.getLogger("");
        assertEquals(0, root.getHandlers().length);

        properties.put("handlers", "java.util.logging.ConsoleHandler");
        LogManager.getLogManager().readConfiguration(
                EnvironmentHelper.PropertiesToInputStream(properties));

        assertEquals(1, root.getHandlers().length);
    }

    public void testReadConfigurationDoesNotUpdateOtherLoggers()
            throws IOException {
        Properties properties = new Properties();
        LogManager.getLogManager().readConfiguration(
                EnvironmentHelper.PropertiesToInputStream(properties));

        Logger logger = Logger.getLogger("testReadConfigurationDoesNotUpdateOtherLoggers");
        assertEquals(0, logger.getHandlers().length);

        properties.put("testReadConfigurationDoesNotUpdateOtherLoggers.handlers",
                "java.util.logging.ConsoleHandler");
        LogManager.getLogManager().readConfiguration(
                EnvironmentHelper.PropertiesToInputStream(properties));

        assertEquals(0, logger.getHandlers().length);
    }

    public void testAddRemovePropertyChangeListener() throws Exception {
        MockPropertyChangeListener listener1 = new MockPropertyChangeListener();
        MockPropertyChangeListener listener2 = new MockPropertyChangeListener();
        // add same listener1 two times
        mockManager.addPropertyChangeListener(listener1);
        mockManager.addPropertyChangeListener(listener1);
        mockManager.addPropertyChangeListener(listener2);

        assertNull(listener1.getEvent());
        assertNull(listener2.getEvent());
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        // if (!hasConfigClass) {
        assertNotNull(listener1.getEvent());
        assertNotNull(listener2.getEvent());
        // }

        listener1.reset();
        listener2.reset();

        // remove listener1, no effect
        mockManager.removePropertyChangeListener(listener1);
        mockManager.readConfiguration(EnvironmentHelper
                .PropertiesToInputStream(props));
        assertNotNull(listener1.getEvent());
        assertNotNull(listener2.getEvent());
        listener1.reset();
        listener2.reset();

        // remove listener1 again and it works
        mockManager.removePropertyChangeListener(listener1);
        mockManager.readConfiguration(EnvironmentHelper
                .PropertiesToInputStream(props));
        assertNull(listener1.getEvent());
        assertNotNull(listener2.getEvent());
        listener2.reset();

        // reset don't produce event
        mockManager.reset();
        assertNull(listener2.getEvent());

        mockManager.removePropertyChangeListener(listener2);
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertNull(listener1.getEvent());
        assertNull(listener2.getEvent());
    }

    public void testAddRemovePropertyChangeListener_null() {
        // seems nothing happened
        try {
            mockManager.addPropertyChangeListener(null);
            fail("Should throw NPE");
        } catch (NullPointerException e) {
        }
        mockManager.removePropertyChangeListener(null);
    }

    public void testLoggerLevelInitialized_explicit() throws SecurityException, IOException {
        // mock LogManager
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertNotNull(mockManager.getProperty("handlers"));

        // Before the Android O (and before the openJdk8) the logger level
        // value was  unconditionally overwritten by a value taken from properties.
        // Starting from Android O, the value is only set from properties if it wasn't
        // initialized before.
        Logger foo = new MockLogger(FOO, null);
        assertNull(foo.getLevel());
        assertEquals(0, foo.getHandlers().length);
        // Explicit set before the .addLogger
        foo.setLevel(Level.ALL);
        foo.addHandler(new ConsoleHandler());
        assertTrue(mockManager.addLogger(foo));
        assertEquals(Level.ALL, foo.getLevel());
    }

    public void testLoggerLevelInitialized() throws SecurityException, IOException {
        // mock LogManager
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertNotNull(mockManager.getProperty("handlers"));

        // Before the Android O (and before the openJdk8) the logger level
        // value was  unconditionally overwritten by a value taken from properties.
        // Starting from Android O, the value is only set from properties if it wasn't
        // initialized before.
        Logger foo = new MockLogger(FOO, null);
        assertNull(foo.getLevel());
        assertEquals(0, foo.getHandlers().length);
        foo.addHandler(new ConsoleHandler());
        assertTrue(mockManager.addLogger(foo));
        assertEquals(Level.WARNING, foo.getLevel());
    }

    public void testReset() throws SecurityException, IOException {
        // mock LogManager
        mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props));
        assertNotNull(mockManager.getProperty("handlers"));
        Logger foo = new MockLogger(FOO, null);
        assertNull(foo.getLevel());
        assertEquals(0, foo.getHandlers().length);
        foo.addHandler(new ConsoleHandler());
        assertTrue(mockManager.addLogger(foo));
        assertEquals(Level.WARNING, foo.getLevel());
        assertEquals(2, foo.getHandlers().length);

        // reset
        mockManager.reset();

        // properties is cleared
        assertNull(mockManager.getProperty("handlers"));

        // level is null
        assertNull(foo.getLevel());
        // handlers are all closed
        assertEquals(0, foo.getHandlers().length);

        // for root logger
        manager.reset();
        assertNull(manager.getProperty("handlers"));
        Logger root = manager.getLogger("");
        // level reset to info
        assertEquals(Level.INFO, root.getLevel());
        // also close root's handler
        assertEquals(0, root.getHandlers().length);
    }

    public void testGlobalPropertyConfig() throws Exception {
        PrintStream err = System.err;
        try {
            System.setErr(new PrintStream(new NullOutputStream()));
            // before add config property, root has two handler
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(2, manager.getLogger("").getHandlers().length);

            // one valid config class
            props.setProperty("config", className + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(3, manager.getLogger("").getHandlers().length);

            // two config class take effect orderly
            props.setProperty("config", className + "$MockValidConfig "
                    + className + "$MockValidConfig2");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(2, manager.getLogger("").getHandlers().length);

            props.setProperty("config", className + "$MockValidConfig2 "
                    + className + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(3, manager.getLogger("").getHandlers().length);

            // invalid config class which throw exception, just print exception
            // and
            // message
            props.setProperty("config", className
                    + "$MockInvalidConfigException");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));

            // invalid config class without default constructor, just print
            // exception and message
            props.setProperty("config", className
                    + "$MockInvalidConfigNoDefaultConstructor");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));

            // bad config class name, just print exception and message
            props.setProperty("config", "badname");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));

            // invalid separator, nothing happened
            props.setProperty("config", className + "$MockValidConfig2;"
                    + className + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(2, manager.getLogger("").getHandlers().length);
            props.setProperty("config", className + "$MockValidConfig2;"
                    + className + "$MockValidConfig " + className
                    + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(3, manager.getLogger("").getHandlers().length);

            // duplicate config class, take effect twice
            props.setProperty("config", className + "$MockValidConfig "
                    + className + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(4, manager.getLogger("").getHandlers().length);

            // invalid config classes mixed with valid config classes, valid
            // config
            // classes take effect
            props.setProperty("config", "badname " + className
                    + "$MockValidConfig " + className
                    + "$MockInvalidConfigNoDefaultConstructor " + className
                    + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(4, manager.getLogger("").getHandlers().length);

            // global property take effect before logger specified property
            props.setProperty("config", className + "$MockValidConfig");
            manager.readConfiguration(EnvironmentHelper
                    .PropertiesToInputStream(props));
            assertEquals(Level.FINE, manager.getLogger("").getLevel());
        } finally {
            System.setErr(err);
        }

    }

    public void testValidConfigClass() throws Exception {
        String oldPropertyValue = System.getProperty(CONFIG_CLASS);
        try {
            System.setProperty(CONFIG_CLASS, this.getClass().getName()
                    + "$ConfigClass");
            assertNull(manager.getLogger("testConfigClass.foo"));

            manager.readConfiguration();
            assertNull(manager.getLogger("testConfigClass.foo"));
            Logger l = Logger.getLogger("testConfigClass.foo.child");
            assertSame(Level.FINEST, manager.getLogger("").getLevel());
            assertEquals(0, manager.getLogger("").getHandlers().length);
            assertEquals("testConfigClass.foo", l.getParent().getName());
        } finally {
            Properties systemProperties = System.getProperties();
            if (oldPropertyValue != null) {
                systemProperties.setProperty(CONFIG_CLASS, oldPropertyValue);
            } else {
                systemProperties.remove(CONFIG_CLASS);
            }
        }
    }

    public void testNotExistConfigFile() throws Exception {
        String oldPropertyValue = System.getProperty(CONFIG_FILE);
        System.setProperty(CONFIG_FILE, "not.exist.config.file");
        try {
            LogManager.getLogManager().readConfiguration();
            fail("should throw FileNotFoundException");
        } catch (FileNotFoundException e) {
            // Expected
        } finally {
            Properties systemProperties = System.getProperties();
            if (oldPropertyValue != null) {
                systemProperties.setProperty(CONFIG_FILE, oldPropertyValue);
            } else {
                systemProperties.remove(CONFIG_FILE);
            }
        }
    }

    // regression for HARMONY-3075
    public void testGetLoggingMXBean() throws Exception {
        assertNotNull(LogManager.getLoggingMXBean());
    }

    /*
      * ----------------------------------------------------
      * mock classes
      * ----------------------------------------------------
      */
    public static class ConfigClass {
        public ConfigClass() throws Exception {
            LogManager man = LogManager.getLogManager();
            Properties props = LogManagerTest.initProps();
            props.put("testConfigClass.foo.level", "OFF");
            props.put("testConfigClass.foo.handlers", "java.util.logging.ConsoleHandler");
            props.put(".level", "FINEST");
            props.remove("handlers");
            InputStream in = EnvironmentHelper.PropertiesToInputStream(props);
            man.readConfiguration(in);
        }
    }

    public static class MockInvalidInitClass {
        public MockInvalidInitClass() {
            throw new RuntimeException();
        }
    }

    public static class TestInvalidConfigFile {
        public static void main(String[] args) {
            LogManager manager = LogManager.getLogManager();
            Logger root = manager.getLogger("");
            checkPropertyNull(manager);
            assertEquals(0, root.getHandlers().length);
            assertEquals(Level.INFO, root.getLevel());

            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            checkProperty(manager);
            assertNull(root.getHandlers()[0].getLevel());
            assertEquals(1, root.getHandlers().length);
            assertEquals(Level.INFO, root.getLevel());

            manager.reset();
            checkProperty(manager);
            assertEquals(0, root.getHandlers().length);
            assertEquals(Level.INFO, root.getLevel());
            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class TestValidConfigFile {
        public static void main(String[] args) {
            LogManager manager = LogManager.getLogManager();
            Logger root = manager.getLogger("");
            checkPropertyNull(manager);
            assertEquals(2, root.getHandlers().length);
            assertEquals(root.getHandlers()[0].getLevel(), Level.OFF);
            assertEquals(Level.ALL, root.getLevel());

            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            checkPropertyNull(manager);
            assertEquals(root.getHandlers()[0].getLevel(), Level.OFF);
            assertEquals(2, root.getHandlers().length);
            assertEquals(Level.ALL, root.getLevel());

            manager.reset();
            checkPropertyNull(manager);
            assertEquals(0, root.getHandlers().length);
            assertEquals(Level.INFO, root.getLevel());
            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class TestMockLogManager {
        public static void main(String[] args) {
            LogManager manager = LogManager.getLogManager();
            assertTrue(manager instanceof MockLogManager);
        }
    }

    public static class TestValidConfigClass {
        public static void main(String[] args) {
            LogManager manager = LogManager.getLogManager();
            Logger root = manager.getLogger("");
            checkPropertyNull(manager);
            assertEquals(1, root.getHandlers().length);
            assertEquals(Level.OFF, root.getLevel());

            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            checkPropertyNull(manager);
            assertEquals(1, root.getHandlers().length);
            assertEquals(Level.OFF, root.getLevel());

            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
            checkPropertyNull(manager);
            assertEquals(1, root.getHandlers().length);
            assertEquals(Level.OFF, root.getLevel());

            manager.reset();
            checkPropertyNull(manager);
            assertEquals(0, root.getHandlers().length);
            assertEquals(Level.INFO, root.getLevel());
            try {
                manager.readConfiguration();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class MockLogger extends Logger {
        public MockLogger(String name, String rbName) {
            super(name, rbName);
        }
    }

    public static class MockLogManager extends LogManager {
    }

    public static class MockConfigLogManager extends LogManager {
        public boolean isCalled = false;

        public void readConfiguration(InputStream ins) throws IOException {
            isCalled = true;
            super.readConfiguration(ins);
        }
    }

    public static class MockHandler extends Handler {
        static int number = 0;

        public MockHandler() {
            addNumber();
            // System.out.println(this + ":start:" + number);
        }

        private synchronized void addNumber() {
            number++;
        }

        public void close() {
            minusNumber();
            // System.out.println(this + ":close:" + number);
        }

        private synchronized void minusNumber() {
            number--;
        }

        public void flush() {
            // System.out.println(this + ":flush");
        }

        public void publish(LogRecord record) {
        }

    }

    public static class MockValidInitClass {
        public MockValidInitClass() {
            Properties p = new Properties();
            p.put("handlers", className + "$MockHandler");
            p.put(".level", "OFF");
            InputStream in = null;
            try {
                in = EnvironmentHelper.PropertiesToInputStream(p);
                LogManager manager = LogManager.getLogManager();
                manager.readConfiguration(in);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static class MockValidConfig {
        public MockValidConfig() {
            handler = new MockHandler();
            LogManager manager = LogManager.getLogManager();
            Logger root = null;
            if (null != manager) {
                root = manager.getLogger("");
            } else {
                System.out.println("null manager");
            }
            if (null != root) {
                root.addHandler(handler);
                root.setLevel(Level.OFF);
            }
        }
    }

    public static class MockValidConfig2 {

        static Logger root = null;

        public MockValidConfig2() {
            root = LogManager.getLogManager().getLogger("");
            root.removeHandler(handler);
        }
    }

    public static class MockInvalidConfigException {
        public MockInvalidConfigException() {
            throw new RuntimeException("invalid config class - throw exception");
        }
    }

    public static class MockInvalidConfigNoDefaultConstructor {
        public MockInvalidConfigNoDefaultConstructor(int i) {
            throw new RuntimeException(
                    "invalid config class - no default constructor");
        }
    }

    public static class MockPropertyChangeListener implements
            PropertyChangeListener {

        PropertyChangeEvent event = null;

        public void propertyChange(PropertyChangeEvent event) {
            this.event = event;
        }

        public PropertyChangeEvent getEvent() {
            return event;
        }

        public void reset() {
            event = null;
        }

    }

    /*
     * Test config class loading
     * java -Djava.util.logging.config.class=badConfigClassName ClassLoadingTest
     */
    public static class ClassLoadingTest {
        public static void main(String[] args) {
            Thread.currentThread().setContextClassLoader(new MockErrorClassLoader());
            try {
                LogManager.getLogManager();
                fail("Should throw mock error");
            } catch (MockError e) {
            }
        }

        static class MockErrorClassLoader extends ClassLoader {
            public Class<?> loadClass(String name) {
                throw new MockError();
            }
        }

        static class MockError extends Error {
        }
    }

}