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