1 /*
   2  * Copyright (c) 2015, 2016, 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 jdk.internal.logger;
  27 
  28 import java.lang.ref.Reference;
  29 import java.lang.ref.WeakReference;
  30 import java.util.HashMap;
  31 import java.util.Map;
  32 import java.util.function.Function;
  33 import java.util.Objects;
  34 import java.lang.System.LoggerFinder;
  35 import java.lang.System.Logger;
  36 import java.lang.ref.ReferenceQueue;
  37 import java.lang.reflect.Module;
  38 import java.security.AccessController;
  39 import java.security.PrivilegedAction;
  40 import java.util.Collection;
  41 import java.util.ResourceBundle;
  42 
  43 /**
  44  * Internal Service Provider Interface (SPI) that makes it possible to use
  45  * {@code java.util.logging} as backend when the {@link
  46  * sun.util.logging.internal.LoggingProviderImpl
  47  * sun.util.logging.internal.LoggingProviderImpl} is present.
  48  * <p>
  49  * The JDK default implementation of the {@link LoggerFinder} will
  50  * attempt to locate and load an {@linkplain
  51  * java.util.ServiceLoader#loadInstalled(java.lang.Class) installed}
  52  * implementation of the {@code DefaultLoggerFinder}. If {@code java.util.logging}
  53  * is present, this will usually resolve to an instance of {@link
  54  * sun.util.logging.internal.LoggingProviderImpl sun.util.logging.internal.LoggingProviderImpl}.
  55  * Otherwise, if no concrete service provider is declared for
  56  * {@code DefaultLoggerFinder}, the default implementation provided by this class
  57  * will be used.
  58  * <p>
  59  * When the {@link sun.util.logging.internal.LoggingProviderImpl
  60  * sun.util.logging.internal.LoggingProviderImpl} is not present then the
  61  * default implementation provided by this class is to use a simple logger
  62  * that will log messages whose level is INFO and above to the console.
  63  * These simple loggers are not configurable.
  64  * <p>
  65  * When configuration is needed, an application should either link with
  66  * {@code java.util.logging} - and use the {@code java.util.logging} for
  67  * configuration, or link with {@link LoggerFinder another implementation}
  68  * of the {@link LoggerFinder}
  69  * that provides the necessary configuration.
  70  *
  71  * @apiNote Programmers are not expected to call this class directly.
  72  * Instead they should rely on the static methods defined by {@link
  73  * java.lang.System java.lang.System} or {@link sun.util.logging.PlatformLogger
  74  * sun.util.logging.PlatformLogger}.
  75  *
  76  * @see java.lang.System.LoggerFinder
  77  * @see jdk.internal.logger
  78  * @see sun.util.logging.internal
  79  *
  80  */
  81 public class DefaultLoggerFinder extends LoggerFinder {
  82 
  83     static final RuntimePermission LOGGERFINDER_PERMISSION =
  84                 new RuntimePermission("loggerFinder");
  85 
  86     /**
  87      * Creates a new instance of DefaultLoggerFinder.
  88      * @throws SecurityException if the calling code does not have the
  89      * {@code RuntimePermission("loggerFinder")}
  90      */
  91     protected DefaultLoggerFinder() {
  92         this(checkPermission());
  93     }
  94 
  95     private DefaultLoggerFinder(Void unused) {
  96         // nothing to do.
  97     }
  98 
  99     private static Void checkPermission() {
 100         final SecurityManager sm = System.getSecurityManager();
 101         if (sm != null) {
 102             sm.checkPermission(LOGGERFINDER_PERMISSION);
 103         }
 104         return null;
 105     }
 106 
 107     // SharedLoggers is a default cache of loggers used when JUL is not
 108     // present - in that case we use instances of SimpleConsoleLogger which
 109     // cannot be directly configure through public APIs.
 110     //
 111     // We can therefore afford to simply maintain two domains - one for the
 112     // system, and one for the application.
 113     //
 114     static final class SharedLoggers {
 115         private final Map<String, Reference<Logger>> loggers =
 116                 new HashMap<>();
 117         private final ReferenceQueue<Logger> queue = new ReferenceQueue<>();
 118 
 119         synchronized Logger get(Function<String, Logger> loggerSupplier, final String name) {
 120             Reference<? extends Logger> ref = loggers.get(name);
 121             Logger w = ref == null ? null :  ref.get();
 122             if (w == null) {
 123                 w = loggerSupplier.apply(name);
 124                 loggers.put(name, new WeakReference<>(w, queue));
 125             }
 126 
 127             // Remove stale mapping...
 128             Collection<Reference<Logger>> values = null;
 129             while ((ref = queue.poll()) != null) {
 130                 if (values == null) values = loggers.values();
 131                 values.remove(ref);
 132             }
 133             return w;
 134         }
 135 
 136         final static SharedLoggers system = new SharedLoggers();
 137         final static SharedLoggers application = new SharedLoggers();
 138     }
 139 
 140     public static boolean isSystem(Module m) {
 141         return AccessController.doPrivileged(new PrivilegedAction<>() {
 142             @Override
 143             public Boolean run() {
 144                 final ClassLoader moduleCL = m.getClassLoader();
 145                 if (moduleCL == null) return true;
 146                 ClassLoader cl = ClassLoader.getPlatformClassLoader();
 147                 while (cl != null && moduleCL != cl) {
 148                     cl = cl.getParent();
 149                 }
 150                 // returns true if moduleCL is the platform class loader
 151                 // or one of its ancestors.
 152                 return moduleCL == cl;
 153             }
 154         });
 155     }
 156 
 157     @Override
 158     public final Logger getLogger(String name,  Module module) {
 159         Objects.requireNonNull(name, "name");
 160         Objects.requireNonNull(module, "module");
 161         checkPermission();
 162         return demandLoggerFor(name, module);
 163     }
 164 
 165     @Override
 166     public final Logger getLocalizedLogger(String name, ResourceBundle bundle,
 167                                            Module module) {
 168         return super.getLocalizedLogger(name, bundle, module);
 169     }
 170 
 171     /**
 172      * Returns a {@link Logger logger} suitable for use within the
 173      * given {@code module}.
 174      *
 175      * @implSpec The default implementation for this method is to return a
 176      *    simple logger that will print all messages of INFO level and above
 177      *    to the console. That simple logger is not configurable.
 178      *
 179      * @param name The name of the logger.
 180      * @param module The module on behalf of which the logger is created.
 181      * @return A {@link Logger logger} suitable for the application usage.
 182      * @throws SecurityException if the calling code does not have the
 183      * {@code RuntimePermission("loggerFinder")}.
 184      */
 185     protected Logger demandLoggerFor(String name, Module module) {
 186         checkPermission();
 187         if (isSystem(module)) {
 188             return SharedLoggers.system.get(SimpleConsoleLogger::makeSimpleLogger, name);
 189         } else {
 190             return SharedLoggers.application.get(SimpleConsoleLogger::makeSimpleLogger, name);
 191         }
 192     }
 193 
 194 }