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.UnsupportedEncodingException;
  30 import java.security.AccessController;
  31 import java.security.PrivilegedAction;
  32 
  33 /**
  34  * A <tt>Handler</tt> object takes log messages from a <tt>Logger</tt> and
  35  * exports them.  It might for example, write them to a console
  36  * or write them to a file, or send them to a network logging service,
  37  * or forward them to an OS log, or whatever.
  38  * <p>
  39  * A <tt>Handler</tt> can be disabled by doing a <tt>setLevel(Level.OFF)</tt>
  40  * and can  be re-enabled by doing a <tt>setLevel</tt> with an appropriate level.
  41  * <p>
  42  * <tt>Handler</tt> classes typically use <tt>LogManager</tt> properties to set
  43  * default values for the <tt>Handler</tt>'s <tt>Filter</tt>, <tt>Formatter</tt>,
  44  * and <tt>Level</tt>.  See the specific documentation for each concrete
  45  * <tt>Handler</tt> class.
  46  *
  47  *
  48  * @since 1.4
  49  */
  50 
  51 public abstract class Handler {
  52     private static final int offValue = Level.OFF.intValue();
  53     private final LogManager manager = LogManager.getLogManager();
  54 
  55     // We're using volatile here to avoid synchronizing getters, which
  56     // would prevent other threads from calling isLoggable()
  57     // while publish() is executing.
  58     // On the other hand, setters will be synchronized to exclude concurrent
  59     // execution with more complex methods, such as StreamHandler.publish().
  60     // We wouldn't want 'level' to be changed by another thread in the middle
  61     // of the execution of a 'publish' call.
  62     private volatile Filter filter;
  63     private volatile Formatter formatter;
  64     private volatile Level logLevel = Level.ALL;
  65     private volatile ErrorManager errorManager = new ErrorManager();
  66     private volatile String encoding;
  67 
  68     /**
  69      * Default constructor.  The resulting <tt>Handler</tt> has a log
  70      * level of <tt>Level.ALL</tt>, no <tt>Formatter</tt>, and no
  71      * <tt>Filter</tt>.  A default <tt>ErrorManager</tt> instance is installed
  72      * as the <tt>ErrorManager</tt>.
  73      */
  74     protected Handler() {
  75     }
  76 
  77     /**
  78      * Publish a <tt>LogRecord</tt>.
  79      * <p>
  80      * The logging request was made initially to a <tt>Logger</tt> object,
  81      * which initialized the <tt>LogRecord</tt> and forwarded it here.
  82      * <p>
  83      * The <tt>Handler</tt>  is responsible for formatting the message, when and
  84      * if necessary.  The formatting should include localization.
  85      *
  86      * @param  record  description of the log event. A null record is
  87      *                 silently ignored and is not published
  88      */
  89     public abstract void publish(LogRecord record);
  90 
  91     /**
  92      * Flush any buffered output.
  93      */
  94     public abstract void flush();
  95 
  96     /**
  97      * Close the <tt>Handler</tt> and free all associated resources.
  98      * <p>
  99      * The close method will perform a <tt>flush</tt> and then close the
 100      * <tt>Handler</tt>.   After close has been called this <tt>Handler</tt>
 101      * should no longer be used.  Method calls may either be silently
 102      * ignored or may throw runtime exceptions.
 103      *
 104      * @exception  SecurityException  if a security manager exists and if
 105      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 106      */
 107     public abstract void close() throws SecurityException;
 108 
 109     /**
 110      * Set a <tt>Formatter</tt>.  This <tt>Formatter</tt> will be used
 111      * to format <tt>LogRecords</tt> for this <tt>Handler</tt>.
 112      * <p>
 113      * Some <tt>Handlers</tt> may not use <tt>Formatters</tt>, in
 114      * which case the <tt>Formatter</tt> will be remembered, but not used.
 115      * <p>
 116      * @param newFormatter the <tt>Formatter</tt> to use (may not be null)
 117      * @exception  SecurityException  if a security manager exists and if
 118      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 119      */
 120     public synchronized void setFormatter(Formatter newFormatter) throws SecurityException {
 121         checkPermission();
 122         // Check for a null pointer:
 123         newFormatter.getClass();
 124         formatter = newFormatter;
 125     }
 126 
 127     /**
 128      * Return the <tt>Formatter</tt> for this <tt>Handler</tt>.
 129      * @return the <tt>Formatter</tt> (may be null).
 130      */
 131     public Formatter getFormatter() {
 132         return formatter;
 133     }
 134 
 135     /**
 136      * Set the character encoding used by this <tt>Handler</tt>.
 137      * <p>
 138      * The encoding should be set before any <tt>LogRecords</tt> are written
 139      * to the <tt>Handler</tt>.
 140      *
 141      * @param encoding  The name of a supported character encoding.
 142      *        May be null, to indicate the default platform encoding.
 143      * @exception  SecurityException  if a security manager exists and if
 144      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 145      * @exception  UnsupportedEncodingException if the named encoding is
 146      *          not supported.
 147      */
 148     public synchronized void setEncoding(String encoding)
 149                         throws SecurityException, java.io.UnsupportedEncodingException {
 150         checkPermission();
 151         if (encoding != null) {
 152             try {
 153                 if(!java.nio.charset.Charset.isSupported(encoding)) {
 154                     throw new UnsupportedEncodingException(encoding);
 155                 }
 156             } catch (java.nio.charset.IllegalCharsetNameException e) {
 157                 throw new UnsupportedEncodingException(encoding);
 158             }
 159         }
 160         this.encoding = encoding;
 161     }
 162 
 163     /**
 164      * Return the character encoding for this <tt>Handler</tt>.
 165      *
 166      * @return  The encoding name.  May be null, which indicates the
 167      *          default encoding should be used.
 168      */
 169     public String getEncoding() {
 170         return encoding;
 171     }
 172 
 173     /**
 174      * Set a <tt>Filter</tt> to control output on this <tt>Handler</tt>.
 175      * <P>
 176      * For each call of <tt>publish</tt> the <tt>Handler</tt> will call
 177      * this <tt>Filter</tt> (if it is non-null) to check if the
 178      * <tt>LogRecord</tt> should be published or discarded.
 179      *
 180      * @param   newFilter  a <tt>Filter</tt> object (may be null)
 181      * @exception  SecurityException  if a security manager exists and if
 182      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 183      */
 184     public synchronized void setFilter(Filter newFilter) throws SecurityException {
 185         checkPermission();
 186         filter = newFilter;
 187     }
 188 
 189     /**
 190      * Get the current <tt>Filter</tt> for this <tt>Handler</tt>.
 191      *
 192      * @return  a <tt>Filter</tt> object (may be null)
 193      */
 194     public Filter getFilter() {
 195         return filter;
 196     }
 197 
 198     /**
 199      * Define an ErrorManager for this Handler.
 200      * <p>
 201      * The ErrorManager's "error" method will be invoked if any
 202      * errors occur while using this Handler.
 203      *
 204      * @param em  the new ErrorManager
 205      * @exception  SecurityException  if a security manager exists and if
 206      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 207      */
 208     public synchronized void setErrorManager(ErrorManager em) {
 209         checkPermission();
 210         if (em == null) {
 211            throw new NullPointerException();
 212         }
 213         errorManager = em;
 214     }
 215 
 216     /**
 217      * Retrieves the ErrorManager for this Handler.
 218      *
 219      * @return the ErrorManager for this Handler
 220      * @exception  SecurityException  if a security manager exists and if
 221      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 222      */
 223     public ErrorManager getErrorManager() {
 224         checkPermission();
 225         return errorManager;
 226     }
 227 
 228    /**
 229      * Protected convenience method to report an error to this Handler's
 230      * ErrorManager.  Note that this method retrieves and uses the ErrorManager
 231      * without doing a security check.  It can therefore be used in
 232      * environments where the caller may be non-privileged.
 233      *
 234      * @param msg    a descriptive string (may be null)
 235      * @param ex     an exception (may be null)
 236      * @param code   an error code defined in ErrorManager
 237      */
 238     protected void reportError(String msg, Exception ex, int code) {
 239         try {
 240             errorManager.error(msg, ex, code);
 241         } catch (Exception ex2) {
 242             System.err.println("Handler.reportError caught:");
 243             ex2.printStackTrace();
 244         }
 245     }
 246 
 247     /**
 248      * Set the log level specifying which message levels will be
 249      * logged by this <tt>Handler</tt>.  Message levels lower than this
 250      * value will be discarded.
 251      * <p>
 252      * The intention is to allow developers to turn on voluminous
 253      * logging, but to limit the messages that are sent to certain
 254      * <tt>Handlers</tt>.
 255      *
 256      * @param newLevel   the new value for the log level
 257      * @exception  SecurityException  if a security manager exists and if
 258      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 259      */
 260     public synchronized void setLevel(Level newLevel) throws SecurityException {
 261         if (newLevel == null) {
 262             throw new NullPointerException();
 263         }
 264         checkPermission();
 265         logLevel = newLevel;
 266     }
 267 
 268     /**
 269      * Get the log level specifying which messages will be
 270      * logged by this <tt>Handler</tt>.  Message levels lower
 271      * than this level will be discarded.
 272      * @return  the level of messages being logged.
 273      */
 274     public Level getLevel() {
 275         return logLevel;
 276     }
 277 
 278     /**
 279      * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>.
 280      * <p>
 281      * This method checks if the <tt>LogRecord</tt> has an appropriate
 282      * <tt>Level</tt> and  whether it satisfies any <tt>Filter</tt>.  It also
 283      * may make other <tt>Handler</tt> specific checks that might prevent a
 284      * handler from logging the <tt>LogRecord</tt>. It will return false if
 285      * the <tt>LogRecord</tt> is null.
 286      * <p>
 287      * @param record  a <tt>LogRecord</tt>
 288      * @return true if the <tt>LogRecord</tt> would be logged.
 289      *
 290      */
 291     public boolean isLoggable(LogRecord record) {
 292         final int levelValue = getLevel().intValue();
 293         if (record.getLevel().intValue() < levelValue || levelValue == offValue) {
 294             return false;
 295         }
 296         final Filter filter = getFilter();
 297         if (filter == null) {
 298             return true;
 299         }
 300         return filter.isLoggable(record);
 301     }
 302 
 303     // Package-private support method for security checks.
 304     // We check that the caller has appropriate security privileges
 305     // to update Handler state and if not throw a SecurityException.
 306     void checkPermission() throws SecurityException {
 307         manager.checkPermission();
 308     }
 309 
 310     // Package-private support for executing actions with additional
 311     // LoggingPermission("control", null) permission.
 312     interface PrivilegedVoidAction extends PrivilegedAction<Void> {
 313         default Void run() { runVoid(); return null; }
 314         void runVoid();
 315     }
 316 
 317     void doWithControlPermission(PrivilegedVoidAction action) {
 318         AccessController.doPrivileged(action, null, LogManager.controlPermission);
 319     }
 320 }