Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.logging/share/classes/java/util/logging/Level.java
41159 views
1
/*
2
* Copyright (c) 2000, 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. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.util.logging;
27
28
import java.io.Serial;
29
import java.lang.ref.Reference;
30
import java.lang.ref.ReferenceQueue;
31
import java.lang.ref.WeakReference;
32
import java.security.AccessController;
33
import java.security.PrivilegedAction;
34
import java.util.ArrayList;
35
import java.util.Collections;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Locale;
39
import java.util.Map;
40
import java.util.Optional;
41
import java.util.ResourceBundle;
42
import java.util.function.Function;
43
import jdk.internal.loader.ClassLoaderValue;
44
import jdk.internal.access.JavaUtilResourceBundleAccess;
45
import jdk.internal.access.SharedSecrets;
46
47
/**
48
* The Level class defines a set of standard logging levels that
49
* can be used to control logging output. The logging Level objects
50
* are ordered and are specified by ordered integers. Enabling logging
51
* at a given level also enables logging at all higher levels.
52
* <p>
53
* Clients should normally use the predefined Level constants such
54
* as Level.SEVERE.
55
* <p>
56
* The levels in descending order are:
57
* <ul>
58
* <li>SEVERE (highest value)
59
* <li>WARNING
60
* <li>INFO
61
* <li>CONFIG
62
* <li>FINE
63
* <li>FINER
64
* <li>FINEST (lowest value)
65
* </ul>
66
* In addition there is a level OFF that can be used to turn
67
* off logging, and a level ALL that can be used to enable
68
* logging of all messages.
69
* <p>
70
* It is possible for third parties to define additional logging
71
* levels by subclassing Level. In such cases subclasses should
72
* take care to chose unique integer level values and to ensure that
73
* they maintain the Object uniqueness property across serialization
74
* by defining a suitable readResolve method.
75
*
76
* @since 1.4
77
*/
78
79
public class Level implements java.io.Serializable {
80
private static final String defaultBundle =
81
"sun.util.logging.resources.logging";
82
83
// Calling SharedSecrets.getJavaUtilResourceBundleAccess()
84
// forces the initialization of ResourceBundle.class, which
85
// can be too early if the VM has not finished booting yet.
86
private static final class RbAccess {
87
static final JavaUtilResourceBundleAccess RB_ACCESS =
88
SharedSecrets.getJavaUtilResourceBundleAccess();
89
}
90
91
/**
92
* @serial The non-localized name of the level.
93
*/
94
private final String name;
95
96
/**
97
* @serial The integer value of the level.
98
*/
99
private final int value;
100
101
/**
102
* @serial The resource bundle name to be used in localizing the level name.
103
*/
104
private final String resourceBundleName;
105
106
// localized level name
107
private transient String localizedLevelName;
108
private transient Locale cachedLocale;
109
110
/**
111
* OFF is a special level that can be used to turn off logging.
112
* This level is initialized to <CODE>Integer.MAX_VALUE</CODE>.
113
*/
114
public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle);
115
116
/**
117
* SEVERE is a message level indicating a serious failure.
118
* <p>
119
* In general SEVERE messages should describe events that are
120
* of considerable importance and which will prevent normal
121
* program execution. They should be reasonably intelligible
122
* to end users and to system administrators.
123
* This level is initialized to <CODE>1000</CODE>.
124
*/
125
public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle);
126
127
/**
128
* WARNING is a message level indicating a potential problem.
129
* <p>
130
* In general WARNING messages should describe events that will
131
* be of interest to end users or system managers, or which
132
* indicate potential problems.
133
* This level is initialized to <CODE>900</CODE>.
134
*/
135
public static final Level WARNING = new Level("WARNING", 900, defaultBundle);
136
137
/**
138
* INFO is a message level for informational messages.
139
* <p>
140
* Typically INFO messages will be written to the console
141
* or its equivalent. So the INFO level should only be
142
* used for reasonably significant messages that will
143
* make sense to end users and system administrators.
144
* This level is initialized to <CODE>800</CODE>.
145
*/
146
public static final Level INFO = new Level("INFO", 800, defaultBundle);
147
148
/**
149
* CONFIG is a message level for static configuration messages.
150
* <p>
151
* CONFIG messages are intended to provide a variety of static
152
* configuration information, to assist in debugging problems
153
* that may be associated with particular configurations.
154
* For example, CONFIG message might include the CPU type,
155
* the graphics depth, the GUI look-and-feel, etc.
156
* This level is initialized to <CODE>700</CODE>.
157
*/
158
public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle);
159
160
/**
161
* FINE is a message level providing tracing information.
162
* <p>
163
* All of FINE, FINER, and FINEST are intended for relatively
164
* detailed tracing. The exact meaning of the three levels will
165
* vary between subsystems, but in general, FINEST should be used
166
* for the most voluminous detailed output, FINER for somewhat
167
* less detailed output, and FINE for the lowest volume (and
168
* most important) messages.
169
* <p>
170
* In general the FINE level should be used for information
171
* that will be broadly interesting to developers who do not have
172
* a specialized interest in the specific subsystem.
173
* <p>
174
* FINE messages might include things like minor (recoverable)
175
* failures. Issues indicating potential performance problems
176
* are also worth logging as FINE.
177
* This level is initialized to <CODE>500</CODE>.
178
*/
179
public static final Level FINE = new Level("FINE", 500, defaultBundle);
180
181
/**
182
* FINER indicates a fairly detailed tracing message.
183
* By default logging calls for entering, returning, or throwing
184
* an exception are traced at this level.
185
* This level is initialized to <CODE>400</CODE>.
186
*/
187
public static final Level FINER = new Level("FINER", 400, defaultBundle);
188
189
/**
190
* FINEST indicates a highly detailed tracing message.
191
* This level is initialized to <CODE>300</CODE>.
192
*/
193
public static final Level FINEST = new Level("FINEST", 300, defaultBundle);
194
195
/**
196
* ALL indicates that all messages should be logged.
197
* This level is initialized to <CODE>Integer.MIN_VALUE</CODE>.
198
*/
199
public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle);
200
201
private static final Level[] standardLevels = {
202
OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL
203
};
204
205
/**
206
* Create a named Level with a given integer value.
207
* <p>
208
* Note that this constructor is "protected" to allow subclassing.
209
* In general clients of logging should use one of the constant Level
210
* objects such as SEVERE or FINEST. However, if clients need to
211
* add new logging levels, they may subclass Level and define new
212
* constants.
213
* @param name the name of the Level, for example "SEVERE".
214
* @param value an integer value for the level.
215
* @throws NullPointerException if the name is null
216
*/
217
protected Level(String name, int value) {
218
this(name, value, null);
219
}
220
221
/**
222
* Create a named Level with a given integer value and a
223
* given localization resource name.
224
*
225
* @param name the name of the Level, for example "SEVERE".
226
* @param value an integer value for the level.
227
* @param resourceBundleName name of a resource bundle to use in
228
* localizing the given name. If the resourceBundleName is null
229
* or an empty string, it is ignored.
230
* @throws NullPointerException if the name is null
231
*/
232
protected Level(String name, int value, String resourceBundleName) {
233
this(name, value, resourceBundleName, true);
234
}
235
236
// private constructor to specify whether this instance should be added
237
// to the KnownLevel list from which Level.parse method does its look up
238
private Level(String name, int value, String resourceBundleName, boolean visible) {
239
if (name == null) {
240
throw new NullPointerException();
241
}
242
this.name = name;
243
this.value = value;
244
this.resourceBundleName = resourceBundleName;
245
this.localizedLevelName = resourceBundleName == null ? name : null;
246
this.cachedLocale = null;
247
if (visible) {
248
KnownLevel.add(this);
249
}
250
}
251
252
/**
253
* Return the level's localization resource bundle name, or
254
* null if no localization bundle is defined.
255
*
256
* @return localization resource bundle name
257
*/
258
public String getResourceBundleName() {
259
return resourceBundleName;
260
}
261
262
/**
263
* Return the non-localized string name of the Level.
264
*
265
* @return non-localized name
266
*/
267
public String getName() {
268
return name;
269
}
270
271
/**
272
* Return the localized string name of the Level, for
273
* the current default locale.
274
* <p>
275
* If no localization information is available, the
276
* non-localized name is returned.
277
*
278
* @return localized name
279
*/
280
public String getLocalizedName() {
281
return getLocalizedLevelName();
282
}
283
284
// package-private getLevelName() is used by the implementation
285
// instead of getName() to avoid calling the subclass's version
286
final String getLevelName() {
287
return this.name;
288
}
289
290
private String computeLocalizedLevelName(Locale newLocale) {
291
// Resource bundle should be loaded from the defining module
292
// or its defining class loader, if it's unnamed module,
293
// of this Level instance that can be a custom Level subclass;
294
Module module = this.getClass().getModule();
295
ResourceBundle rb = RbAccess.RB_ACCESS.getBundle(resourceBundleName,
296
newLocale, module);
297
298
final String localizedName = rb.getString(name);
299
final boolean isDefaultBundle = defaultBundle.equals(resourceBundleName);
300
if (!isDefaultBundle) return localizedName;
301
302
// This is a trick to determine whether the name has been translated
303
// or not. If it has not been translated, we need to use Locale.ROOT
304
// when calling toUpperCase().
305
final Locale rbLocale = rb.getLocale();
306
final Locale locale =
307
Locale.ROOT.equals(rbLocale)
308
|| name.equals(localizedName.toUpperCase(Locale.ROOT))
309
? Locale.ROOT : rbLocale;
310
311
// ALL CAPS in a resource bundle's message indicates no translation
312
// needed per Oracle translation guideline. To workaround this
313
// in Oracle JDK implementation, convert the localized level name
314
// to uppercase for compatibility reason.
315
return Locale.ROOT.equals(locale) ? name : localizedName.toUpperCase(locale);
316
}
317
318
// Avoid looking up the localizedLevelName twice if we already
319
// have it.
320
final String getCachedLocalizedLevelName() {
321
322
if (localizedLevelName != null) {
323
if (cachedLocale != null) {
324
if (cachedLocale.equals(Locale.getDefault())) {
325
// OK: our cached value was looked up with the same
326
// locale. We can use it.
327
return localizedLevelName;
328
}
329
}
330
}
331
332
if (resourceBundleName == null) {
333
// No resource bundle: just use the name.
334
return name;
335
}
336
337
// We need to compute the localized name.
338
// Either because it's the first time, or because our cached
339
// value is for a different locale. Just return null.
340
return null;
341
}
342
343
final synchronized String getLocalizedLevelName() {
344
345
// See if we have a cached localized name
346
final String cachedLocalizedName = getCachedLocalizedLevelName();
347
if (cachedLocalizedName != null) {
348
return cachedLocalizedName;
349
}
350
351
// No cached localized name or cache invalid.
352
// Need to compute the localized name.
353
final Locale newLocale = Locale.getDefault();
354
try {
355
localizedLevelName = computeLocalizedLevelName(newLocale);
356
} catch (Exception ex) {
357
localizedLevelName = name;
358
}
359
cachedLocale = newLocale;
360
return localizedLevelName;
361
}
362
363
// Returns a mirrored Level object that matches the given name as
364
// specified in the Level.parse method. Returns null if not found.
365
//
366
// It returns the same Level object as the one returned by Level.parse
367
// method if the given name is a non-localized name or integer.
368
//
369
// If the name is a localized name, findLevel and parse method may
370
// return a different level value if there is a custom Level subclass
371
// that overrides Level.getLocalizedName() to return a different string
372
// than what's returned by the default implementation.
373
//
374
static Level findLevel(String name) {
375
if (name == null) {
376
throw new NullPointerException();
377
}
378
379
Optional<Level> level;
380
381
// Look for a known Level with the given non-localized name.
382
level = KnownLevel.findByName(name, KnownLevel::mirrored);
383
if (level.isPresent()) {
384
return level.get();
385
}
386
387
// Now, check if the given name is an integer. If so,
388
// first look for a Level with the given value and then
389
// if necessary create one.
390
try {
391
int x = Integer.parseInt(name);
392
level = KnownLevel.findByValue(x, KnownLevel::mirrored);
393
if (level.isPresent()) {
394
return level.get();
395
}
396
// add new Level
397
Level levelObject = new Level(name, x);
398
// There's no need to use a reachability fence here because
399
// KnownLevel keeps a strong reference on the level when
400
// level.getClass() == Level.class.
401
return KnownLevel.findByValue(x, KnownLevel::mirrored).get();
402
} catch (NumberFormatException ex) {
403
// Not an integer.
404
// Drop through.
405
}
406
407
level = KnownLevel.findByLocalizedLevelName(name,
408
KnownLevel::mirrored);
409
if (level.isPresent()) {
410
return level.get();
411
}
412
413
return null;
414
}
415
416
/**
417
* Returns a string representation of this Level.
418
*
419
* @return the non-localized name of the Level, for example "INFO".
420
*/
421
@Override
422
public final String toString() {
423
return name;
424
}
425
426
/**
427
* Get the integer value for this level. This integer value
428
* can be used for efficient ordering comparisons between
429
* Level objects.
430
* @return the integer value for this level.
431
*/
432
public final int intValue() {
433
return value;
434
}
435
436
@Serial
437
private static final long serialVersionUID = -8176160795706313070L;
438
439
/**
440
* Returns a {@code Level} instance with the same {@code name},
441
* {@code value}, and {@code resourceBundleName} as the deserialized
442
* object.
443
* @return a {@code Level} instance corresponding to the deserialized
444
* object.
445
*/
446
@Serial
447
private Object readResolve() {
448
// Serialization magic to prevent "doppelgangers".
449
// This is a performance optimization.
450
Optional<Level> level = KnownLevel.matches(this);
451
if (level.isPresent()) {
452
return level.get();
453
}
454
// Woops. Whoever sent us this object knows
455
// about a new log level. Add it to our list.
456
return new Level(this.name, this.value, this.resourceBundleName);
457
}
458
459
/**
460
* Parse a level name string into a Level.
461
* <p>
462
* The argument string may consist of either a level name
463
* or an integer value.
464
* <p>
465
* For example:
466
* <ul>
467
* <li> "SEVERE"
468
* <li> "1000"
469
* </ul>
470
*
471
* @param name string to be parsed
472
* @throws NullPointerException if the name is null
473
* @throws IllegalArgumentException if the value is not valid.
474
* Valid values are integers between <CODE>Integer.MIN_VALUE</CODE>
475
* and <CODE>Integer.MAX_VALUE</CODE>, and all known level names.
476
* Known names are the levels defined by this class (e.g., <CODE>FINE</CODE>,
477
* <CODE>FINER</CODE>, <CODE>FINEST</CODE>), or created by this class with
478
* appropriate package access, or new levels defined or created
479
* by subclasses.
480
*
481
* @return The parsed value. Passing an integer that corresponds to a known name
482
* (e.g., 700) will return the associated name (e.g., <CODE>CONFIG</CODE>).
483
* Passing an integer that does not (e.g., 1) will return a new level name
484
* initialized to that value.
485
*/
486
public static synchronized Level parse(String name) throws IllegalArgumentException {
487
// Check that name is not null.
488
name.length();
489
490
Optional<Level> level;
491
492
// Look for a known Level with the given non-localized name.
493
level = KnownLevel.findByName(name, KnownLevel::referent);
494
if (level.isPresent()) {
495
return level.get();
496
}
497
498
// Now, check if the given name is an integer. If so,
499
// first look for a Level with the given value and then
500
// if necessary create one.
501
try {
502
int x = Integer.parseInt(name);
503
level = KnownLevel.findByValue(x, KnownLevel::referent);
504
if (level.isPresent()) {
505
return level.get();
506
}
507
// add new Level.
508
Level levelObject = new Level(name, x);
509
// There's no need to use a reachability fence here because
510
// KnownLevel keeps a strong reference on the level when
511
// level.getClass() == Level.class.
512
return KnownLevel.findByValue(x, KnownLevel::referent).get();
513
} catch (NumberFormatException ex) {
514
// Not an integer.
515
// Drop through.
516
}
517
518
// Finally, look for a known level with the given localized name,
519
// in the current default locale.
520
// This is relatively expensive, but not excessively so.
521
level = KnownLevel.findByLocalizedLevelName(name, KnownLevel::referent);
522
if (level .isPresent()) {
523
return level.get();
524
}
525
526
// OK, we've tried everything and failed
527
throw new IllegalArgumentException("Bad level \"" + name + "\"");
528
}
529
530
/**
531
* Compare two objects for value equality.
532
* @return true if and only if the two objects have the same level value.
533
*/
534
@Override
535
public boolean equals(Object ox) {
536
try {
537
Level lx = (Level)ox;
538
return (lx.value == this.value);
539
} catch (Exception ex) {
540
return false;
541
}
542
}
543
544
/**
545
* Generate a hashcode.
546
* @return a hashcode based on the level value
547
*/
548
@Override
549
public int hashCode() {
550
return this.value;
551
}
552
553
// KnownLevel class maintains the global list of all known levels.
554
// The API allows multiple custom Level instances of the same name/value
555
// be created. This class provides convenient methods to find a level
556
// by a given name, by a given value, or by a given localized name.
557
//
558
// KnownLevel wraps the following Level objects:
559
// 1. levelObject: standard Level object or custom Level object
560
// 2. mirroredLevel: Level object representing the level specified in the
561
// logging configuration.
562
//
563
// Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
564
// are non-final but the name and resource bundle name are parameters to
565
// the Level constructor. Use the mirroredLevel object instead of the
566
// levelObject to prevent the logging framework to execute foreign code
567
// implemented by untrusted Level subclass.
568
//
569
// Implementation Notes:
570
// If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
571
// were final, the following KnownLevel implementation can be removed.
572
// Future API change should take this into consideration.
573
static final class KnownLevel extends WeakReference<Level> {
574
private static Map<String, List<KnownLevel>> nameToLevels = new HashMap<>();
575
private static Map<Integer, List<KnownLevel>> intToLevels = new HashMap<>();
576
private static final ReferenceQueue<Level> QUEUE = new ReferenceQueue<>();
577
578
// CUSTOM_LEVEL_CLV is used to register custom level instances with
579
// their defining class loader, so that they are garbage collected
580
// if and only if their class loader is no longer strongly
581
// referenced.
582
private static final ClassLoaderValue<List<Level>> CUSTOM_LEVEL_CLV =
583
new ClassLoaderValue<>();
584
585
final Level mirroredLevel; // mirror of the custom Level
586
KnownLevel(Level l) {
587
super(l, QUEUE);
588
if (l.getClass() == Level.class) {
589
this.mirroredLevel = l;
590
} else {
591
// this mirrored level object is hidden
592
this.mirroredLevel = new Level(l.name, l.value,
593
l.resourceBundleName, false);
594
}
595
}
596
597
Optional<Level> mirrored() {
598
return Optional.of(mirroredLevel);
599
}
600
601
Optional<Level> referent() {
602
return Optional.ofNullable(get());
603
}
604
605
private void remove() {
606
Optional.ofNullable(nameToLevels.get(mirroredLevel.name))
607
.ifPresent((x) -> x.remove(this));
608
Optional.ofNullable(intToLevels.get(mirroredLevel.value))
609
.ifPresent((x) -> x.remove(this));
610
}
611
612
// Remove all stale KnownLevel instances
613
static synchronized void purge() {
614
Reference<? extends Level> ref;
615
while ((ref = QUEUE.poll()) != null) {
616
if (ref instanceof KnownLevel) {
617
((KnownLevel)ref).remove();
618
}
619
}
620
}
621
622
private static void registerWithClassLoader(Level customLevel) {
623
PrivilegedAction<ClassLoader> pa = customLevel.getClass()::getClassLoader;
624
@SuppressWarnings("removal")
625
final ClassLoader cl = AccessController.doPrivileged(pa);
626
CUSTOM_LEVEL_CLV.computeIfAbsent(cl, (c, v) -> new ArrayList<>())
627
.add(customLevel);
628
}
629
630
static synchronized void add(Level l) {
631
purge();
632
// the mirroredLevel object is always added to the list
633
// before the custom Level instance
634
KnownLevel o = new KnownLevel(l);
635
nameToLevels.computeIfAbsent(l.name, (k) -> new ArrayList<>())
636
.add(o);
637
intToLevels.computeIfAbsent(l.value, (k) -> new ArrayList<>())
638
.add(o);
639
640
// keep the custom level reachable from its class loader
641
// This will ensure that custom level values are not GC'ed
642
// until there class loader is GC'ed.
643
if (o.mirroredLevel != l) {
644
registerWithClassLoader(l);
645
}
646
647
}
648
649
// Returns a KnownLevel with the given non-localized name.
650
static synchronized Optional<Level> findByName(String name,
651
Function<KnownLevel, Optional<Level>> selector) {
652
purge();
653
return nameToLevels.getOrDefault(name, Collections.emptyList())
654
.stream()
655
.map(selector)
656
.flatMap(Optional::stream)
657
.findFirst();
658
}
659
660
// Returns a KnownLevel with the given value.
661
static synchronized Optional<Level> findByValue(int value,
662
Function<KnownLevel, Optional<Level>> selector) {
663
purge();
664
return intToLevels.getOrDefault(value, Collections.emptyList())
665
.stream()
666
.map(selector)
667
.flatMap(Optional::stream)
668
.findFirst();
669
}
670
671
// Returns a KnownLevel with the given localized name matching
672
// by calling the Level.getLocalizedLevelName() method (i.e. found
673
// from the resourceBundle associated with the Level object).
674
// This method does not call Level.getLocalizedName() that may
675
// be overridden in a subclass implementation
676
static synchronized Optional<Level> findByLocalizedLevelName(String name,
677
Function<KnownLevel, Optional<Level>> selector) {
678
purge();
679
return nameToLevels.values().stream()
680
.flatMap(List::stream)
681
.map(selector)
682
.flatMap(Optional::stream)
683
.filter(l -> name.equals(l.getLocalizedLevelName()))
684
.findFirst();
685
}
686
687
static synchronized Optional<Level> matches(Level l) {
688
purge();
689
List<KnownLevel> list = nameToLevels.get(l.name);
690
if (list != null) {
691
for (KnownLevel ref : list) {
692
Level levelObject = ref.get();
693
if (levelObject == null) continue;
694
Level other = ref.mirroredLevel;
695
Class<? extends Level> type = levelObject.getClass();
696
if (l.value == other.value &&
697
(l.resourceBundleName == other.resourceBundleName ||
698
(l.resourceBundleName != null &&
699
l.resourceBundleName.equals(other.resourceBundleName)))) {
700
if (type == l.getClass()) {
701
return Optional.of(levelObject);
702
}
703
}
704
}
705
}
706
return Optional.empty();
707
}
708
}
709
710
}
711
712