1 /*
   2  * Copyright (c) 2000, 2013, 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 import java.lang.reflect.Module;
  28 import java.util.ArrayList;

  29 import java.util.HashMap;
  30 import java.util.List;
  31 import java.util.Locale;
  32 import java.util.Map;

  33 import java.util.ResourceBundle;


  34 
  35 /**
  36  * The Level class defines a set of standard logging levels that
  37  * can be used to control logging output.  The logging Level objects
  38  * are ordered and are specified by ordered integers.  Enabling logging
  39  * at a given level also enables logging at all higher levels.
  40  * <p>
  41  * Clients should normally use the predefined Level constants such
  42  * as Level.SEVERE.
  43  * <p>
  44  * The levels in descending order are:
  45  * <ul>
  46  * <li>SEVERE (highest value)
  47  * <li>WARNING
  48  * <li>INFO
  49  * <li>CONFIG
  50  * <li>FINE
  51  * <li>FINER
  52  * <li>FINEST  (lowest value)
  53  * </ul>
  54  * In addition there is a level OFF that can be used to turn
  55  * off logging, and a level ALL that can be used to enable
  56  * logging of all messages.
  57  * <p>
  58  * It is possible for third parties to define additional logging
  59  * levels by subclassing Level.  In such cases subclasses should
  60  * take care to chose unique integer level values and to ensure that
  61  * they maintain the Object uniqueness property across serialization
  62  * by defining a suitable readResolve method.
  63  *
  64  * @since 1.4
  65  */
  66 
  67 public class Level implements java.io.Serializable {
  68     private static final String defaultBundle = "sun.util.logging.resources.logging";
  69 
  70     /**
  71      * @serial  The non-localized name of the level.
  72      */
  73     private final String name;
  74 
  75     /**
  76      * @serial  The integer value of the level.
  77      */
  78     private final int value;
  79 
  80     /**
  81      * @serial The resource bundle name to be used in localizing the level name.
  82      */
  83     private final String resourceBundleName;
  84 
  85     // localized level name
  86     private transient String localizedLevelName;
  87     private transient Locale cachedLocale;
  88 
  89     /**
  90      * OFF is a special level that can be used to turn off logging.
  91      * This level is initialized to <CODE>Integer.MAX_VALUE</CODE>.
  92      */
  93     public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle);
  94 
  95     /**
  96      * SEVERE is a message level indicating a serious failure.
  97      * <p>
  98      * In general SEVERE messages should describe events that are
  99      * of considerable importance and which will prevent normal
 100      * program execution.   They should be reasonably intelligible
 101      * to end users and to system administrators.
 102      * This level is initialized to <CODE>1000</CODE>.
 103      */
 104     public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle);
 105 
 106     /**
 107      * WARNING is a message level indicating a potential problem.
 108      * <p>
 109      * In general WARNING messages should describe events that will
 110      * be of interest to end users or system managers, or which
 111      * indicate potential problems.
 112      * This level is initialized to <CODE>900</CODE>.
 113      */
 114     public static final Level WARNING = new Level("WARNING", 900, defaultBundle);
 115 
 116     /**
 117      * INFO is a message level for informational messages.
 118      * <p>
 119      * Typically INFO messages will be written to the console
 120      * or its equivalent.  So the INFO level should only be
 121      * used for reasonably significant messages that will
 122      * make sense to end users and system administrators.
 123      * This level is initialized to <CODE>800</CODE>.
 124      */
 125     public static final Level INFO = new Level("INFO", 800, defaultBundle);
 126 
 127     /**
 128      * CONFIG is a message level for static configuration messages.
 129      * <p>
 130      * CONFIG messages are intended to provide a variety of static
 131      * configuration information, to assist in debugging problems
 132      * that may be associated with particular configurations.
 133      * For example, CONFIG message might include the CPU type,
 134      * the graphics depth, the GUI look-and-feel, etc.
 135      * This level is initialized to <CODE>700</CODE>.
 136      */
 137     public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle);
 138 
 139     /**
 140      * FINE is a message level providing tracing information.
 141      * <p>
 142      * All of FINE, FINER, and FINEST are intended for relatively
 143      * detailed tracing.  The exact meaning of the three levels will
 144      * vary between subsystems, but in general, FINEST should be used
 145      * for the most voluminous detailed output, FINER for somewhat
 146      * less detailed output, and FINE for the  lowest volume (and
 147      * most important) messages.
 148      * <p>
 149      * In general the FINE level should be used for information
 150      * that will be broadly interesting to developers who do not have
 151      * a specialized interest in the specific subsystem.
 152      * <p>
 153      * FINE messages might include things like minor (recoverable)
 154      * failures.  Issues indicating potential performance problems
 155      * are also worth logging as FINE.
 156      * This level is initialized to <CODE>500</CODE>.
 157      */
 158     public static final Level FINE = new Level("FINE", 500, defaultBundle);
 159 
 160     /**
 161      * FINER indicates a fairly detailed tracing message.
 162      * By default logging calls for entering, returning, or throwing
 163      * an exception are traced at this level.
 164      * This level is initialized to <CODE>400</CODE>.
 165      */
 166     public static final Level FINER = new Level("FINER", 400, defaultBundle);
 167 
 168     /**
 169      * FINEST indicates a highly detailed tracing message.
 170      * This level is initialized to <CODE>300</CODE>.
 171      */
 172     public static final Level FINEST = new Level("FINEST", 300, defaultBundle);
 173 
 174     /**
 175      * ALL indicates that all messages should be logged.
 176      * This level is initialized to <CODE>Integer.MIN_VALUE</CODE>.
 177      */
 178     public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle);
 179 
 180     /**
 181      * Create a named Level with a given integer value.
 182      * <p>
 183      * Note that this constructor is "protected" to allow subclassing.
 184      * In general clients of logging should use one of the constant Level
 185      * objects such as SEVERE or FINEST.  However, if clients need to
 186      * add new logging levels, they may subclass Level and define new
 187      * constants.
 188      * @param name  the name of the Level, for example "SEVERE".
 189      * @param value an integer value for the level.
 190      * @throws NullPointerException if the name is null
 191      */
 192     protected Level(String name, int value) {
 193         this(name, value, null);
 194     }
 195 
 196     /**
 197      * Create a named Level with a given integer value and a
 198      * given localization resource name.
 199      *
 200      * @param name  the name of the Level, for example "SEVERE".
 201      * @param value an integer value for the level.
 202      * @param resourceBundleName name of a resource bundle to use in
 203      *    localizing the given name. If the resourceBundleName is null
 204      *    or an empty string, it is ignored.
 205      * @throws NullPointerException if the name is null
 206      */
 207     protected Level(String name, int value, String resourceBundleName) {
 208         this(name, value, resourceBundleName, true);
 209     }
 210 
 211     // private constructor to specify whether this instance should be added
 212     // to the KnownLevel list from which Level.parse method does its look up
 213     private Level(String name, int value, String resourceBundleName, boolean visible) {
 214         if (name == null) {
 215             throw new NullPointerException();
 216         }
 217         this.name = name;
 218         this.value = value;
 219         this.resourceBundleName = resourceBundleName;
 220         this.localizedLevelName = resourceBundleName == null ? name : null;
 221         this.cachedLocale = null;
 222         if (visible) {
 223             KnownLevel.add(this);
 224         }
 225     }
 226 
 227     /**
 228      * Return the level's localization resource bundle name, or
 229      * null if no localization bundle is defined.
 230      *
 231      * @return localization resource bundle name
 232      */
 233     public String getResourceBundleName() {
 234         return resourceBundleName;
 235     }
 236 
 237     /**
 238      * Return the non-localized string name of the Level.
 239      *
 240      * @return non-localized name
 241      */
 242     public String getName() {
 243         return name;
 244     }
 245 
 246     /**
 247      * Return the localized string name of the Level, for
 248      * the current default locale.
 249      * <p>
 250      * If no localization information is available, the
 251      * non-localized name is returned.
 252      *
 253      * @return localized name
 254      */
 255     public String getLocalizedName() {
 256         return getLocalizedLevelName();
 257     }
 258 
 259     // package-private getLevelName() is used by the implementation
 260     // instead of getName() to avoid calling the subclass's version
 261     final String getLevelName() {
 262         return this.name;
 263     }
 264 
 265     private String computeLocalizedLevelName(Locale newLocale) {
 266         // Resource bundle should be loaded from the defining module
 267         // or its defining class loader, if it's unnamed module,
 268         // of this Level instance that can be a custom Level subclass;
 269         Module module = this.getClass().getModule();
 270         ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName, newLocale, module);

 271 
 272         final String localizedName = rb.getString(name);
 273         final boolean isDefaultBundle = defaultBundle.equals(resourceBundleName);
 274         if (!isDefaultBundle) return localizedName;
 275 
 276         // This is a trick to determine whether the name has been translated
 277         // or not. If it has not been translated, we need to use Locale.ROOT
 278         // when calling toUpperCase().
 279         final Locale rbLocale = rb.getLocale();
 280         final Locale locale =
 281                 Locale.ROOT.equals(rbLocale)
 282                 || name.equals(localizedName.toUpperCase(Locale.ROOT))
 283                 ? Locale.ROOT : rbLocale;
 284 
 285         // ALL CAPS in a resource bundle's message indicates no translation
 286         // needed per Oracle translation guideline.  To workaround this
 287         // in Oracle JDK implementation, convert the localized level name
 288         // to uppercase for compatibility reason.
 289         return Locale.ROOT.equals(locale) ? name : localizedName.toUpperCase(locale);
 290     }
 291 
 292     // Avoid looking up the localizedLevelName twice if we already
 293     // have it.
 294     final String getCachedLocalizedLevelName() {
 295 
 296         if (localizedLevelName != null) {
 297             if (cachedLocale != null) {
 298                 if (cachedLocale.equals(Locale.getDefault())) {
 299                     // OK: our cached value was looked up with the same
 300                     //     locale. We can use it.
 301                     return localizedLevelName;
 302                 }
 303             }
 304         }
 305 
 306         if (resourceBundleName == null) {
 307             // No resource bundle: just use the name.
 308             return name;
 309         }
 310 
 311         // We need to compute the localized name.
 312         // Either because it's the first time, or because our cached
 313         // value is for a different locale. Just return null.
 314         return null;
 315     }
 316 
 317     final synchronized String getLocalizedLevelName() {
 318 
 319         // See if we have a cached localized name
 320         final String cachedLocalizedName = getCachedLocalizedLevelName();
 321         if (cachedLocalizedName != null) {
 322             return cachedLocalizedName;
 323         }
 324 
 325         // No cached localized name or cache invalid.
 326         // Need to compute the localized name.
 327         final Locale newLocale = Locale.getDefault();
 328         try {
 329             localizedLevelName = computeLocalizedLevelName(newLocale);
 330         } catch (Exception ex) {
 331             localizedLevelName = name;
 332         }
 333         cachedLocale = newLocale;
 334         return localizedLevelName;
 335     }
 336 
 337     // Returns a mirrored Level object that matches the given name as
 338     // specified in the Level.parse method.  Returns null if not found.
 339     //
 340     // It returns the same Level object as the one returned by Level.parse
 341     // method if the given name is a non-localized name or integer.
 342     //
 343     // If the name is a localized name, findLevel and parse method may
 344     // return a different level value if there is a custom Level subclass
 345     // that overrides Level.getLocalizedName() to return a different string
 346     // than what's returned by the default implementation.
 347     //
 348     static Level findLevel(String name) {
 349         if (name == null) {
 350             throw new NullPointerException();
 351         }
 352 
 353         KnownLevel level;
 354 
 355         // Look for a known Level with the given non-localized name.
 356         level = KnownLevel.findByName(name);
 357         if (level != null) {
 358             return level.mirroredLevel;
 359         }
 360 
 361         // Now, check if the given name is an integer.  If so,
 362         // first look for a Level with the given value and then
 363         // if necessary create one.
 364         try {
 365             int x = Integer.parseInt(name);
 366             level = KnownLevel.findByValue(x);
 367             if (level == null) {
 368                 // add new Level
 369                 Level levelObject = new Level(name, x);
 370                 level = KnownLevel.findByValue(x);
 371             }
 372             return level.mirroredLevel;
 373         } catch (NumberFormatException ex) {
 374             // Not an integer.
 375             // Drop through.
 376         }
 377 
 378         level = KnownLevel.findByLocalizedLevelName(name);
 379         if (level != null) {
 380             return level.mirroredLevel;

 381         }
 382 
 383         return null;
 384     }
 385 
 386     /**
 387      * Returns a string representation of this Level.
 388      *
 389      * @return the non-localized name of the Level, for example "INFO".
 390      */
 391     @Override
 392     public final String toString() {
 393         return name;
 394     }
 395 
 396     /**
 397      * Get the integer value for this level.  This integer value
 398      * can be used for efficient ordering comparisons between
 399      * Level objects.
 400      * @return the integer value for this level.
 401      */
 402     public final int intValue() {
 403         return value;
 404     }
 405 
 406     private static final long serialVersionUID = -8176160795706313070L;
 407 
 408     // Serialization magic to prevent "doppelgangers".
 409     // This is a performance optimization.
 410     private Object readResolve() {
 411         KnownLevel o = KnownLevel.matches(this);
 412         if (o != null) {
 413             return o.levelObject;
 414         }
 415 
 416         // Woops.  Whoever sent us this object knows
 417         // about a new log level.  Add it to our list.
 418         Level level = new Level(this.name, this.value, this.resourceBundleName);
 419         return level;
 420     }
 421 
 422     /**
 423      * Parse a level name string into a Level.
 424      * <p>
 425      * The argument string may consist of either a level name
 426      * or an integer value.
 427      * <p>
 428      * For example:
 429      * <ul>
 430      * <li>     "SEVERE"
 431      * <li>     "1000"
 432      * </ul>
 433      *
 434      * @param  name   string to be parsed
 435      * @throws NullPointerException if the name is null
 436      * @throws IllegalArgumentException if the value is not valid.
 437      * Valid values are integers between <CODE>Integer.MIN_VALUE</CODE>
 438      * and <CODE>Integer.MAX_VALUE</CODE>, and all known level names.
 439      * Known names are the levels defined by this class (e.g., <CODE>FINE</CODE>,
 440      * <CODE>FINER</CODE>, <CODE>FINEST</CODE>), or created by this class with
 441      * appropriate package access, or new levels defined or created
 442      * by subclasses.
 443      *
 444      * @return The parsed value. Passing an integer that corresponds to a known name
 445      * (e.g., 700) will return the associated name (e.g., <CODE>CONFIG</CODE>).
 446      * Passing an integer that does not (e.g., 1) will return a new level name
 447      * initialized to that value.
 448      */
 449     public static synchronized Level parse(String name) throws IllegalArgumentException {
 450         // Check that name is not null.
 451         name.length();
 452 
 453         KnownLevel level;
 454 
 455         // Look for a known Level with the given non-localized name.
 456         level = KnownLevel.findByName(name);
 457         if (level != null) {
 458             return level.levelObject;
 459         }
 460 
 461         // Now, check if the given name is an integer.  If so,
 462         // first look for a Level with the given value and then
 463         // if necessary create one.
 464         try {
 465             int x = Integer.parseInt(name);
 466             level = KnownLevel.findByValue(x);
 467             if (level == null) {
 468                 // add new Level
 469                 Level levelObject = new Level(name, x);
 470                 level = KnownLevel.findByValue(x);
 471             }
 472             return level.levelObject;


 473         } catch (NumberFormatException ex) {
 474             // Not an integer.
 475             // Drop through.
 476         }
 477 
 478         // Finally, look for a known level with the given localized name,
 479         // in the current default locale.
 480         // This is relatively expensive, but not excessively so.
 481         level = KnownLevel.findByLocalizedLevelName(name);
 482         if (level != null) {
 483             return level.levelObject;
 484         }
 485 
 486         // OK, we've tried everything and failed
 487         throw new IllegalArgumentException("Bad level \"" + name + "\"");
 488     }
 489 
 490     /**
 491      * Compare two objects for value equality.
 492      * @return true if and only if the two objects have the same level value.
 493      */
 494     @Override
 495     public boolean equals(Object ox) {
 496         try {
 497             Level lx = (Level)ox;
 498             return (lx.value == this.value);
 499         } catch (Exception ex) {
 500             return false;
 501         }
 502     }
 503 
 504     /**
 505      * Generate a hashcode.
 506      * @return a hashcode based on the level value
 507      */
 508     @Override
 509     public int hashCode() {
 510         return this.value;
 511     }
 512 
 513     // KnownLevel class maintains the global list of all known levels.
 514     // The API allows multiple custom Level instances of the same name/value
 515     // be created. This class provides convenient methods to find a level
 516     // by a given name, by a given value, or by a given localized name.
 517     //
 518     // KnownLevel wraps the following Level objects:
 519     // 1. levelObject:   standard Level object or custom Level object
 520     // 2. mirroredLevel: Level object representing the level specified in the
 521     //                   logging configuration.
 522     //
 523     // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
 524     // are non-final but the name and resource bundle name are parameters to
 525     // the Level constructor.  Use the mirroredLevel object instead of the
 526     // levelObject to prevent the logging framework to execute foreign code
 527     // implemented by untrusted Level subclass.
 528     //
 529     // Implementation Notes:
 530     // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
 531     // were final, the following KnownLevel implementation can be removed.
 532     // Future API change should take this into consideration.
 533     static final class KnownLevel {
 534         private static Map<String, List<KnownLevel>> nameToLevels = new HashMap<>();
 535         private static Map<Integer, List<KnownLevel>> intToLevels = new HashMap<>();
 536         final Level levelObject;     // instance of Level class or Level subclass

 537         final Level mirroredLevel;   // mirror of the custom Level
 538         KnownLevel(Level l) {
 539             this.levelObject = l;
 540             if (l.getClass() == Level.class) {
 541                 this.mirroredLevel = l;
 542             } else {
 543                 // this mirrored level object is hidden
 544                 this.mirroredLevel = new Level(l.name, l.value, l.resourceBundleName, false);



























 545             }
 546         }
 547 
 548         static synchronized void add(Level l) {

 549             // the mirroredLevel object is always added to the list
 550             // before the custom Level instance
 551             KnownLevel o = new KnownLevel(l);
 552             List<KnownLevel> list = nameToLevels.get(l.name);
 553             if (list == null) {
 554                 list = new ArrayList<>();
 555                 nameToLevels.put(l.name, list);
 556             }
 557             list.add(o);
 558 
 559             list = intToLevels.get(l.value);
 560             if (list == null) {
 561                 list = new ArrayList<>();
 562                 intToLevels.put(l.value, list);
 563             }
 564             list.add(o);
 565         }
 566 
 567         // Returns a KnownLevel with the given non-localized name.
 568         static synchronized KnownLevel findByName(String name) {
 569             List<KnownLevel> list = nameToLevels.get(name);
 570             if (list != null) {
 571                 return list.get(0);
 572             }
 573             return null;

 574         }
 575 
 576         // Returns a KnownLevel with the given value.
 577         static synchronized KnownLevel findByValue(int value) {
 578             List<KnownLevel> list = intToLevels.get(value);
 579             if (list != null) {
 580                 return list.get(0);
 581             }
 582             return null;

 583         }
 584 
 585         // Returns a KnownLevel with the given localized name matching
 586         // by calling the Level.getLocalizedLevelName() method (i.e. found
 587         // from the resourceBundle associated with the Level object).
 588         // This method does not call Level.getLocalizedName() that may
 589         // be overridden in a subclass implementation
 590         static synchronized KnownLevel findByLocalizedLevelName(String name) {
 591             for (List<KnownLevel> levels : nameToLevels.values()) {
 592                 for (KnownLevel l : levels) {
 593                     String lname = l.levelObject.getLocalizedLevelName();
 594                     if (name.equals(lname)) {
 595                         return l;
 596                     }
 597                 }
 598             }
 599             return null;
 600         }
 601 
 602         static synchronized KnownLevel matches(Level l) {

 603             List<KnownLevel> list = nameToLevels.get(l.name);
 604             if (list != null) {
 605                 for (KnownLevel level : list) {
 606                     Level other = level.mirroredLevel;


 607                     if (l.value == other.value &&
 608                            (l.resourceBundleName == other.resourceBundleName ||
 609                                (l.resourceBundleName != null &&
 610                                 l.resourceBundleName.equals(other.resourceBundleName)))) {
 611                         return level;
 612                     }
 613                 }
 614             }
 615             return null;
 616         }
 617     }
 618 
 619 }
--- EOF ---