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 
  27 package java.util.logging;
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;
  34 import java.lang.reflect.Constructor;
  35 import java.lang.reflect.InvocationTargetException;
  36 import java.lang.reflect.Method;
  37 import java.beans.PropertyChangeListener;
  38 import sun.misc.JavaAWTAccess;
  39 import sun.misc.SharedSecrets;
  40 
  41 /**
  42  * There is a single global LogManager object that is used to
  43  * maintain a set of shared state about Loggers and log services.
  44  * <p>
  45  * This LogManager object:
  46  * <ul>
  47  * <li> Manages a hierarchical namespace of Logger objects.  All
  48  *      named Loggers are stored in this namespace.
  49  * <li> Manages a set of logging control properties.  These are
  50  *      simple key-value pairs that can be used by Handlers and
  51  *      other logging objects to configure themselves.
  52  * </ul>
  53  * <p>
  54  * The global LogManager object can be retrieved using LogManager.getLogManager().
  55  * The LogManager object is created during class initialization and
  56  * cannot subsequently be changed.
  57  * <p>
  58  * At startup the LogManager class is located using the
  59  * java.util.logging.manager system property.
  60  * <p>
  61  * The LogManager defines two optional system properties that allow control over
  62  * the initial configuration:
  63  * <ul>
  64  * <li>"java.util.logging.config.class"
  65  * <li>"java.util.logging.config.file"
  66  * </ul>
  67  * These two properties may be specified on the command line to the "java"
  68  * command, or as system property definitions passed to JNI_CreateJavaVM.
  69  * <p>
  70  * If the "java.util.logging.config.class" property is set, then the
  71  * property value is treated as a class name.  The given class will be
  72  * loaded, an object will be instantiated, and that object's constructor
  73  * is responsible for reading in the initial configuration.  (That object
  74  * may use other system properties to control its configuration.)  The
  75  * alternate configuration class can use <tt>readConfiguration(InputStream)</tt>
  76  * to define properties in the LogManager.
  77  * <p>
  78  * If "java.util.logging.config.class" property is <b>not</b> set,
  79  * then the "java.util.logging.config.file" system property can be used
  80  * to specify a properties file (in java.util.Properties format). The
  81  * initial logging configuration will be read from this file.
  82  * <p>
  83  * If neither of these properties is defined then the LogManager uses its
  84  * default configuration. The default configuration is typically loaded from the
  85  * properties file "{@code lib/logging.properties}" in the Java installation
  86  * directory.
  87  * <p>
  88  * The properties for loggers and Handlers will have names starting
  89  * with the dot-separated name for the handler or logger.
  90  * <p>
  91  * The global logging properties may include:
  92  * <ul>
  93  * <li>A property "handlers".  This defines a whitespace or comma separated
  94  * list of class names for handler classes to load and register as
  95  * handlers on the root Logger (the Logger named "").  Each class
  96  * name must be for a Handler class which has a default constructor.
  97  * Note that these Handlers may be created lazily, when they are
  98  * first used.
  99  *
 100  * <li>A property "&lt;logger&gt;.handlers". This defines a whitespace or
 101  * comma separated list of class names for handlers classes to
 102  * load and register as handlers to the specified logger. Each class
 103  * name must be for a Handler class which has a default constructor.
 104  * Note that these Handlers may be created lazily, when they are
 105  * first used.
 106  *
 107  * <li>A property "&lt;logger&gt;.useParentHandlers". This defines a boolean
 108  * value. By default every logger calls its parent in addition to
 109  * handling the logging message itself, this often result in messages
 110  * being handled by the root logger as well. When setting this property
 111  * to false a Handler needs to be configured for this logger otherwise
 112  * no logging messages are delivered.
 113  *
 114  * <li>A property "config".  This property is intended to allow
 115  * arbitrary configuration code to be run.  The property defines a
 116  * whitespace or comma separated list of class names.  A new instance will be
 117  * created for each named class.  The default constructor of each class
 118  * may execute arbitrary code to update the logging configuration, such as
 119  * setting logger levels, adding handlers, adding filters, etc.
 120  * </ul>
 121  * <p>
 122  * Note that all classes loaded during LogManager configuration are
 123  * first searched on the system class path before any user class path.
 124  * That includes the LogManager class, any config classes, and any
 125  * handler classes.
 126  * <p>
 127  * Loggers are organized into a naming hierarchy based on their
 128  * dot separated names.  Thus "a.b.c" is a child of "a.b", but
 129  * "a.b1" and a.b2" are peers.
 130  * <p>
 131  * All properties whose names end with ".level" are assumed to define
 132  * log levels for Loggers.  Thus "foo.level" defines a log level for
 133  * the logger called "foo" and (recursively) for any of its children
 134  * in the naming hierarchy.  Log Levels are applied in the order they
 135  * are defined in the properties file.  Thus level settings for child
 136  * nodes in the tree should come after settings for their parents.
 137  * The property name ".level" can be used to set the level for the
 138  * root of the tree.
 139  * <p>
 140  * All methods on the LogManager object are multi-thread safe.
 141  *
 142  * @since 1.4
 143 */
 144 
 145 public class LogManager {
 146     // The global LogManager object
 147     private static final LogManager manager;
 148 
 149     private Properties props = new Properties();
 150     private final static Level defaultLevel = Level.INFO;
 151 
 152     // The map of the registered listeners. The map value is the registration
 153     // count to allow for cases where the same listener is registered many times.
 154     private final Map<Object,Integer> listenerMap = new HashMap<>();
 155 
 156     // LoggerContext for system loggers and user loggers
 157     private final LoggerContext systemContext = new SystemLoggerContext();
 158     private final LoggerContext userContext = new LoggerContext();
 159     // non final field - make it volatile to make sure that other threads
 160     // will see the new value once ensureLogManagerInitialized() has finished
 161     // executing.
 162     private volatile Logger rootLogger;
 163     // Have we done the primordial reading of the configuration file?
 164     // (Must be done after a suitable amount of java.lang.System
 165     // initialization has been done)
 166     private volatile boolean readPrimordialConfiguration;
 167     // Have we initialized global (root) handlers yet?
 168     // This gets set to false in readConfiguration
 169     private boolean initializedGlobalHandlers = true;
 170     // True if JVM death is imminent and the exit hook has been called.
 171     private boolean deathImminent;
 172 
 173     static {
 174         manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
 175             @Override
 176             public LogManager run() {
 177                 LogManager mgr = null;
 178                 String cname = null;
 179                 try {
 180                     cname = System.getProperty("java.util.logging.manager");
 181                     if (cname != null) {
 182                         try {
 183                             Class<?> clz = ClassLoader.getSystemClassLoader()
 184                                     .loadClass(cname);
 185                             mgr = (LogManager) clz.newInstance();
 186                         } catch (ClassNotFoundException ex) {
 187                             Class<?> clz = Thread.currentThread()
 188                                     .getContextClassLoader().loadClass(cname);
 189                             mgr = (LogManager) clz.newInstance();
 190                         }
 191                     }
 192                 } catch (Exception ex) {
 193                     System.err.println("Could not load Logmanager \"" + cname + "\"");
 194                     ex.printStackTrace();
 195                 }
 196                 if (mgr == null) {
 197                     mgr = new LogManager();
 198                 }
 199                 return mgr;
 200 
 201             }
 202         });
 203     }
 204 
 205 
 206     // This private class is used as a shutdown hook.
 207     // It does a "reset" to close all open handlers.
 208     private class Cleaner extends Thread {
 209 
 210         private Cleaner() {
 211             /* Set context class loader to null in order to avoid
 212              * keeping a strong reference to an application classloader.
 213              */
 214             this.setContextClassLoader(null);
 215         }
 216 
 217         @Override
 218         public void run() {
 219             // This is to ensure the LogManager.<clinit> is completed
 220             // before synchronized block. Otherwise deadlocks are possible.
 221             LogManager mgr = manager;
 222 
 223             // If the global handlers haven't been initialized yet, we
 224             // don't want to initialize them just so we can close them!
 225             synchronized (LogManager.this) {
 226                 // Note that death is imminent.
 227                 deathImminent = true;
 228                 initializedGlobalHandlers = true;
 229             }
 230 
 231             // Do a reset to close all active handlers.
 232             reset();
 233         }
 234     }
 235 
 236 
 237     /**
 238      * Protected constructor.  This is protected so that container applications
 239      * (such as J2EE containers) can subclass the object.  It is non-public as
 240      * it is intended that there only be one LogManager object, whose value is
 241      * retrieved by calling LogManager.getLogManager.
 242      */
 243     protected LogManager() {
 244         // Add a shutdown hook to close the global handlers.
 245         try {
 246             Runtime.getRuntime().addShutdownHook(new Cleaner());
 247         } catch (IllegalStateException e) {
 248             // If the VM is already shutting down,
 249             // We do not need to register shutdownHook.
 250         }
 251     }
 252 
 253     /**
 254      * Lazy initialization: if this instance of manager is the global
 255      * manager then this method will read the initial configuration and
 256      * add the root logger and global logger by calling addLogger().
 257      *
 258      * Note that it is subtly different from what we do in LoggerContext.
 259      * In LoggerContext we're patching up the logger context tree in order to add
 260      * the root and global logger *to the context tree*.
 261      *
 262      * For this to work, addLogger() must have already have been called
 263      * once on the LogManager instance for the default logger being
 264      * added.
 265      *
 266      * This is why ensureLogManagerInitialized() needs to be called before
 267      * any logger is added to any logger context.
 268      *
 269      */
 270     private boolean initializedCalled = false;
 271     private volatile boolean initializationDone = false;
 272     final void ensureLogManagerInitialized() {
 273         final LogManager owner = this;
 274         if (initializationDone || owner != manager) {
 275             // we don't want to do this twice, and we don't want to do
 276             // this on private manager instances.
 277             return;
 278         }
 279 
 280         // Maybe another thread has called ensureLogManagerInitialized()
 281         // before us and is still executing it. If so we will block until
 282         // the log manager has finished initialized, then acquire the monitor,
 283         // notice that initializationDone is now true and return.
 284         // Otherwise - we have come here first! We will acquire the monitor,
 285         // see that initializationDone is still false, and perform the
 286         // initialization.
 287         //
 288         synchronized(this) {
 289             // If initializedCalled is true it means that we're already in
 290             // the process of initializing the LogManager in this thread.
 291             // There has been a recursive call to ensureLogManagerInitialized().
 292             final boolean isRecursiveInitialization = (initializedCalled == true);
 293 
 294             assert initializedCalled || !initializationDone
 295                     : "Initialization can't be done if initialized has not been called!";
 296 
 297             if (isRecursiveInitialization || initializationDone) {
 298                 // If isRecursiveInitialization is true it means that we're
 299                 // already in the process of initializing the LogManager in
 300                 // this thread. There has been a recursive call to
 301                 // ensureLogManagerInitialized(). We should not proceed as
 302                 // it would lead to infinite recursion.
 303                 //
 304                 // If initializationDone is true then it means the manager
 305                 // has finished initializing; just return: we're done.
 306                 return;
 307             }
 308             // Calling addLogger below will in turn call requiresDefaultLogger()
 309             // which will call ensureLogManagerInitialized().
 310             // We use initializedCalled to break the recursion.
 311             initializedCalled = true;
 312             try {
 313                 AccessController.doPrivileged(new PrivilegedAction<Object>() {
 314                     @Override
 315                     public Object run() {
 316                         assert rootLogger == null;
 317                         assert initializedCalled && !initializationDone;
 318 
 319                         // Read configuration.
 320                         owner.readPrimordialConfiguration();
 321 
 322                         // Create and retain Logger for the root of the namespace.
 323                         owner.rootLogger = owner.new RootLogger();
 324                         owner.addLogger(owner.rootLogger);
 325 
 326                         // Adding the global Logger.
 327                         // Do not call Logger.getGlobal() here as this might trigger
 328                         // subtle inter-dependency issues.
 329                         @SuppressWarnings("deprecation")
 330                         final Logger global = Logger.global;
 331 
 332                         // Make sure the global logger will be registered in the
 333                         // global manager
 334                         owner.addLogger(global);
 335                         return null;
 336                     }
 337                 });
 338             } finally {
 339                 initializationDone = true;
 340             }
 341         }
 342     }
 343 
 344     /**
 345      * Returns the global LogManager object.
 346      * @return the global LogManager object
 347      */
 348     public static LogManager getLogManager() {
 349         if (manager != null) {
 350             manager.ensureLogManagerInitialized();
 351         }
 352         return manager;
 353     }
 354 
 355     private void readPrimordialConfiguration() {
 356         if (!readPrimordialConfiguration) {
 357             synchronized (this) {
 358                 if (!readPrimordialConfiguration) {
 359                     // If System.in/out/err are null, it's a good
 360                     // indication that we're still in the
 361                     // bootstrapping phase
 362                     if (System.out == null) {
 363                         return;
 364                     }
 365                     readPrimordialConfiguration = true;
 366 
 367                     try {
 368                         AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
 369                                 @Override
 370                                 public Void run() throws Exception {
 371                                     readConfiguration();
 372 
 373                                     // Platform loggers begin to delegate to java.util.logging.Logger
 374                                     sun.util.logging.PlatformLogger.redirectPlatformLoggers();
 375                                     return null;
 376                                 }
 377                             });
 378                     } catch (Exception ex) {
 379                         assert false : "Exception raised while reading logging configuration: " + ex;
 380                     }
 381                 }
 382             }
 383         }
 384     }
 385 
 386     /**
 387      * Adds an event listener to be invoked when the logging
 388      * properties are re-read. Adding multiple instances of
 389      * the same event Listener results in multiple entries
 390      * in the property event listener table.
 391      *
 392      * <p><b>WARNING:</b> This method is omitted from this class in all subset
 393      * Profiles of Java SE that do not include the {@code java.beans} package.
 394      * </p>
 395      *
 396      * @param l  event listener
 397      * @exception  SecurityException  if a security manager exists and if
 398      *             the caller does not have LoggingPermission("control").
 399      * @exception NullPointerException if the PropertyChangeListener is null.
 400      * @deprecated The dependency on {@code PropertyChangeListener} creates a
 401      *             significant impediment to future modularization of the Java
 402      *             platform. This method will be removed in a future release.
 403      *             The global {@code LogManager} can detect changes to the
 404      *             logging configuration by overridding the {@link
 405      *             #readConfiguration readConfiguration} method.
 406      */
 407     @Deprecated
 408     public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException {
 409         PropertyChangeListener listener = Objects.requireNonNull(l);
 410         checkPermission();
 411         synchronized (listenerMap) {
 412             // increment the registration count if already registered
 413             Integer value = listenerMap.get(listener);
 414             value = (value == null) ? 1 : (value + 1);
 415             listenerMap.put(listener, value);
 416         }
 417     }
 418 
 419     /**
 420      * Removes an event listener for property change events.
 421      * If the same listener instance has been added to the listener table
 422      * through multiple invocations of <CODE>addPropertyChangeListener</CODE>,
 423      * then an equivalent number of
 424      * <CODE>removePropertyChangeListener</CODE> invocations are required to remove
 425      * all instances of that listener from the listener table.
 426      * <P>
 427      * Returns silently if the given listener is not found.
 428      *
 429      * <p><b>WARNING:</b> This method is omitted from this class in all subset
 430      * Profiles of Java SE that do not include the {@code java.beans} package.
 431      * </p>
 432      *
 433      * @param l  event listener (can be null)
 434      * @exception  SecurityException  if a security manager exists and if
 435      *             the caller does not have LoggingPermission("control").
 436      * @deprecated The dependency on {@code PropertyChangeListener} creates a
 437      *             significant impediment to future modularization of the Java
 438      *             platform. This method will be removed in a future release.
 439      *             The global {@code LogManager} can detect changes to the
 440      *             logging configuration by overridding the {@link
 441      *             #readConfiguration readConfiguration} method.
 442      */
 443     @Deprecated
 444     public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException {
 445         checkPermission();
 446         if (l != null) {
 447             PropertyChangeListener listener = l;
 448             synchronized (listenerMap) {
 449                 Integer value = listenerMap.get(listener);
 450                 if (value != null) {
 451                     // remove from map if registration count is 1, otherwise
 452                     // just decrement its count
 453                     int i = value.intValue();
 454                     if (i == 1) {
 455                         listenerMap.remove(listener);
 456                     } else {
 457                         assert i > 1;
 458                         listenerMap.put(listener, i - 1);
 459                     }
 460                 }
 461             }
 462         }
 463     }
 464 
 465     // LoggerContext maps from AppContext
 466     private WeakHashMap<Object, LoggerContext> contextsMap = null;
 467 
 468     // Returns the LoggerContext for the user code (i.e. application or AppContext).
 469     // Loggers are isolated from each AppContext.
 470     private LoggerContext getUserContext() {
 471         LoggerContext context = null;
 472 
 473         SecurityManager sm = System.getSecurityManager();
 474         JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
 475         if (sm != null && javaAwtAccess != null) {
 476             // for each applet, it has its own LoggerContext isolated from others
 477             synchronized (javaAwtAccess) {
 478                 // find the AppContext of the applet code
 479                 // will be null if we are in the main app context.
 480                 final Object ecx = javaAwtAccess.getAppletContext();
 481                 if (ecx != null) {
 482                     if (contextsMap == null) {
 483                         contextsMap = new WeakHashMap<>();
 484                     }
 485                     context = contextsMap.get(ecx);
 486                     if (context == null) {
 487                         // Create a new LoggerContext for the applet.
 488                         context = new LoggerContext();
 489                         contextsMap.put(ecx, context);
 490                     }
 491                 }
 492             }
 493         }
 494         // for standalone app, return userContext
 495         return context != null ? context : userContext;
 496     }
 497 
 498     // The system context.
 499     final LoggerContext getSystemContext() {
 500         return systemContext;
 501     }
 502 
 503     private List<LoggerContext> contexts() {
 504         List<LoggerContext> cxs = new ArrayList<>();
 505         cxs.add(getSystemContext());
 506         cxs.add(getUserContext());
 507         return cxs;
 508     }
 509 
 510     // Find or create a specified logger instance. If a logger has
 511     // already been created with the given name it is returned.
 512     // Otherwise a new logger instance is created and registered
 513     // in the LogManager global namespace.
 514     // This method will always return a non-null Logger object.
 515     // Synchronization is not required here. All synchronization for
 516     // adding a new Logger object is handled by addLogger().
 517     //
 518     // This method must delegate to the LogManager implementation to
 519     // add a new Logger or return the one that has been added previously
 520     // as a LogManager subclass may override the addLogger, getLogger,
 521     // readConfiguration, and other methods.
 522     Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 523         Logger result = getLogger(name);
 524         if (result == null) {
 525             // only allocate the new logger once
 526             Logger newLogger = new Logger(name, resourceBundleName, caller, this);
 527             do {
 528                 if (addLogger(newLogger)) {
 529                     // We successfully added the new Logger that we
 530                     // created above so return it without refetching.
 531                     return newLogger;
 532                 }
 533 
 534                 // We didn't add the new Logger that we created above
 535                 // because another thread added a Logger with the same
 536                 // name after our null check above and before our call
 537                 // to addLogger(). We have to refetch the Logger because
 538                 // addLogger() returns a boolean instead of the Logger
 539                 // reference itself. However, if the thread that created
 540                 // the other Logger is not holding a strong reference to
 541                 // the other Logger, then it is possible for the other
 542                 // Logger to be GC'ed after we saw it in addLogger() and
 543                 // before we can refetch it. If it has been GC'ed then
 544                 // we'll just loop around and try again.
 545                 result = getLogger(name);
 546             } while (result == null);
 547         }
 548         return result;
 549     }
 550 
 551     Logger demandSystemLogger(String name, String resourceBundleName) {
 552         // Add a system logger in the system context's namespace
 553         final Logger sysLogger = getSystemContext().demandLogger(name, resourceBundleName);
 554 
 555         // Add the system logger to the LogManager's namespace if not exist
 556         // so that there is only one single logger of the given name.
 557         // System loggers are visible to applications unless a logger of
 558         // the same name has been added.
 559         Logger logger;
 560         do {
 561             // First attempt to call addLogger instead of getLogger
 562             // This would avoid potential bug in custom LogManager.getLogger
 563             // implementation that adds a logger if does not exist
 564             if (addLogger(sysLogger)) {
 565                 // successfully added the new system logger
 566                 logger = sysLogger;
 567             } else {
 568                 logger = getLogger(name);
 569             }
 570         } while (logger == null);
 571 
 572         // LogManager will set the sysLogger's handlers via LogManager.addLogger method.
 573         if (logger != sysLogger && sysLogger.getHandlers().length == 0) {
 574             // if logger already exists but handlers not set
 575             final Logger l = logger;
 576             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 577                 @Override
 578                 public Void run() {
 579                     for (Handler hdl : l.getHandlers()) {
 580                         sysLogger.addHandler(hdl);
 581                     }
 582                     return null;
 583                 }
 584             });
 585         }
 586         return sysLogger;
 587     }
 588 
 589     // LoggerContext maintains the logger namespace per context.
 590     // The default LogManager implementation has one system context and user
 591     // context.  The system context is used to maintain the namespace for
 592     // all system loggers and is queried by the system code.  If a system logger
 593     // doesn't exist in the user context, it'll also be added to the user context.
 594     // The user context is queried by the user code and all other loggers are
 595     // added in the user context.
 596     class LoggerContext {
 597         // Table of named Loggers that maps names to Loggers.
 598         private final Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
 599         // Tree of named Loggers
 600         private final LogNode root;
 601         private LoggerContext() {
 602             this.root = new LogNode(null, this);
 603         }
 604 
 605 
 606         // Tells whether default loggers are required in this context.
 607         // If true, the default loggers will be lazily added.
 608         final boolean requiresDefaultLoggers() {
 609             final boolean requiresDefaultLoggers = (getOwner() == manager);
 610             if (requiresDefaultLoggers) {
 611                 getOwner().ensureLogManagerInitialized();
 612             }
 613             return requiresDefaultLoggers;
 614         }
 615 
 616         // This context's LogManager.
 617         final LogManager getOwner() {
 618             return LogManager.this;
 619         }
 620 
 621         // This context owner's root logger, which if not null, and if
 622         // the context requires default loggers, will be added to the context
 623         // logger's tree.
 624         final Logger getRootLogger() {
 625             return getOwner().rootLogger;
 626         }
 627 
 628         // The global logger, which if not null, and if
 629         // the context requires default loggers, will be added to the context
 630         // logger's tree.
 631         final Logger getGlobalLogger() {
 632             @SuppressWarnings("deprecated") // avoids initialization cycles.
 633             final Logger global = Logger.global;
 634             return global;
 635         }
 636 
 637         Logger demandLogger(String name, String resourceBundleName) {
 638             // a LogManager subclass may have its own implementation to add and
 639             // get a Logger.  So delegate to the LogManager to do the work.
 640             final LogManager owner = getOwner();
 641             return owner.demandLogger(name, resourceBundleName, null);
 642         }
 643 
 644 
 645         // Due to subtle deadlock issues getUserContext() no longer
 646         // calls addLocalLogger(rootLogger);
 647         // Therefore - we need to add the default loggers later on.
 648         // Checks that the context is properly initialized
 649         // This is necessary before calling e.g. find(name)
 650         // or getLoggerNames()
 651         //
 652         private void ensureInitialized() {
 653             if (requiresDefaultLoggers()) {
 654                 // Ensure that the root and global loggers are set.
 655                 ensureDefaultLogger(getRootLogger());
 656                 ensureDefaultLogger(getGlobalLogger());
 657             }
 658         }
 659 
 660 
 661         synchronized Logger findLogger(String name) {
 662             // ensure that this context is properly initialized before
 663             // looking for loggers.
 664             ensureInitialized();
 665             LoggerWeakRef ref = namedLoggers.get(name);
 666             if (ref == null) {
 667                 return null;
 668             }
 669             Logger logger = ref.get();
 670             if (logger == null) {
 671                 // Hashtable holds stale weak reference
 672                 // to a logger which has been GC-ed.
 673                 removeLogger(name);
 674             }
 675             return logger;
 676         }
 677 
 678         // This method is called before adding a logger to the
 679         // context.
 680         // 'logger' is the context that will be added.
 681         // This method will ensure that the defaults loggers are added
 682         // before adding 'logger'.
 683         //
 684         private void ensureAllDefaultLoggers(Logger logger) {
 685             if (requiresDefaultLoggers()) {
 686                 final String name = logger.getName();
 687                 if (!name.isEmpty()) {
 688                     ensureDefaultLogger(getRootLogger());
 689                     if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) {
 690                         ensureDefaultLogger(getGlobalLogger());
 691                     }
 692                 }
 693             }
 694         }
 695 
 696         private void ensureDefaultLogger(Logger logger) {
 697             // Used for lazy addition of root logger and global logger
 698             // to a LoggerContext.
 699 
 700             // This check is simple sanity: we do not want that this
 701             // method be called for anything else than Logger.global
 702             // or owner.rootLogger.
 703             if (!requiresDefaultLoggers() || logger == null
 704                     || logger != Logger.global && logger != LogManager.this.rootLogger) {
 705 
 706                 // the case where we have a non null logger which is neither
 707                 // Logger.global nor manager.rootLogger indicates a serious
 708                 // issue - as ensureDefaultLogger should never be called
 709                 // with any other loggers than one of these two (or null - if
 710                 // e.g manager.rootLogger is not yet initialized)...
 711                 assert logger == null;
 712 
 713                 return;
 714             }
 715 
 716             // Adds the logger if it's not already there.
 717             if (!namedLoggers.containsKey(logger.getName())) {
 718                 // It is important to prevent addLocalLogger to
 719                 // call ensureAllDefaultLoggers when we're in the process
 720                 // off adding one of those default loggers - as this would
 721                 // immediately cause a stack overflow.
 722                 // Therefore we must pass addDefaultLoggersIfNeeded=false,
 723                 // even if requiresDefaultLoggers is true.
 724                 addLocalLogger(logger, false);
 725             }
 726         }
 727 
 728         boolean addLocalLogger(Logger logger) {
 729             // no need to add default loggers if it's not required
 730             return addLocalLogger(logger, requiresDefaultLoggers());
 731         }
 732 
 733         // Add a logger to this context.  This method will only set its level
 734         // and process parent loggers.  It doesn't set its handlers.
 735         synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) {
 736             // addDefaultLoggersIfNeeded serves to break recursion when adding
 737             // default loggers. If we're adding one of the default loggers
 738             // (we're being called from ensureDefaultLogger()) then
 739             // addDefaultLoggersIfNeeded will be false: we don't want to
 740             // call ensureAllDefaultLoggers again.
 741             //
 742             // Note: addDefaultLoggersIfNeeded can also be false when
 743             //       requiresDefaultLoggers is false - since calling
 744             //       ensureAllDefaultLoggers would have no effect in this case.
 745             if (addDefaultLoggersIfNeeded) {
 746                 ensureAllDefaultLoggers(logger);
 747             }
 748 
 749             final String name = logger.getName();
 750             if (name == null) {
 751                 throw new NullPointerException();
 752             }
 753             LoggerWeakRef ref = namedLoggers.get(name);
 754             if (ref != null) {
 755                 if (ref.get() == null) {
 756                     // It's possible that the Logger was GC'ed after a
 757                     // drainLoggerRefQueueBounded() call above so allow
 758                     // a new one to be registered.
 759                     removeLogger(name);
 760                 } else {
 761                     // We already have a registered logger with the given name.
 762                     return false;
 763                 }
 764             }
 765 
 766             // We're adding a new logger.
 767             // Note that we are creating a weak reference here.
 768             final LogManager owner = getOwner();
 769             logger.setLogManager(owner);
 770             ref = owner.new LoggerWeakRef(logger);
 771             namedLoggers.put(name, ref);
 772 
 773             // Apply any initial level defined for the new logger.
 774             Level level = owner.getLevelProperty(name + ".level", null);
 775             if (level != null) {
 776                 doSetLevel(logger, level);
 777             }
 778 
 779             // instantiation of the handler is done in the LogManager.addLogger
 780             // implementation as a handler class may be only visible to LogManager
 781             // subclass for the custom log manager case
 782             processParentHandlers(logger, name);
 783 
 784             // Find the new node and its parent.
 785             LogNode node = getNode(name);
 786             node.loggerRef = ref;
 787             Logger parent = null;
 788             LogNode nodep = node.parent;
 789             while (nodep != null) {
 790                 LoggerWeakRef nodeRef = nodep.loggerRef;
 791                 if (nodeRef != null) {
 792                     parent = nodeRef.get();
 793                     if (parent != null) {
 794                         break;
 795                     }
 796                 }
 797                 nodep = nodep.parent;
 798             }
 799 
 800             if (parent != null) {
 801                 doSetParent(logger, parent);
 802             }
 803             // Walk over the children and tell them we are their new parent.
 804             node.walkAndSetParent(logger);
 805             // new LogNode is ready so tell the LoggerWeakRef about it
 806             ref.setNode(node);
 807             return true;
 808         }
 809 
 810         // note: all calls to removeLogger are synchronized on LogManager's
 811         // intrinsic lock
 812         void removeLogger(String name) {
 813             namedLoggers.remove(name);
 814         }
 815 
 816         synchronized Enumeration<String> getLoggerNames() {
 817             // ensure that this context is properly initialized before
 818             // returning logger names.
 819             ensureInitialized();
 820             return namedLoggers.keys();
 821         }
 822 
 823         // If logger.getUseParentHandlers() returns 'true' and any of the logger's
 824         // parents have levels or handlers defined, make sure they are instantiated.
 825         private void processParentHandlers(final Logger logger, final String name) {
 826             final LogManager owner = getOwner();
 827             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 828                 @Override
 829                 public Void run() {
 830                     if (logger != owner.rootLogger) {
 831                         boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true);
 832                         if (!useParent) {
 833                             logger.setUseParentHandlers(false);
 834                         }
 835                     }
 836                     return null;
 837                 }
 838             });
 839 
 840             int ix = 1;
 841             for (;;) {
 842                 int ix2 = name.indexOf(".", ix);
 843                 if (ix2 < 0) {
 844                     break;
 845                 }
 846                 String pname = name.substring(0, ix2);
 847                 if (owner.getProperty(pname + ".level") != null ||
 848                     owner.getProperty(pname + ".handlers") != null) {
 849                     // This pname has a level/handlers definition.
 850                     // Make sure it exists.
 851                     demandLogger(pname, null);
 852                 }
 853                 ix = ix2+1;
 854             }
 855         }
 856 
 857         // Gets a node in our tree of logger nodes.
 858         // If necessary, create it.
 859         LogNode getNode(String name) {
 860             if (name == null || name.equals("")) {
 861                 return root;
 862             }
 863             LogNode node = root;
 864             while (name.length() > 0) {
 865                 int ix = name.indexOf(".");
 866                 String head;
 867                 if (ix > 0) {
 868                     head = name.substring(0, ix);
 869                     name = name.substring(ix + 1);
 870                 } else {
 871                     head = name;
 872                     name = "";
 873                 }
 874                 if (node.children == null) {
 875                     node.children = new HashMap<>();
 876                 }
 877                 LogNode child = node.children.get(head);
 878                 if (child == null) {
 879                     child = new LogNode(node, this);
 880                     node.children.put(head, child);
 881                 }
 882                 node = child;
 883             }
 884             return node;
 885         }
 886     }
 887 
 888     final class SystemLoggerContext extends LoggerContext {
 889         // Add a system logger in the system context's namespace as well as
 890         // in the LogManager's namespace if not exist so that there is only
 891         // one single logger of the given name.  System loggers are visible
 892         // to applications unless a logger of the same name has been added.
 893         @Override
 894         Logger demandLogger(String name, String resourceBundleName) {
 895             Logger result = findLogger(name);
 896             if (result == null) {
 897                 // only allocate the new system logger once
 898                 Logger newLogger = new Logger(name, resourceBundleName, null, getOwner());
 899                 do {
 900                     if (addLocalLogger(newLogger)) {
 901                         // We successfully added the new Logger that we
 902                         // created above so return it without refetching.
 903                         result = newLogger;
 904                     } else {
 905                         // We didn't add the new Logger that we created above
 906                         // because another thread added a Logger with the same
 907                         // name after our null check above and before our call
 908                         // to addLogger(). We have to refetch the Logger because
 909                         // addLogger() returns a boolean instead of the Logger
 910                         // reference itself. However, if the thread that created
 911                         // the other Logger is not holding a strong reference to
 912                         // the other Logger, then it is possible for the other
 913                         // Logger to be GC'ed after we saw it in addLogger() and
 914                         // before we can refetch it. If it has been GC'ed then
 915                         // we'll just loop around and try again.
 916                         result = findLogger(name);
 917                     }
 918                 } while (result == null);
 919             }
 920             return result;
 921         }
 922     }
 923 
 924     // Add new per logger handlers.
 925     // We need to raise privilege here. All our decisions will
 926     // be made based on the logging configuration, which can
 927     // only be modified by trusted code.
 928     private void loadLoggerHandlers(final Logger logger, final String name,
 929                                     final String handlersPropertyName)
 930     {
 931         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 932             @Override
 933             public Object run() {
 934                 String names[] = parseClassNames(handlersPropertyName);
 935                 for (int i = 0; i < names.length; i++) {
 936                     String word = names[i];
 937                     try {
 938                         Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
 939                         Handler hdl = (Handler) clz.newInstance();
 940                         // Check if there is a property defining the
 941                         // this handler's level.
 942                         String levs = getProperty(word + ".level");
 943                         if (levs != null) {
 944                             Level l = Level.findLevel(levs);
 945                             if (l != null) {
 946                                 hdl.setLevel(l);
 947                             } else {
 948                                 // Probably a bad level. Drop through.
 949                                 System.err.println("Can't set level for " + word);
 950                             }
 951                         }
 952                         // Add this Handler to the logger
 953                         logger.addHandler(hdl);
 954                     } catch (Exception ex) {
 955                         System.err.println("Can't load log handler \"" + word + "\"");
 956                         System.err.println("" + ex);
 957                         ex.printStackTrace();
 958                     }
 959                 }
 960                 return null;
 961             }
 962         });
 963     }
 964 
 965 
 966     // loggerRefQueue holds LoggerWeakRef objects for Logger objects
 967     // that have been GC'ed.
 968     private final ReferenceQueue<Logger> loggerRefQueue
 969         = new ReferenceQueue<>();
 970 
 971     // Package-level inner class.
 972     // Helper class for managing WeakReferences to Logger objects.
 973     //
 974     // LogManager.namedLoggers
 975     //     - has weak references to all named Loggers
 976     //     - namedLoggers keeps the LoggerWeakRef objects for the named
 977     //       Loggers around until we can deal with the book keeping for
 978     //       the named Logger that is being GC'ed.
 979     // LogManager.LogNode.loggerRef
 980     //     - has a weak reference to a named Logger
 981     //     - the LogNode will also keep the LoggerWeakRef objects for
 982     //       the named Loggers around; currently LogNodes never go away.
 983     // Logger.kids
 984     //     - has a weak reference to each direct child Logger; this
 985     //       includes anonymous and named Loggers
 986     //     - anonymous Loggers are always children of the rootLogger
 987     //       which is a strong reference; rootLogger.kids keeps the
 988     //       LoggerWeakRef objects for the anonymous Loggers around
 989     //       until we can deal with the book keeping.
 990     //
 991     final class LoggerWeakRef extends WeakReference<Logger> {
 992         private String                name;       // for namedLoggers cleanup
 993         private LogNode               node;       // for loggerRef cleanup
 994         private WeakReference<Logger> parentRef;  // for kids cleanup
 995 
 996         LoggerWeakRef(Logger logger) {
 997             super(logger, loggerRefQueue);
 998 
 999             name = logger.getName();  // save for namedLoggers cleanup
1000         }
1001 
1002         // dispose of this LoggerWeakRef object
1003         void dispose() {
1004             if (node != null) {
1005                 // if we have a LogNode, then we were a named Logger
1006                 // so clear namedLoggers weak ref to us
1007                 node.context.removeLogger(name);
1008                 name = null;  // clear our ref to the Logger's name
1009 
1010                 node.loggerRef = null;  // clear LogNode's weak ref to us
1011                 node = null;            // clear our ref to LogNode
1012             }
1013 
1014             if (parentRef != null) {
1015                 // this LoggerWeakRef has or had a parent Logger
1016                 Logger parent = parentRef.get();
1017                 if (parent != null) {
1018                     // the parent Logger is still there so clear the
1019                     // parent Logger's weak ref to us
1020                     parent.removeChildLogger(this);
1021                 }
1022                 parentRef = null;  // clear our weak ref to the parent Logger
1023             }
1024         }
1025 
1026         // set the node field to the specified value
1027         void setNode(LogNode node) {
1028             this.node = node;
1029         }
1030 
1031         // set the parentRef field to the specified value
1032         void setParentRef(WeakReference<Logger> parentRef) {
1033             this.parentRef = parentRef;
1034         }
1035     }
1036 
1037     // Package-level method.
1038     // Drain some Logger objects that have been GC'ed.
1039     //
1040     // drainLoggerRefQueueBounded() is called by addLogger() below
1041     // and by Logger.getAnonymousLogger(String) so we'll drain up to
1042     // MAX_ITERATIONS GC'ed Loggers for every Logger we add.
1043     //
1044     // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives
1045     // us about a 50/50 mix in increased weak ref counts versus
1046     // decreased weak ref counts in the AnonLoggerWeakRefLeak test.
1047     // Here are stats for cleaning up sets of 400 anonymous Loggers:
1048     //   - test duration 1 minute
1049     //   - sample size of 125 sets of 400
1050     //   - average: 1.99 ms
1051     //   - minimum: 0.57 ms
1052     //   - maximum: 25.3 ms
1053     //
1054     // The same config gives us a better decreased weak ref count
1055     // than increased weak ref count in the LoggerWeakRefLeak test.
1056     // Here are stats for cleaning up sets of 400 named Loggers:
1057     //   - test duration 2 minutes
1058     //   - sample size of 506 sets of 400
1059     //   - average: 0.57 ms
1060     //   - minimum: 0.02 ms
1061     //   - maximum: 10.9 ms
1062     //
1063     private final static int MAX_ITERATIONS = 400;
1064     final synchronized void drainLoggerRefQueueBounded() {
1065         for (int i = 0; i < MAX_ITERATIONS; i++) {
1066             if (loggerRefQueue == null) {
1067                 // haven't finished loading LogManager yet
1068                 break;
1069             }
1070 
1071             LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll();
1072             if (ref == null) {
1073                 break;
1074             }
1075             // a Logger object has been GC'ed so clean it up
1076             ref.dispose();
1077         }
1078     }
1079 
1080     /**
1081      * Add a named logger.  This does nothing and returns false if a logger
1082      * with the same name is already registered.
1083      * <p>
1084      * The Logger factory methods call this method to register each
1085      * newly created Logger.
1086      * <p>
1087      * The application should retain its own reference to the Logger
1088      * object to avoid it being garbage collected.  The LogManager
1089      * may only retain a weak reference.
1090      *
1091      * @param   logger the new logger.
1092      * @return  true if the argument logger was registered successfully,
1093      *          false if a logger of that name already exists.
1094      * @exception NullPointerException if the logger name is null.
1095      */
1096     public boolean addLogger(Logger logger) {
1097         final String name = logger.getName();
1098         if (name == null) {
1099             throw new NullPointerException();
1100         }
1101         drainLoggerRefQueueBounded();
1102         LoggerContext cx = getUserContext();
1103         if (cx.addLocalLogger(logger)) {
1104             // Do we have a per logger handler too?
1105             // Note: this will add a 200ms penalty
1106             loadLoggerHandlers(logger, name, name + ".handlers");
1107             return true;
1108         } else {
1109             return false;
1110         }
1111     }
1112 
1113     // Private method to set a level on a logger.
1114     // If necessary, we raise privilege before doing the call.
1115     private static void doSetLevel(final Logger logger, final Level level) {
1116         SecurityManager sm = System.getSecurityManager();
1117         if (sm == null) {
1118             // There is no security manager, so things are easy.
1119             logger.setLevel(level);
1120             return;
1121         }
1122         // There is a security manager.  Raise privilege before
1123         // calling setLevel.
1124         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1125             @Override
1126             public Object run() {
1127                 logger.setLevel(level);
1128                 return null;
1129             }});
1130     }
1131 
1132     // Private method to set a parent on a logger.
1133     // If necessary, we raise privilege before doing the setParent call.
1134     private static void doSetParent(final Logger logger, final Logger parent) {
1135         SecurityManager sm = System.getSecurityManager();
1136         if (sm == null) {
1137             // There is no security manager, so things are easy.
1138             logger.setParent(parent);
1139             return;
1140         }
1141         // There is a security manager.  Raise privilege before
1142         // calling setParent.
1143         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1144             @Override
1145             public Object run() {
1146                 logger.setParent(parent);
1147                 return null;
1148             }});
1149     }
1150 
1151     /**
1152      * Method to find a named logger.
1153      * <p>
1154      * Note that since untrusted code may create loggers with
1155      * arbitrary names this method should not be relied on to
1156      * find Loggers for security sensitive logging.
1157      * It is also important to note that the Logger associated with the
1158      * String {@code name} may be garbage collected at any time if there
1159      * is no strong reference to the Logger. The caller of this method
1160      * must check the return value for null in order to properly handle
1161      * the case where the Logger has been garbage collected.
1162      * <p>
1163      * @param name name of the logger
1164      * @return  matching logger or null if none is found
1165      */
1166     public Logger getLogger(String name) {
1167         return getUserContext().findLogger(name);
1168     }
1169 
1170     /**
1171      * Get an enumeration of known logger names.
1172      * <p>
1173      * Note:  Loggers may be added dynamically as new classes are loaded.
1174      * This method only reports on the loggers that are currently registered.
1175      * It is also important to note that this method only returns the name
1176      * of a Logger, not a strong reference to the Logger itself.
1177      * The returned String does nothing to prevent the Logger from being
1178      * garbage collected. In particular, if the returned name is passed
1179      * to {@code LogManager.getLogger()}, then the caller must check the
1180      * return value from {@code LogManager.getLogger()} for null to properly
1181      * handle the case where the Logger has been garbage collected in the
1182      * time since its name was returned by this method.
1183      * <p>
1184      * @return  enumeration of logger name strings
1185      */
1186     public Enumeration<String> getLoggerNames() {
1187         return getUserContext().getLoggerNames();
1188     }
1189 
1190     /**
1191      * Reinitialize the logging properties and reread the logging configuration.
1192      * <p>
1193      * The same rules are used for locating the configuration properties
1194      * as are used at startup.  So normally the logging properties will
1195      * be re-read from the same file that was used at startup.
1196      * <P>
1197      * Any log level definitions in the new configuration file will be
1198      * applied using Logger.setLevel(), if the target Logger exists.
1199      * <p>
1200      * A PropertyChangeEvent will be fired after the properties are read.
1201      *
1202      * @exception  SecurityException  if a security manager exists and if
1203      *             the caller does not have LoggingPermission("control").
1204      * @exception  IOException if there are IO problems reading the configuration.
1205      */
1206     public void readConfiguration() throws IOException, SecurityException {
1207         checkPermission();
1208 
1209         // if a configuration class is specified, load it and use it.
1210         String cname = System.getProperty("java.util.logging.config.class");
1211         if (cname != null) {
1212             try {
1213                 // Instantiate the named class.  It is its constructor's
1214                 // responsibility to initialize the logging configuration, by
1215                 // calling readConfiguration(InputStream) with a suitable stream.
1216                 try {
1217                     Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
1218                     clz.newInstance();
1219                     return;
1220                 } catch (ClassNotFoundException ex) {
1221                     Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
1222                     clz.newInstance();
1223                     return;
1224                 }
1225             } catch (Exception ex) {
1226                 System.err.println("Logging configuration class \"" + cname + "\" failed");
1227                 System.err.println("" + ex);
1228                 // keep going and useful config file.
1229             }
1230         }
1231 
1232         String fname = System.getProperty("java.util.logging.config.file");
1233         if (fname == null) {
1234             fname = System.getProperty("java.home");
1235             if (fname == null) {
1236                 throw new Error("Can't find java.home ??");
1237             }
1238             File f = new File(fname, "lib");
1239             f = new File(f, "logging.properties");
1240             fname = f.getCanonicalPath();
1241         }
1242         try (final InputStream in = new FileInputStream(fname)) {
1243             final BufferedInputStream bin = new BufferedInputStream(in);
1244             readConfiguration(bin);
1245         }
1246     }
1247 
1248     /**
1249      * Reset the logging configuration.
1250      * <p>
1251      * For all named loggers, the reset operation removes and closes
1252      * all Handlers and (except for the root logger) sets the level
1253      * to null.  The root logger's level is set to Level.INFO.
1254      *
1255      * @exception  SecurityException  if a security manager exists and if
1256      *             the caller does not have LoggingPermission("control").
1257      */
1258 
1259     public void reset() throws SecurityException {
1260         checkPermission();
1261         synchronized (this) {
1262             props = new Properties();
1263             // Since we are doing a reset we no longer want to initialize
1264             // the global handlers, if they haven't been initialized yet.
1265             initializedGlobalHandlers = true;
1266         }
1267         for (LoggerContext cx : contexts()) {
1268             Enumeration<String> enum_ = cx.getLoggerNames();
1269             while (enum_.hasMoreElements()) {
1270                 String name = enum_.nextElement();
1271                 Logger logger = cx.findLogger(name);
1272                 if (logger != null) {
1273                     resetLogger(logger);
1274                 }
1275             }
1276         }
1277     }
1278 
1279     // Private method to reset an individual target logger.
1280     private void resetLogger(Logger logger) {
1281         // Close all the Logger's handlers.
1282         Handler[] targets = logger.getHandlers();
1283         for (int i = 0; i < targets.length; i++) {
1284             Handler h = targets[i];
1285             logger.removeHandler(h);
1286             try {
1287                 h.close();
1288             } catch (Exception ex) {
1289                 // Problems closing a handler?  Keep going...
1290             }
1291         }
1292         String name = logger.getName();
1293         if (name != null && name.equals("")) {
1294             // This is the root logger.
1295             logger.setLevel(defaultLevel);
1296         } else {
1297             logger.setLevel(null);
1298         }
1299     }
1300 
1301     // get a list of whitespace separated classnames from a property.
1302     private String[] parseClassNames(String propertyName) {
1303         String hands = getProperty(propertyName);
1304         if (hands == null) {
1305             return new String[0];
1306         }
1307         hands = hands.trim();
1308         int ix = 0;
1309         final List<String> result = new ArrayList<>();
1310         while (ix < hands.length()) {
1311             int end = ix;
1312             while (end < hands.length()) {
1313                 if (Character.isWhitespace(hands.charAt(end))) {
1314                     break;
1315                 }
1316                 if (hands.charAt(end) == ',') {
1317                     break;
1318                 }
1319                 end++;
1320             }
1321             String word = hands.substring(ix, end);
1322             ix = end+1;
1323             word = word.trim();
1324             if (word.length() == 0) {
1325                 continue;
1326             }
1327             result.add(word);
1328         }
1329         return result.toArray(new String[result.size()]);
1330     }
1331 
1332     /**
1333      * Reinitialize the logging properties and reread the logging configuration
1334      * from the given stream, which should be in java.util.Properties format.
1335      * A PropertyChangeEvent will be fired after the properties are read.
1336      * <p>
1337      * Any log level definitions in the new configuration file will be
1338      * applied using Logger.setLevel(), if the target Logger exists.
1339      *
1340      * @param ins       stream to read properties from
1341      * @exception  SecurityException  if a security manager exists and if
1342      *             the caller does not have LoggingPermission("control").
1343      * @exception  IOException if there are problems reading from the stream.
1344      */
1345     public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1346         checkPermission();
1347         reset();
1348 
1349         // Load the properties
1350         props.load(ins);
1351         // Instantiate new configuration objects.
1352         String names[] = parseClassNames("config");
1353 
1354         for (int i = 0; i < names.length; i++) {
1355             String word = names[i];
1356             try {
1357                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
1358                 clz.newInstance();
1359             } catch (Exception ex) {
1360                 System.err.println("Can't load config class \"" + word + "\"");
1361                 System.err.println("" + ex);
1362                 // ex.printStackTrace();
1363             }
1364         }
1365 
1366         // Set levels on any pre-existing loggers, based on the new properties.
1367         setLevelsOnExistingLoggers();
1368 
1369         // Notify any interested parties that our properties have changed.
1370         // We first take a copy of the listener map so that we aren't holding any
1371         // locks when calling the listeners.
1372         Map<Object,Integer> listeners = null;
1373         synchronized (listenerMap) {
1374             if (!listenerMap.isEmpty())
1375                 listeners = new HashMap<>(listenerMap);
1376         }
1377         if (listeners != null) {
1378             assert Beans.isBeansPresent();
1379             Object ev = Beans.newPropertyChangeEvent(LogManager.class, null, null, null);
1380             for (Map.Entry<Object,Integer> entry : listeners.entrySet()) {
1381                 Object listener = entry.getKey();
1382                 int count = entry.getValue().intValue();
1383                 for (int i = 0; i < count; i++) {
1384                     Beans.invokePropertyChange(listener, ev);
1385                 }
1386             }
1387         }
1388 
1389 
1390         // Note that we need to reinitialize global handles when
1391         // they are first referenced.
1392         synchronized (this) {
1393             initializedGlobalHandlers = false;
1394         }
1395     }
1396 
1397     /**
1398      * Get the value of a logging property.
1399      * The method returns null if the property is not found.
1400      * @param name      property name
1401      * @return          property value
1402      */
1403     public String getProperty(String name) {
1404         return props.getProperty(name);
1405     }
1406 
1407     // Package private method to get a String property.
1408     // If the property is not defined we return the given
1409     // default value.
1410     String getStringProperty(String name, String defaultValue) {
1411         String val = getProperty(name);
1412         if (val == null) {
1413             return defaultValue;
1414         }
1415         return val.trim();
1416     }
1417 
1418     // Package private method to get an integer property.
1419     // If the property is not defined or cannot be parsed
1420     // we return the given default value.
1421     int getIntProperty(String name, int defaultValue) {
1422         String val = getProperty(name);
1423         if (val == null) {
1424             return defaultValue;
1425         }
1426         try {
1427             return Integer.parseInt(val.trim());
1428         } catch (Exception ex) {
1429             return defaultValue;
1430         }
1431     }
1432 
1433     // Package private method to get a boolean property.
1434     // If the property is not defined or cannot be parsed
1435     // we return the given default value.
1436     boolean getBooleanProperty(String name, boolean defaultValue) {
1437         String val = getProperty(name);
1438         if (val == null) {
1439             return defaultValue;
1440         }
1441         val = val.toLowerCase();
1442         if (val.equals("true") || val.equals("1")) {
1443             return true;
1444         } else if (val.equals("false") || val.equals("0")) {
1445             return false;
1446         }
1447         return defaultValue;
1448     }
1449 
1450     // Package private method to get a Level property.
1451     // If the property is not defined or cannot be parsed
1452     // we return the given default value.
1453     Level getLevelProperty(String name, Level defaultValue) {
1454         String val = getProperty(name);
1455         if (val == null) {
1456             return defaultValue;
1457         }
1458         Level l = Level.findLevel(val.trim());
1459         return l != null ? l : defaultValue;
1460     }
1461 
1462     // Package private method to get a filter property.
1463     // We return an instance of the class named by the "name"
1464     // property. If the property is not defined or has problems
1465     // we return the defaultValue.
1466     Filter getFilterProperty(String name, Filter defaultValue) {
1467         String val = getProperty(name);
1468         try {
1469             if (val != null) {
1470                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
1471                 return (Filter) clz.newInstance();
1472             }
1473         } catch (Exception ex) {
1474             // We got one of a variety of exceptions in creating the
1475             // class or creating an instance.
1476             // Drop through.
1477         }
1478         // We got an exception.  Return the defaultValue.
1479         return defaultValue;
1480     }
1481 
1482 
1483     // Package private method to get a formatter property.
1484     // We return an instance of the class named by the "name"
1485     // property. If the property is not defined or has problems
1486     // we return the defaultValue.
1487     Formatter getFormatterProperty(String name, Formatter defaultValue) {
1488         String val = getProperty(name);
1489         try {
1490             if (val != null) {
1491                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
1492                 return (Formatter) clz.newInstance();
1493             }
1494         } catch (Exception ex) {
1495             // We got one of a variety of exceptions in creating the
1496             // class or creating an instance.
1497             // Drop through.
1498         }
1499         // We got an exception.  Return the defaultValue.
1500         return defaultValue;
1501     }
1502 
1503     // Private method to load the global handlers.
1504     // We do the real work lazily, when the global handlers
1505     // are first used.
1506     private synchronized void initializeGlobalHandlers() {
1507         if (initializedGlobalHandlers) {
1508             return;
1509         }
1510 
1511         initializedGlobalHandlers = true;
1512 
1513         if (deathImminent) {
1514             // Aaargh...
1515             // The VM is shutting down and our exit hook has been called.
1516             // Avoid allocating global handlers.
1517             return;
1518         }
1519         loadLoggerHandlers(rootLogger, null, "handlers");
1520     }
1521 
1522     private final Permission controlPermission = new LoggingPermission("control", null);
1523 
1524     void checkPermission() {
1525         SecurityManager sm = System.getSecurityManager();
1526         if (sm != null)
1527             sm.checkPermission(controlPermission);
1528     }
1529 
1530     /**
1531      * Check that the current context is trusted to modify the logging
1532      * configuration.  This requires LoggingPermission("control").
1533      * <p>
1534      * If the check fails we throw a SecurityException, otherwise
1535      * we return normally.
1536      *
1537      * @exception  SecurityException  if a security manager exists and if
1538      *             the caller does not have LoggingPermission("control").
1539      */
1540     public void checkAccess() throws SecurityException {
1541         checkPermission();
1542     }
1543 
1544     // Nested class to represent a node in our tree of named loggers.
1545     private static class LogNode {
1546         HashMap<String,LogNode> children;
1547         LoggerWeakRef loggerRef;
1548         LogNode parent;
1549         final LoggerContext context;
1550 
1551         LogNode(LogNode parent, LoggerContext context) {
1552             this.parent = parent;
1553             this.context = context;
1554         }
1555 
1556         // Recursive method to walk the tree below a node and set
1557         // a new parent logger.
1558         void walkAndSetParent(Logger parent) {
1559             if (children == null) {
1560                 return;
1561             }
1562             Iterator<LogNode> values = children.values().iterator();
1563             while (values.hasNext()) {
1564                 LogNode node = values.next();
1565                 LoggerWeakRef ref = node.loggerRef;
1566                 Logger logger = (ref == null) ? null : ref.get();
1567                 if (logger == null) {
1568                     node.walkAndSetParent(parent);
1569                 } else {
1570                     doSetParent(logger, parent);
1571                 }
1572             }
1573         }
1574     }
1575 
1576     // We use a subclass of Logger for the root logger, so
1577     // that we only instantiate the global handlers when they
1578     // are first needed.
1579     private final class RootLogger extends Logger {
1580         private RootLogger() {
1581             // We do not call the protected Logger two args constructor here,
1582             // to avoid calling LogManager.getLogManager() from within the
1583             // RootLogger constructor.
1584             super("", null, null, LogManager.this);
1585             setLevel(defaultLevel);
1586         }
1587 
1588         @Override
1589         public void log(LogRecord record) {
1590             // Make sure that the global handlers have been instantiated.
1591             initializeGlobalHandlers();
1592             super.log(record);
1593         }
1594 
1595         @Override
1596         public void addHandler(Handler h) {
1597             initializeGlobalHandlers();
1598             super.addHandler(h);
1599         }
1600 
1601         @Override
1602         public void removeHandler(Handler h) {
1603             initializeGlobalHandlers();
1604             super.removeHandler(h);
1605         }
1606 
1607         @Override
1608         public Handler[] getHandlers() {
1609             initializeGlobalHandlers();
1610             return super.getHandlers();
1611         }
1612     }
1613 
1614 
1615     // Private method to be called when the configuration has
1616     // changed to apply any level settings to any pre-existing loggers.
1617     synchronized private void setLevelsOnExistingLoggers() {
1618         Enumeration<?> enum_ = props.propertyNames();
1619         while (enum_.hasMoreElements()) {
1620             String key = (String)enum_.nextElement();
1621             if (!key.endsWith(".level")) {
1622                 // Not a level definition.
1623                 continue;
1624             }
1625             int ix = key.length() - 6;
1626             String name = key.substring(0, ix);
1627             Level level = getLevelProperty(key, null);
1628             if (level == null) {
1629                 System.err.println("Bad level value for property: " + key);
1630                 continue;
1631             }
1632             for (LoggerContext cx : contexts()) {
1633                 Logger l = cx.findLogger(name);
1634                 if (l == null) {
1635                     continue;
1636                 }
1637                 l.setLevel(level);
1638             }
1639         }
1640     }
1641 
1642     // Management Support
1643     private static LoggingMXBean loggingMXBean = null;
1644     /**
1645      * String representation of the
1646      * {@link javax.management.ObjectName} for the management interface
1647      * for the logging facility.
1648      *
1649      * @see java.lang.management.PlatformLoggingMXBean
1650      * @see java.util.logging.LoggingMXBean
1651      *
1652      * @since 1.5
1653      */
1654     public final static String LOGGING_MXBEAN_NAME
1655         = "java.util.logging:type=Logging";
1656 
1657     /**
1658      * Returns <tt>LoggingMXBean</tt> for managing loggers.
1659      * An alternative way to manage loggers is through the
1660      * {@link java.lang.management.PlatformLoggingMXBean} interface
1661      * that can be obtained by calling:
1662      * <pre>
1663      *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
1664      *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
1665      * </pre>
1666      *
1667      * @return a {@link LoggingMXBean} object.
1668      *
1669      * @see java.lang.management.PlatformLoggingMXBean
1670      * @since 1.5
1671      */
1672     public static synchronized LoggingMXBean getLoggingMXBean() {
1673         if (loggingMXBean == null) {
1674             loggingMXBean =  new Logging();
1675         }
1676         return loggingMXBean;
1677     }
1678 
1679     /**
1680      * A class that provides access to the java.beans.PropertyChangeListener
1681      * and java.beans.PropertyChangeEvent without creating a static dependency
1682      * on java.beans. This class can be removed once the addPropertyChangeListener
1683      * and removePropertyChangeListener methods are removed.
1684      */
1685     private static class Beans {
1686         private static final Class<?> propertyChangeListenerClass =
1687             getClass("java.beans.PropertyChangeListener");
1688 
1689         private static final Class<?> propertyChangeEventClass =
1690             getClass("java.beans.PropertyChangeEvent");
1691 
1692         private static final Method propertyChangeMethod =
1693             getMethod(propertyChangeListenerClass,
1694                       "propertyChange",
1695                       propertyChangeEventClass);
1696 
1697         private static final Constructor<?> propertyEventCtor =
1698             getConstructor(propertyChangeEventClass,
1699                            Object.class,
1700                            String.class,
1701                            Object.class,
1702                            Object.class);
1703 
1704         private static Class<?> getClass(String name) {
1705             try {
1706                 return Class.forName(name, true, Beans.class.getClassLoader());
1707             } catch (ClassNotFoundException e) {
1708                 return null;
1709             }
1710         }
1711         private static Constructor<?> getConstructor(Class<?> c, Class<?>... types) {
1712             try {
1713                 return (c == null) ? null : c.getDeclaredConstructor(types);
1714             } catch (NoSuchMethodException x) {
1715                 throw new AssertionError(x);
1716             }
1717         }
1718 
1719         private static Method getMethod(Class<?> c, String name, Class<?>... types) {
1720             try {
1721                 return (c == null) ? null : c.getMethod(name, types);
1722             } catch (NoSuchMethodException e) {
1723                 throw new AssertionError(e);
1724             }
1725         }
1726 
1727         /**
1728          * Returns {@code true} if java.beans is present.
1729          */
1730         static boolean isBeansPresent() {
1731             return propertyChangeListenerClass != null &&
1732                    propertyChangeEventClass != null;
1733         }
1734 
1735         /**
1736          * Returns a new PropertyChangeEvent with the given source, property
1737          * name, old and new values.
1738          */
1739         static Object newPropertyChangeEvent(Object source, String prop,
1740                                              Object oldValue, Object newValue)
1741         {
1742             try {
1743                 return propertyEventCtor.newInstance(source, prop, oldValue, newValue);
1744             } catch (InstantiationException | IllegalAccessException x) {
1745                 throw new AssertionError(x);
1746             } catch (InvocationTargetException x) {
1747                 Throwable cause = x.getCause();
1748                 if (cause instanceof Error)
1749                     throw (Error)cause;
1750                 if (cause instanceof RuntimeException)
1751                     throw (RuntimeException)cause;
1752                 throw new AssertionError(x);
1753             }
1754         }
1755 
1756         /**
1757          * Invokes the given PropertyChangeListener's propertyChange method
1758          * with the given event.
1759          */
1760         static void invokePropertyChange(Object listener, Object ev) {
1761             try {
1762                 propertyChangeMethod.invoke(listener, ev);
1763             } catch (IllegalAccessException x) {
1764                 throw new AssertionError(x);
1765             } catch (InvocationTargetException x) {
1766                 Throwable cause = x.getCause();
1767                 if (cause instanceof Error)
1768                     throw (Error)cause;
1769                 if (cause instanceof RuntimeException)
1770                     throw (RuntimeException)cause;
1771                 throw new AssertionError(x);
1772             }
1773         }
1774     }
1775 }