1 /*
   2  * Copyright (c) 2000, 2020, 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      * This method prevents creating two different instances of
 441      * {@code Level} with the same characteristics.
 442      * If a matching level is found in the local system that corresponds
 443      * to the deserialized object, the deserialized object is replaced
 444      * by the existing instance. Otherwise, a new instance of {@code Level}
 445      * is created and substituted to the deserialized object.
 446      * The returned {@code Level} instance will have the same {@code name},
 447      * {@code value}, and {@code resourceBundleName} as the deserialized
 448      * object, but no further guarantee is made.
 449      * @return A {@code Level} instance with equivalent characteristics.
 450      */
 451     @Serial
 452     private Object readResolve() {
 453         // Serialization magic to prevent "doppelgangers".
 454         // This is a performance optimization.
 455         Optional<Level> level = KnownLevel.matches(this);
 456         if (level.isPresent()) {
 457             return level.get();
 458         }
 459         // Woops.  Whoever sent us this object knows
 460         // about a new log level.  Add it to our list.
 461         return new Level(this.name, this.value, this.resourceBundleName);
 462     }
 463 
 464     /**
 465      * Parse a level name string into a Level.
 466      * <p>
 467      * The argument string may consist of either a level name
 468      * or an integer value.
 469      * <p>
 470      * For example:
 471      * <ul>
 472      * <li>     "SEVERE"
 473      * <li>     "1000"
 474      * </ul>
 475      *
 476      * @param  name   string to be parsed
 477      * @throws NullPointerException if the name is null
 478      * @throws IllegalArgumentException if the value is not valid.
 479      * Valid values are integers between <CODE>Integer.MIN_VALUE</CODE>
 480      * and <CODE>Integer.MAX_VALUE</CODE>, and all known level names.
 481      * Known names are the levels defined by this class (e.g., <CODE>FINE</CODE>,
 482      * <CODE>FINER</CODE>, <CODE>FINEST</CODE>), or created by this class with
 483      * appropriate package access, or new levels defined or created
 484      * by subclasses.
 485      *
 486      * @return The parsed value. Passing an integer that corresponds to a known name
 487      * (e.g., 700) will return the associated name (e.g., <CODE>CONFIG</CODE>).
 488      * Passing an integer that does not (e.g., 1) will return a new level name
 489      * initialized to that value.
 490      */
 491     public static synchronized Level parse(String name) throws IllegalArgumentException {
 492         // Check that name is not null.
 493         name.length();
 494 
 495         Optional<Level> level;
 496 
 497         // Look for a known Level with the given non-localized name.
 498         level = KnownLevel.findByName(name, KnownLevel::referent);
 499         if (level.isPresent()) {
 500             return level.get();
 501         }
 502 
 503         // Now, check if the given name is an integer.  If so,
 504         // first look for a Level with the given value and then
 505         // if necessary create one.
 506         try {
 507             int x = Integer.parseInt(name);
 508             level = KnownLevel.findByValue(x, KnownLevel::referent);
 509             if (level.isPresent()) {
 510                 return level.get();
 511             }
 512             // add new Level.
 513             Level levelObject = new Level(name, x);
 514             // There's no need to use a reachability fence here because
 515             // KnownLevel keeps a strong reference on the level when
 516             // level.getClass() == Level.class.
 517             return KnownLevel.findByValue(x, KnownLevel::referent).get();
 518         } catch (NumberFormatException ex) {
 519             // Not an integer.
 520             // Drop through.
 521         }
 522 
 523         // Finally, look for a known level with the given localized name,
 524         // in the current default locale.
 525         // This is relatively expensive, but not excessively so.
 526         level = KnownLevel.findByLocalizedLevelName(name, KnownLevel::referent);
 527         if (level .isPresent()) {
 528             return level.get();
 529         }
 530 
 531         // OK, we've tried everything and failed
 532         throw new IllegalArgumentException("Bad level \"" + name + "\"");
 533     }
 534 
 535     /**
 536      * Compare two objects for value equality.
 537      * @return true if and only if the two objects have the same level value.
 538      */
 539     @Override
 540     public boolean equals(Object ox) {
 541         try {
 542             Level lx = (Level)ox;
 543             return (lx.value == this.value);
 544         } catch (Exception ex) {
 545             return false;
 546         }
 547     }
 548 
 549     /**
 550      * Generate a hashcode.
 551      * @return a hashcode based on the level value
 552      */
 553     @Override
 554     public int hashCode() {
 555         return this.value;
 556     }
 557 
 558     // KnownLevel class maintains the global list of all known levels.
 559     // The API allows multiple custom Level instances of the same name/value
 560     // be created. This class provides convenient methods to find a level
 561     // by a given name, by a given value, or by a given localized name.
 562     //
 563     // KnownLevel wraps the following Level objects:
 564     // 1. levelObject:   standard Level object or custom Level object
 565     // 2. mirroredLevel: Level object representing the level specified in the
 566     //                   logging configuration.
 567     //
 568     // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
 569     // are non-final but the name and resource bundle name are parameters to
 570     // the Level constructor.  Use the mirroredLevel object instead of the
 571     // levelObject to prevent the logging framework to execute foreign code
 572     // implemented by untrusted Level subclass.
 573     //
 574     // Implementation Notes:
 575     // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
 576     // were final, the following KnownLevel implementation can be removed.
 577     // Future API change should take this into consideration.
 578     static final class KnownLevel extends WeakReference<Level> {
 579         private static Map<String, List<KnownLevel>> nameToLevels = new HashMap<>();
 580         private static Map<Integer, List<KnownLevel>> intToLevels = new HashMap<>();
 581         private static final ReferenceQueue<Level> QUEUE = new ReferenceQueue<>();
 582 
 583         // CUSTOM_LEVEL_CLV is used to register custom level instances with
 584         // their defining class loader, so that they are garbage collected
 585         // if and only if their class loader is no longer strongly
 586         // referenced.
 587         private static final ClassLoaderValue<List<Level>> CUSTOM_LEVEL_CLV =
 588                     new ClassLoaderValue<>();
 589 
 590         final Level mirroredLevel;   // mirror of the custom Level
 591         KnownLevel(Level l) {
 592             super(l, QUEUE);
 593             if (l.getClass() == Level.class) {
 594                 this.mirroredLevel = l;
 595             } else {
 596                 // this mirrored level object is hidden
 597                 this.mirroredLevel = new Level(l.name, l.value,
 598                         l.resourceBundleName, false);
 599             }
 600         }
 601 
 602         Optional<Level> mirrored() {
 603             return Optional.of(mirroredLevel);
 604         }
 605 
 606         Optional<Level> referent() {
 607             return Optional.ofNullable(get());
 608         }
 609 
 610         private void remove() {
 611             Optional.ofNullable(nameToLevels.get(mirroredLevel.name))
 612                     .ifPresent((x) -> x.remove(this));
 613             Optional.ofNullable(intToLevels.get(mirroredLevel.value))
 614                     .ifPresent((x) -> x.remove(this));
 615         }
 616 
 617         // Remove all stale KnownLevel instances
 618         static synchronized void purge() {
 619             Reference<? extends Level> ref;
 620             while ((ref = QUEUE.poll()) != null) {
 621                 if (ref instanceof KnownLevel) {
 622                     ((KnownLevel)ref).remove();
 623                 }
 624             }
 625         }
 626 
 627         private static void registerWithClassLoader(Level customLevel) {
 628             PrivilegedAction<ClassLoader> pa = customLevel.getClass()::getClassLoader;
 629             final ClassLoader cl = AccessController.doPrivileged(pa);
 630             CUSTOM_LEVEL_CLV.computeIfAbsent(cl, (c, v) -> new ArrayList<>())
 631                 .add(customLevel);
 632         }
 633 
 634         static synchronized void add(Level l) {
 635             purge();
 636             // the mirroredLevel object is always added to the list
 637             // before the custom Level instance
 638             KnownLevel o = new KnownLevel(l);
 639             nameToLevels.computeIfAbsent(l.name, (k) -> new ArrayList<>())
 640                 .add(o);
 641             intToLevels.computeIfAbsent(l.value, (k) -> new ArrayList<>())
 642                 .add(o);
 643 
 644             // keep the custom level reachable from its class loader
 645             // This will ensure that custom level values are not GC'ed
 646             // until there class loader is GC'ed.
 647             if (o.mirroredLevel != l) {
 648                 registerWithClassLoader(l);
 649             }
 650 
 651         }
 652 
 653         // Returns a KnownLevel with the given non-localized name.
 654         static synchronized Optional<Level> findByName(String name,
 655                 Function<KnownLevel, Optional<Level>> selector) {
 656             purge();
 657             return nameToLevels.getOrDefault(name, Collections.emptyList())
 658                         .stream()
 659                         .map(selector)
 660                         .flatMap(Optional::stream)
 661                         .findFirst();
 662         }
 663 
 664         // Returns a KnownLevel with the given value.
 665         static synchronized Optional<Level> findByValue(int value,
 666                 Function<KnownLevel, Optional<Level>> selector) {
 667             purge();
 668             return intToLevels.getOrDefault(value, Collections.emptyList())
 669                         .stream()
 670                         .map(selector)
 671                         .flatMap(Optional::stream)
 672                         .findFirst();
 673         }
 674 
 675         // Returns a KnownLevel with the given localized name matching
 676         // by calling the Level.getLocalizedLevelName() method (i.e. found
 677         // from the resourceBundle associated with the Level object).
 678         // This method does not call Level.getLocalizedName() that may
 679         // be overridden in a subclass implementation
 680         static synchronized Optional<Level> findByLocalizedLevelName(String name,
 681                 Function<KnownLevel, Optional<Level>> selector) {
 682             purge();
 683             return nameToLevels.values().stream()
 684                          .flatMap(List::stream)
 685                          .map(selector)
 686                          .flatMap(Optional::stream)
 687                          .filter(l -> name.equals(l.getLocalizedLevelName()))
 688                          .findFirst();
 689         }
 690 
 691         static synchronized Optional<Level> matches(Level l) {
 692             purge();
 693             List<KnownLevel> list = nameToLevels.get(l.name);
 694             if (list != null) {
 695                 for (KnownLevel ref : list) {
 696                     Level levelObject = ref.get();
 697                     if (levelObject == null) continue;
 698                     Level other = ref.mirroredLevel;
 699                     Class<? extends Level> type = levelObject.getClass();
 700                     if (l.value == other.value &&
 701                            (l.resourceBundleName == other.resourceBundleName ||
 702                                (l.resourceBundleName != null &&
 703                                 l.resourceBundleName.equals(other.resourceBundleName)))) {
 704                         if (type == l.getClass()) {
 705                             return Optional.of(levelObject);
 706                         }
 707                     }
 708                 }
 709             }
 710             return Optional.empty();
 711         }
 712     }
 713 
 714 }