Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/LoggerFinderLoaderTest.java
66648 views
1
/*
2
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
import java.io.ByteArrayOutputStream;
24
import java.io.IOException;
25
import java.io.PrintStream;
26
import java.io.UncheckedIOException;
27
import java.security.AccessControlException;
28
import java.security.CodeSource;
29
import java.security.Permission;
30
import java.security.PermissionCollection;
31
import java.security.Permissions;
32
import java.security.Policy;
33
import java.security.ProtectionDomain;
34
import java.util.Collections;
35
import java.util.Enumeration;
36
import java.util.HashMap;
37
import java.util.Map;
38
import java.util.ResourceBundle;
39
import java.util.stream.Collectors;
40
import java.util.stream.Stream;
41
import java.util.concurrent.ConcurrentHashMap;
42
import java.util.concurrent.atomic.AtomicBoolean;
43
import java.util.concurrent.atomic.AtomicLong;
44
import java.util.function.Supplier;
45
import java.lang.System.LoggerFinder;
46
import java.lang.System.Logger;
47
import java.lang.System.Logger.Level;
48
import java.util.EnumSet;
49
import java.util.Iterator;
50
import java.util.Locale;
51
import java.util.ServiceLoader;
52
import java.util.concurrent.atomic.AtomicReference;
53
54
/**
55
* @test
56
* @bug 8140364 8189291
57
* @summary JDK implementation specific unit test for LoggerFinderLoader.
58
* Tests the behavior of LoggerFinderLoader with respect to the
59
* value of the internal diagnosability switches. Also test the
60
* DefaultLoggerFinder and SimpleConsoleLogger implementation.
61
* @modules java.base/sun.util.logging
62
* java.base/jdk.internal.logger
63
* @build AccessSystemLogger LoggerFinderLoaderTest CustomSystemClassLoader BaseLoggerFinder BaseLoggerFinder2
64
* @run driver AccessSystemLogger
65
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader LoggerFinderLoaderTest NOSECURITY
66
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader LoggerFinderLoaderTest NOPERMISSIONS
67
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader LoggerFinderLoaderTest WITHPERMISSIONS
68
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true LoggerFinderLoaderTest NOSECURITY
69
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true LoggerFinderLoaderTest NOPERMISSIONS
70
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true LoggerFinderLoaderTest WITHPERMISSIONS
71
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest NOSECURITY
72
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest NOPERMISSIONS
73
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest WITHPERMISSIONS
74
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest NOSECURITY
75
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest NOPERMISSIONS
76
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest WITHPERMISSIONS
77
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest NOSECURITY
78
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest NOPERMISSIONS
79
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Dtest.fails=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest WITHPERMISSIONS
80
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true LoggerFinderLoaderTest NOSECURITY
81
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true LoggerFinderLoaderTest NOPERMISSIONS
82
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true LoggerFinderLoaderTest WITHPERMISSIONS
83
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest NOSECURITY
84
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest NOPERMISSIONS
85
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=ERROR LoggerFinderLoaderTest WITHPERMISSIONS
86
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest NOSECURITY
87
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest NOPERMISSIONS
88
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=DEBUG LoggerFinderLoaderTest WITHPERMISSIONS
89
* @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest NOSECURITY
90
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest NOPERMISSIONS
91
* @run main/othervm -Xbootclasspath/a:boot -Djava.security.manager=allow -Djava.system.class.loader=CustomSystemClassLoader -Djdk.logger.finder.singleton=true -Djdk.logger.finder.error=QUIET LoggerFinderLoaderTest WITHPERMISSIONS
92
* @author danielfuchs
93
*/
94
public class LoggerFinderLoaderTest {
95
96
static final Policy DEFAULT_POLICY = Policy.getPolicy();
97
static final RuntimePermission LOGGERFINDER_PERMISSION =
98
new RuntimePermission("loggerFinder");
99
final static boolean VERBOSE = false;
100
static final ThreadLocal<AtomicBoolean> allowControl = new ThreadLocal<AtomicBoolean>() {
101
@Override
102
protected AtomicBoolean initialValue() {
103
return new AtomicBoolean(false);
104
}
105
};
106
static final ThreadLocal<AtomicBoolean> allowAccess = new ThreadLocal<AtomicBoolean>() {
107
@Override
108
protected AtomicBoolean initialValue() {
109
return new AtomicBoolean(false);
110
}
111
};
112
113
final static AccessSystemLogger accessSystemLogger = new AccessSystemLogger();
114
static final Class<?>[] providerClass;
115
static {
116
try {
117
providerClass = new Class<?>[] {
118
ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder"),
119
ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder2")
120
};
121
} catch (ClassNotFoundException ex) {
122
throw new ExceptionInInitializerError(ex);
123
}
124
}
125
126
/**
127
* What our test provider needs to implement.
128
*/
129
public static interface TestLoggerFinder {
130
public final static AtomicBoolean fails = new AtomicBoolean();
131
public final static AtomicReference<String> conf = new AtomicReference<>("");
132
public final static AtomicLong sequencer = new AtomicLong();
133
public final ConcurrentHashMap<String, LoggerImpl> system = new ConcurrentHashMap<>();
134
public final ConcurrentHashMap<String, LoggerImpl> user = new ConcurrentHashMap<>();
135
136
public class LoggerImpl implements System.Logger {
137
final String name;
138
final Logger logger;
139
140
public LoggerImpl(String name, Logger logger) {
141
this.name = name;
142
this.logger = logger;
143
}
144
145
@Override
146
public String getName() {
147
return name;
148
}
149
150
@Override
151
public boolean isLoggable(Logger.Level level) {
152
return logger.isLoggable(level);
153
}
154
155
@Override
156
public void log(Logger.Level level, ResourceBundle bundle, String key, Throwable thrown) {
157
logger.log(level, bundle, key, thrown);
158
}
159
160
@Override
161
public void log(Logger.Level level, ResourceBundle bundle, String format, Object... params) {
162
logger.log(level, bundle, format, params);
163
}
164
165
}
166
167
public Logger getLogger(String name, Module caller);
168
public Logger getLocalizedLogger(String name, ResourceBundle bundle, Module caller);
169
}
170
171
public static class MyBundle extends ResourceBundle {
172
173
final ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
174
175
@Override
176
protected Object handleGetObject(String key) {
177
if (key.contains(" (translated)")) {
178
throw new RuntimeException("Unexpected key: " + key);
179
}
180
return map.computeIfAbsent(key, k -> k.toUpperCase(Locale.ROOT) + " (translated)");
181
}
182
183
@Override
184
public Enumeration<String> getKeys() {
185
return Collections.enumeration(map.keySet());
186
}
187
188
}
189
public static class MyLoggerBundle extends MyBundle {
190
191
}
192
193
static enum TestCases {NOSECURITY, NOPERMISSIONS, WITHPERMISSIONS};
194
195
static void setSecurityManager() {
196
if (System.getSecurityManager() == null) {
197
Policy.setPolicy(new SimplePolicy(allowControl, allowAccess));
198
System.setSecurityManager(new SecurityManager());
199
}
200
}
201
202
private static String withoutWarning(String in) {
203
return in.lines().filter(s -> !s.startsWith("WARNING:")).collect(Collectors.joining());
204
}
205
206
static LoggerFinder getLoggerFinder(Class<?> expectedClass,
207
String errorPolicy, boolean singleton) {
208
LoggerFinder provider = null;
209
try {
210
TestLoggerFinder.sequencer.incrementAndGet();
211
provider = LoggerFinder.getLoggerFinder();
212
if (TestLoggerFinder.fails.get() || singleton) {
213
if ("ERROR".equals(errorPolicy.toUpperCase(Locale.ROOT))) {
214
throw new RuntimeException("Expected exception not thrown");
215
} else if ("WARNING".equals(errorPolicy.toUpperCase(Locale.ROOT))) {
216
String warning = ErrorStream.errorStream.peek();
217
if (!warning.contains("WARNING: Failed to instantiate LoggerFinder provider; Using default.")) {
218
throw new RuntimeException("Expected message not found. Error stream contained: " + warning);
219
}
220
} else if ("DEBUG".equals(errorPolicy.toUpperCase(Locale.ROOT))) {
221
String warning = ErrorStream.errorStream.peek();
222
if (!warning.contains("WARNING: Failed to instantiate LoggerFinder provider; Using default.")) {
223
throw new RuntimeException("Expected message not found. Error stream contained: " + warning);
224
}
225
if (!warning.contains("WARNING: Exception raised trying to instantiate LoggerFinder")) {
226
throw new RuntimeException("Expected message not found. Error stream contained: " + warning);
227
}
228
if (TestLoggerFinder.fails.get()) {
229
if (!warning.contains("java.util.ServiceConfigurationError: java.lang.System$LoggerFinder: Provider BaseLoggerFinder could not be instantiated")) {
230
throw new RuntimeException("Expected message not found. Error stream contained: " + warning);
231
}
232
} else if (singleton) {
233
if (!warning.contains("java.util.ServiceConfigurationError: More than on LoggerFinder implementation")) {
234
throw new RuntimeException("Expected message not found. Error stream contained: " + warning);
235
}
236
}
237
} else if ("QUIET".equals(errorPolicy.toUpperCase(Locale.ROOT))) {
238
String warning = ErrorStream.errorStream.peek();
239
warning = withoutWarning(warning);
240
if (!warning.isEmpty()) {
241
throw new RuntimeException("Unexpected error message found: "
242
+ ErrorStream.errorStream.peek());
243
}
244
}
245
}
246
} catch(AccessControlException a) {
247
throw a;
248
} catch(Throwable t) {
249
if (TestLoggerFinder.fails.get() || singleton) {
250
// must check System.err
251
if ("ERROR".equals(errorPolicy.toUpperCase(Locale.ROOT))) {
252
provider = LoggerFinder.getLoggerFinder();
253
} else {
254
Throwable orig = t.getCause();
255
while (orig != null && orig.getCause() != null) orig = orig.getCause();
256
if (orig != null) orig.printStackTrace(ErrorStream.err);
257
throw new RuntimeException("Unexpected exception: " + t, t);
258
}
259
} else {
260
throw new RuntimeException("Unexpected exception: " + t, t);
261
}
262
}
263
expectedClass.cast(provider);
264
ErrorStream.errorStream.store();
265
System.out.println("*** Actual LoggerFinder class is: " + provider.getClass().getName());
266
return provider;
267
}
268
269
270
static class ErrorStream extends PrintStream {
271
272
static AtomicBoolean forward = new AtomicBoolean();
273
ByteArrayOutputStream out;
274
String saved = "";
275
public ErrorStream(ByteArrayOutputStream out) {
276
super(out);
277
this.out = out;
278
}
279
280
@Override
281
public void write(int b) {
282
super.write(b);
283
if (forward.get()) err.write(b);
284
}
285
286
@Override
287
public void write(byte[] b) throws IOException {
288
super.write(b);
289
if (forward.get()) err.write(b);
290
}
291
292
@Override
293
public void write(byte[] buf, int off, int len) {
294
super.write(buf, off, len);
295
if (forward.get()) err.write(buf, off, len);
296
}
297
298
public String peek() {
299
flush();
300
return out.toString();
301
}
302
303
public String drain() {
304
flush();
305
String res = out.toString();
306
out.reset();
307
return res;
308
}
309
310
public void store() {
311
flush();
312
saved = out.toString();
313
out.reset();
314
}
315
316
public void restore() {
317
out.reset();
318
try {
319
out.write(saved.getBytes());
320
} catch(IOException io) {
321
throw new UncheckedIOException(io);
322
}
323
}
324
325
static final PrintStream err = System.err;
326
static final ErrorStream errorStream = new ErrorStream(new ByteArrayOutputStream());
327
}
328
329
private static StringBuilder appendProperty(StringBuilder b, String name) {
330
String value = System.getProperty(name);
331
if (value == null) return b;
332
return b.append(name).append("=").append(value).append('\n');
333
}
334
335
public static void main(String[] args) {
336
if (args.length == 0) {
337
args = new String[] {
338
"NOSECURITY",
339
"NOPERMISSIONS",
340
"WITHPERMISSIONS"
341
};
342
}
343
Locale.setDefault(Locale.ENGLISH);
344
System.setErr(ErrorStream.errorStream);
345
System.setProperty("jdk.logger.packages", TestLoggerFinder.LoggerImpl.class.getName());
346
//System.setProperty("jdk.logger.finder.error", "ERROR");
347
//System.setProperty("jdk.logger.finder.singleton", "true");
348
//System.setProperty("test.fails", "true");
349
TestLoggerFinder.fails.set(Boolean.getBoolean("test.fails"));
350
StringBuilder c = new StringBuilder();
351
appendProperty(c, "jdk.logger.packages");
352
appendProperty(c, "jdk.logger.finder.error");
353
appendProperty(c, "jdk.logger.finder.singleton");
354
appendProperty(c, "test.fails");
355
TestLoggerFinder.conf.set(c.toString());
356
try {
357
test(args);
358
} finally {
359
try {
360
System.setErr(ErrorStream.err);
361
} catch (Error | RuntimeException x) {
362
x.printStackTrace(ErrorStream.err);
363
}
364
}
365
}
366
367
368
public static void test(String[] args) {
369
370
final String errorPolicy = System.getProperty("jdk.logger.finder.error", "WARNING");
371
final Boolean ensureSingleton = Boolean.getBoolean("jdk.logger.finder.singleton");
372
373
final Class<?> expectedClass =
374
TestLoggerFinder.fails.get() || ensureSingleton
375
? jdk.internal.logger.DefaultLoggerFinder.class
376
: TestLoggerFinder.class;
377
378
System.out.println("Declared provider class: " + providerClass[0]
379
+ "[" + providerClass[0].getClassLoader() + "]");
380
381
if (!TestLoggerFinder.fails.get()) {
382
ServiceLoader<LoggerFinder> serviceLoader =
383
ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader());
384
Iterator<LoggerFinder> iterator = serviceLoader.iterator();
385
Object firstProvider = iterator.next();
386
if (!firstProvider.getClass().getName().equals("BaseLoggerFinder")) {
387
throw new RuntimeException("Unexpected provider: " + firstProvider.getClass().getName());
388
}
389
if (!iterator.hasNext()) {
390
throw new RuntimeException("Expected two providers");
391
}
392
}
393
394
Stream.of(args).map(TestCases::valueOf).forEach((testCase) -> {
395
LoggerFinder provider;
396
ErrorStream.errorStream.restore();
397
switch (testCase) {
398
case NOSECURITY:
399
System.out.println("\n*** Without Security Manager\n");
400
System.out.println(TestLoggerFinder.conf.get());
401
provider = getLoggerFinder(expectedClass, errorPolicy, ensureSingleton);
402
test(provider, true);
403
System.out.println("Tetscase count: " + TestLoggerFinder.sequencer.get());
404
break;
405
case NOPERMISSIONS:
406
System.out.println("\n*** With Security Manager, without permissions\n");
407
System.out.println(TestLoggerFinder.conf.get());
408
setSecurityManager();
409
try {
410
provider = getLoggerFinder(expectedClass, errorPolicy, ensureSingleton);
411
throw new RuntimeException("Expected exception not raised");
412
} catch (AccessControlException x) {
413
if (!LOGGERFINDER_PERMISSION.equals(x.getPermission())) {
414
throw new RuntimeException("Unexpected permission check", x);
415
}
416
final boolean control = allowControl.get().get();
417
try {
418
allowControl.get().set(true);
419
provider = getLoggerFinder(expectedClass, errorPolicy, ensureSingleton);
420
} finally {
421
allowControl.get().set(control);
422
}
423
}
424
test(provider, false);
425
System.out.println("Tetscase count: " + TestLoggerFinder.sequencer.get());
426
break;
427
case WITHPERMISSIONS:
428
System.out.println("\n*** With Security Manager, with control permission\n");
429
System.out.println(TestLoggerFinder.conf.get());
430
setSecurityManager();
431
final boolean control = allowControl.get().get();
432
try {
433
allowControl.get().set(true);
434
provider = getLoggerFinder(expectedClass, errorPolicy, ensureSingleton);
435
test(provider, true);
436
} finally {
437
allowControl.get().set(control);
438
}
439
break;
440
default:
441
throw new RuntimeException("Unknown test case: " + testCase);
442
}
443
});
444
System.out.println("\nPASSED: Tested " + TestLoggerFinder.sequencer.get() + " cases.");
445
}
446
447
public static void test(LoggerFinder provider, boolean hasRequiredPermissions) {
448
449
ResourceBundle loggerBundle = ResourceBundle.getBundle(MyLoggerBundle.class.getName());
450
final Map<Logger, String> loggerDescMap = new HashMap<>();
451
452
System.Logger sysLogger = accessSystemLogger.getLogger("foo");
453
loggerDescMap.put(sysLogger, "accessSystemLogger.getLogger(\"foo\")");
454
System.Logger localizedSysLogger = accessSystemLogger.getLogger("fox", loggerBundle);
455
loggerDescMap.put(localizedSysLogger, "accessSystemLogger.getLogger(\"fox\", loggerBundle)");
456
System.Logger appLogger = System.getLogger("bar");
457
loggerDescMap.put(appLogger,"System.getLogger(\"bar\")");
458
System.Logger localizedAppLogger = System.getLogger("baz", loggerBundle);
459
loggerDescMap.put(localizedAppLogger,"System.getLogger(\"baz\", loggerBundle)");
460
461
testLogger(provider, loggerDescMap, "foo", null, sysLogger);
462
testLogger(provider, loggerDescMap, "foo", loggerBundle, localizedSysLogger);
463
testLogger(provider, loggerDescMap, "foo", null, appLogger);
464
testLogger(provider, loggerDescMap, "foo", loggerBundle, localizedAppLogger);
465
}
466
467
public static class Foo {
468
469
}
470
471
static void verbose(String msg) {
472
if (VERBOSE) {
473
System.out.println(msg);
474
}
475
}
476
477
// Calls the 8 methods defined on Logger and verify the
478
// parameters received by the underlying TestProvider.LoggerImpl
479
// logger.
480
private static void testLogger(LoggerFinder provider,
481
Map<Logger, String> loggerDescMap,
482
String name,
483
ResourceBundle loggerBundle,
484
Logger logger) {
485
486
System.out.println("Testing " + loggerDescMap.get(logger) + " [" + logger +"]");
487
AtomicLong sequencer = TestLoggerFinder.sequencer;
488
489
Foo foo = new Foo();
490
String fooMsg = foo.toString();
491
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
492
for (Level messageLevel : Level.values()) {
493
ErrorStream.errorStream.drain();
494
String desc = "logger.log(messageLevel, foo): loggerLevel="
495
+ loggerLevel+", messageLevel="+messageLevel;
496
sequencer.incrementAndGet();
497
logger.log(messageLevel, foo);
498
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
499
if (!ErrorStream.errorStream.peek().isEmpty()) {
500
throw new RuntimeException("unexpected event in queue for "
501
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
502
}
503
} else {
504
String logged = ErrorStream.errorStream.drain();
505
if (!logged.contains("LoggerFinderLoaderTest testLogger")
506
|| !logged.contains(messageLevel.getName() + ": " + fooMsg)) {
507
throw new RuntimeException("mismatch for " + desc
508
+ "\n\texpected:" + "\n<<<<\n"
509
+ "[date] LoggerFinderLoaderTest testLogger\n"
510
+ messageLevel.getName() + " " + fooMsg
511
+ "\n>>>>"
512
+ "\n\t actual:"
513
+ "\n<<<<\n" + logged + ">>>>\n");
514
} else {
515
verbose("Got expected results for "
516
+ desc + "\n<<<<\n" + logged + ">>>>\n");
517
}
518
}
519
}
520
}
521
522
String msg = "blah";
523
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
524
for (Level messageLevel : Level.values()) {
525
String desc = "logger.log(messageLevel, \"blah\"): loggerLevel="
526
+ loggerLevel+", messageLevel="+messageLevel;
527
sequencer.incrementAndGet();
528
logger.log(messageLevel, msg);
529
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
530
if (!ErrorStream.errorStream.peek().isEmpty()) {
531
throw new RuntimeException("unexpected event in queue for "
532
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
533
}
534
} else {
535
String logged = ErrorStream.errorStream.drain();
536
String msgText = loggerBundle == null ? msg : loggerBundle.getString(msg);
537
if (!logged.contains("LoggerFinderLoaderTest testLogger")
538
|| !logged.contains(messageLevel.getName() + ": " + msgText)) {
539
throw new RuntimeException("mismatch for " + desc
540
+ "\n\texpected:" + "\n<<<<\n"
541
+ "[date] LoggerFinderLoaderTest testLogger\n"
542
+ messageLevel.getName() + " " + msgText
543
+ "\n>>>>"
544
+ "\n\t actual:"
545
+ "\n<<<<\n" + logged + ">>>>\n");
546
} else {
547
verbose("Got expected results for "
548
+ desc + "\n<<<<\n" + logged + ">>>>\n");
549
}
550
}
551
}
552
}
553
554
Supplier<String> fooSupplier = new Supplier<String>() {
555
@Override
556
public String get() {
557
return this.toString();
558
}
559
};
560
561
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
562
for (Level messageLevel : Level.values()) {
563
String desc = "logger.log(messageLevel, fooSupplier): loggerLevel="
564
+ loggerLevel+", messageLevel="+messageLevel;
565
sequencer.incrementAndGet();
566
logger.log(messageLevel, fooSupplier);
567
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
568
if (!ErrorStream.errorStream.peek().isEmpty()) {
569
throw new RuntimeException("unexpected event in queue for "
570
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
571
}
572
} else {
573
String logged = ErrorStream.errorStream.drain();
574
if (!logged.contains("LoggerFinderLoaderTest testLogger")
575
|| !logged.contains(messageLevel.getName() + ": " + fooSupplier.get())) {
576
throw new RuntimeException("mismatch for " + desc
577
+ "\n\texpected:" + "\n<<<<\n"
578
+ "[date] LoggerFinderLoaderTest testLogger\n"
579
+ messageLevel.getName() + " " + fooSupplier.get()
580
+ "\n>>>>"
581
+ "\n\t actual:"
582
+ "\n<<<<\n" + logged + ">>>>\n");
583
} else {
584
verbose("Got expected results for "
585
+ desc + "\n<<<<\n" + logged + ">>>>\n");
586
}
587
}
588
}
589
}
590
591
592
String format = "two params [{1} {2}]";
593
Object arg1 = foo;
594
Object arg2 = msg;
595
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
596
for (Level messageLevel : Level.values()) {
597
String desc = "logger.log(messageLevel, format, params...): loggerLevel="
598
+ loggerLevel+", messageLevel="+messageLevel;
599
sequencer.incrementAndGet();
600
logger.log(messageLevel, format, foo, msg);
601
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
602
if (!ErrorStream.errorStream.peek().isEmpty()) {
603
throw new RuntimeException("unexpected event in queue for "
604
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
605
}
606
} else {
607
String logged = ErrorStream.errorStream.drain();
608
String msgFormat = loggerBundle == null ? format : loggerBundle.getString(format);
609
String text = java.text.MessageFormat.format(msgFormat, foo, msg);
610
if (!logged.contains("LoggerFinderLoaderTest testLogger")
611
|| !logged.contains(messageLevel.getName() + ": " + text)) {
612
throw new RuntimeException("mismatch for " + desc
613
+ "\n\texpected:" + "\n<<<<\n"
614
+ "[date] LoggerFinderLoaderTest testLogger\n"
615
+ messageLevel.getName() + " " + text
616
+ "\n>>>>"
617
+ "\n\t actual:"
618
+ "\n<<<<\n" + logged + ">>>>\n");
619
} else {
620
verbose("Got expected results for "
621
+ desc + "\n<<<<\n" + logged + ">>>>\n");
622
}
623
}
624
}
625
}
626
627
Throwable thrown = new Exception("OK: log me!");
628
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
629
for (Level messageLevel : Level.values()) {
630
String desc = "logger.log(messageLevel, \"blah\", thrown): loggerLevel="
631
+ loggerLevel+", messageLevel="+messageLevel;
632
sequencer.incrementAndGet();
633
logger.log(messageLevel, msg, thrown);
634
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
635
if (!ErrorStream.errorStream.peek().isEmpty()) {
636
throw new RuntimeException("unexpected event in queue for "
637
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
638
}
639
} else {
640
String logged = ErrorStream.errorStream.drain();
641
ByteArrayOutputStream baos = new ByteArrayOutputStream();
642
thrown.printStackTrace(new PrintStream(baos));
643
String text = baos.toString();
644
String msgText = loggerBundle == null ? msg : loggerBundle.getString(msg);
645
if (!logged.contains("LoggerFinderLoaderTest testLogger")
646
|| !logged.contains(messageLevel.getName() + ": " + msgText)
647
|| !logged.contains(text)) {
648
throw new RuntimeException("mismatch for " + desc
649
+ "\n\texpected:" + "\n<<<<\n"
650
+ "[date] LoggerFinderLoaderTest testLogger\n"
651
+ messageLevel.getName() + " " + msgText +"\n"
652
+ text
653
+ ">>>>"
654
+ "\n\t actual:"
655
+ "\n<<<<\n" + logged + ">>>>\n");
656
} else {
657
verbose("Got expected results for "
658
+ desc + "\n<<<<\n" + logged + ">>>>\n");
659
}
660
}
661
}
662
}
663
664
665
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
666
for (Level messageLevel : Level.values()) {
667
String desc = "logger.log(messageLevel, thrown, fooSupplier): loggerLevel="
668
+ loggerLevel+", messageLevel="+messageLevel;
669
sequencer.incrementAndGet();
670
logger.log(messageLevel, fooSupplier, thrown);
671
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
672
if (!ErrorStream.errorStream.peek().isEmpty()) {
673
throw new RuntimeException("unexpected event in queue for "
674
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
675
}
676
} else {
677
String logged = ErrorStream.errorStream.drain();
678
ByteArrayOutputStream baos = new ByteArrayOutputStream();
679
thrown.printStackTrace(new PrintStream(baos));
680
String text = baos.toString();
681
if (!logged.contains("LoggerFinderLoaderTest testLogger")
682
|| !logged.contains(messageLevel.getName() + ": " + fooSupplier.get())
683
|| !logged.contains(text)) {
684
throw new RuntimeException("mismatch for " + desc
685
+ "\n\texpected:" + "\n<<<<\n"
686
+ "[date] LoggerFinderLoaderTest testLogger\n"
687
+ messageLevel.getName() + " " + fooSupplier.get() +"\n"
688
+ text
689
+ ">>>>"
690
+ "\n\t actual:"
691
+ "\n<<<<\n" + logged + ">>>>\n");
692
} else {
693
verbose("Got expected results for "
694
+ desc + "\n<<<<\n" + logged + ">>>>\n");
695
}
696
}
697
}
698
}
699
700
ResourceBundle bundle = ResourceBundle.getBundle(MyBundle.class.getName());
701
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
702
for (Level messageLevel : Level.values()) {
703
String desc = "logger.log(messageLevel, bundle, format, params...): loggerLevel="
704
+ loggerLevel+", messageLevel="+messageLevel;
705
sequencer.incrementAndGet();
706
logger.log(messageLevel, bundle, format, foo, msg);
707
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
708
if (!ErrorStream.errorStream.peek().isEmpty()) {
709
throw new RuntimeException("unexpected event in queue for "
710
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
711
}
712
} else {
713
String logged = ErrorStream.errorStream.drain();
714
String text = java.text.MessageFormat.format(bundle.getString(format), foo, msg);
715
if (!logged.contains("LoggerFinderLoaderTest testLogger")
716
|| !logged.contains(messageLevel.getName() + ": " + text)) {
717
throw new RuntimeException("mismatch for " + desc
718
+ "\n\texpected:" + "\n<<<<\n"
719
+ "[date] LoggerFinderLoaderTest testLogger\n"
720
+ messageLevel.getName() + " " + text
721
+ "\n>>>>"
722
+ "\n\t actual:"
723
+ "\n<<<<\n" + logged + ">>>>\n");
724
} else {
725
verbose("Got expected results for "
726
+ desc + "\n<<<<\n" + logged + ">>>>\n");
727
}
728
}
729
}
730
}
731
732
for (Level loggerLevel : EnumSet.of(Level.INFO)) {
733
for (Level messageLevel : Level.values()) {
734
String desc = "logger.log(messageLevel, bundle, \"blah\", thrown): loggerLevel="
735
+ loggerLevel+", messageLevel="+messageLevel;
736
sequencer.incrementAndGet();
737
logger.log(messageLevel, bundle, msg, thrown);
738
if (loggerLevel == Level.OFF || messageLevel == Level.OFF || messageLevel.compareTo(loggerLevel) < 0) {
739
if (!ErrorStream.errorStream.peek().isEmpty()) {
740
throw new RuntimeException("unexpected event in queue for "
741
+ desc +": " + "\n\t" + ErrorStream.errorStream.drain());
742
}
743
} else {
744
String logged = ErrorStream.errorStream.drain();
745
String textMsg = bundle.getString(msg);
746
ByteArrayOutputStream baos = new ByteArrayOutputStream();
747
thrown.printStackTrace(new PrintStream(baos));
748
String text = baos.toString();
749
if (!logged.contains("LoggerFinderLoaderTest testLogger")
750
|| !logged.contains(messageLevel.getName() + ": " + textMsg)
751
|| !logged.contains(text)) {
752
throw new RuntimeException("mismatch for " + desc
753
+ "\n\texpected:" + "\n<<<<\n"
754
+ "[date] LoggerFinderLoaderTest testLogger\n"
755
+ messageLevel.getName() + " " + textMsg +"\n"
756
+ text
757
+ ">>>>"
758
+ "\n\t actual:"
759
+ "\n<<<<\n" + logged + ">>>>\n");
760
} else {
761
verbose("Got expected results for "
762
+ desc + "\n<<<<\n" + logged + ">>>>\n");
763
}
764
}
765
}
766
}
767
768
}
769
770
final static class PermissionsBuilder {
771
final Permissions perms;
772
public PermissionsBuilder() {
773
this(new Permissions());
774
}
775
public PermissionsBuilder(Permissions perms) {
776
this.perms = perms;
777
}
778
public PermissionsBuilder add(Permission p) {
779
perms.add(p);
780
return this;
781
}
782
public PermissionsBuilder addAll(PermissionCollection col) {
783
if (col != null) {
784
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
785
perms.add(e.nextElement());
786
}
787
}
788
return this;
789
}
790
public Permissions toPermissions() {
791
final PermissionsBuilder builder = new PermissionsBuilder();
792
builder.addAll(perms);
793
return builder.perms;
794
}
795
}
796
797
public static class SimplePolicy extends Policy {
798
final static RuntimePermission CONTROL = LOGGERFINDER_PERMISSION;
799
final static RuntimePermission ACCESS = new RuntimePermission("accessClassInPackage.jdk.internal.logger");
800
801
final Permissions permissions;
802
final ThreadLocal<AtomicBoolean> allowControl;
803
final ThreadLocal<AtomicBoolean> allowAccess;
804
public SimplePolicy(ThreadLocal<AtomicBoolean> allowControl, ThreadLocal<AtomicBoolean> allowAccess) {
805
this.allowControl = allowControl;
806
this.allowAccess = allowAccess;
807
permissions = new Permissions();
808
permissions.add(new RuntimePermission("setIO"));
809
}
810
811
Permissions getPermissions() {
812
if (allowControl.get().get() || allowAccess.get().get()) {
813
PermissionsBuilder builder = new PermissionsBuilder()
814
.addAll(permissions);
815
if (allowControl.get().get()) {
816
builder.add(CONTROL);
817
}
818
if (allowAccess.get().get()) {
819
builder.add(ACCESS);
820
}
821
return builder.toPermissions();
822
}
823
return permissions;
824
}
825
826
@Override
827
public boolean implies(ProtectionDomain domain, Permission permission) {
828
return getPermissions().implies(permission) ||
829
DEFAULT_POLICY.implies(domain, permission);
830
}
831
832
@Override
833
public PermissionCollection getPermissions(CodeSource codesource) {
834
return new PermissionsBuilder().addAll(getPermissions()).toPermissions();
835
}
836
837
@Override
838
public PermissionCollection getPermissions(ProtectionDomain domain) {
839
return new PermissionsBuilder().addAll(getPermissions()).toPermissions();
840
}
841
}
842
}
843
844