1 /*
   2  * Copyright (c) 2000, 2012, 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 
  31 /**
  32  * Stream based logging <tt>Handler</tt>.
  33  * <p>
  34  * This is primarily intended as a base class or support class to
  35  * be used in implementing other logging <tt>Handlers</tt>.
  36  * <p>
  37  * <tt>LogRecords</tt> are published to a given <tt>java.io.OutputStream</tt>.
  38  * <p>
  39  * <b>Configuration:</b>
  40  * By default each <tt>StreamHandler</tt> is initialized using the following
  41  * <tt>LogManager</tt> configuration properties where <tt>&lt;handler-name&gt;</tt>
  42  * refers to the fully-qualified class name of the handler.
  43  * If properties are not defined
  44  * (or have invalid values) then the specified default values are used.
  45  * <ul>
  46  * <li>   &lt;handler-name&gt;.level
  47  *        specifies the default level for the <tt>Handler</tt>
  48  *        (defaults to <tt>Level.INFO</tt>). </li>
  49  * <li>   &lt;handler-name&gt;.filter
  50  *        specifies the name of a <tt>Filter</tt> class to use
  51  *         (defaults to no <tt>Filter</tt>). </li>
  52  * <li>   &lt;handler-name&gt;.formatter
  53  *        specifies the name of a <tt>Formatter</tt> class to use
  54  *        (defaults to <tt>java.util.logging.SimpleFormatter</tt>). </li>
  55  * <li>   &lt;handler-name&gt;.encoding
  56  *        the name of the character set encoding to use (defaults to
  57  *        the default platform encoding). </li>
  58  * </ul>
  59  * <p>
  60  * For example, the properties for {@code StreamHandler} would be:
  61  * <ul>
  62  * <li>   java.util.logging.StreamHandler.level=INFO </li>
  63  * <li>   java.util.logging.StreamHandler.formatter=java.util.logging.SimpleFormatter </li>
  64  * </ul>
  65  * <p>
  66  * For a custom handler, e.g. com.foo.MyHandler, the properties would be:
  67  * <ul>
  68  * <li>   com.foo.MyHandler.level=INFO </li>
  69  * <li>   com.foo.MyHandler.formatter=java.util.logging.SimpleFormatter </li>
  70  * </ul>
  71  * <p>
  72  * @since 1.4
  73  */
  74 
  75 public class StreamHandler extends Handler {
  76     private OutputStream output;
  77     private boolean doneHeader;
  78     private volatile Writer writer;
  79 
  80     // Private method to configure a StreamHandler from LogManager
  81     // properties and/or default values as specified in the class
  82     // javadoc.
  83     private void configure() {
  84         LogManager manager = LogManager.getLogManager();
  85         String cname = getClass().getName();
  86 
  87         setLevel(manager.getLevelProperty(cname +".level", Level.INFO));
  88         setFilter(manager.getFilterProperty(cname +".filter", null));
  89         setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter()));
  90         try {
  91             setEncoding(manager.getStringProperty(cname +".encoding", null));
  92         } catch (Exception ex) {
  93             try {
  94                 setEncoding(null);
  95             } catch (Exception ex2) {
  96                 // doing a setEncoding with null should always work.
  97                 // assert false;
  98             }
  99         }
 100     }
 101 
 102     // Package private support for security checking.  When isSealed
 103     // returns true, we access check updates to the class.
 104     // Initially the value is false, but we set to true at end of
 105     // each constructor...
 106     private final boolean sealed;
 107 
 108     @Override
 109     boolean isSealed() {
 110         return sealed;
 111     }
 112 
 113     /**
 114      * Create a <tt>StreamHandler</tt>, with no current output stream.
 115      */
 116     public StreamHandler() {
 117         configure();
 118         sealed = true;
 119     }
 120 
 121     /**
 122      * Create a <tt>StreamHandler</tt> with a given <tt>Formatter</tt>
 123      * and output stream.
 124      * <p>
 125      * @param out         the target output stream
 126      * @param formatter   Formatter to be used to format output
 127      */
 128     public StreamHandler(OutputStream out, Formatter formatter) {
 129         configure();
 130         setFormatter(formatter);
 131         setOutputStream(out);
 132         sealed = true;
 133     }
 134 
 135     /**
 136      * Change the output stream.
 137      * <P>
 138      * If there is a current output stream then the <tt>Formatter</tt>'s
 139      * tail string is written and the stream is flushed and closed.
 140      * Then the output stream is replaced with the new output stream.
 141      *
 142      * @param out   New output stream.  May not be null.
 143      * @exception  SecurityException  if a security manager exists and if
 144      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 145      */
 146     protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
 147         if (out == null) {
 148             throw new NullPointerException();
 149         }
 150         flushAndClose();
 151         output = out;
 152         doneHeader = false;
 153         String encoding = getEncoding();
 154         if (encoding == null) {
 155             writer = new OutputStreamWriter(output);
 156         } else {
 157             try {
 158                 writer = new OutputStreamWriter(output, encoding);
 159             } catch (UnsupportedEncodingException ex) {
 160                 // This shouldn't happen.  The setEncoding method
 161                 // should have validated that the encoding is OK.
 162                 throw new Error("Unexpected exception " + ex);
 163             }
 164         }
 165     }
 166 
 167     /**
 168      * Set (or change) the character encoding used by this <tt>Handler</tt>.
 169      * <p>
 170      * The encoding should be set before any <tt>LogRecords</tt> are written
 171      * to the <tt>Handler</tt>.
 172      *
 173      * @param encoding  The name of a supported character encoding.
 174      *        May be null, to indicate the default platform encoding.
 175      * @exception  SecurityException  if a security manager exists and if
 176      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 177      * @exception  UnsupportedEncodingException if the named encoding is
 178      *          not supported.
 179      */
 180     @Override
 181     public synchronized void setEncoding(String encoding)
 182                         throws SecurityException, java.io.UnsupportedEncodingException {
 183         super.setEncoding(encoding);
 184         if (output == null) {
 185             return;
 186         }
 187         // Replace the current writer with a writer for the new encoding.
 188         flush();
 189         if (encoding == null) {
 190             writer = new OutputStreamWriter(output);
 191         } else {
 192             writer = new OutputStreamWriter(output, encoding);
 193         }
 194     }
 195 
 196     /**
 197      * Format and publish a <tt>LogRecord</tt>.
 198      * <p>
 199      * The <tt>StreamHandler</tt> first checks if there is an <tt>OutputStream</tt>
 200      * and if the given <tt>LogRecord</tt> has at least the required log level.
 201      * If not it silently returns.  If so, it calls any associated
 202      * <tt>Filter</tt> to check if the record should be published.  If so,
 203      * it calls its <tt>Formatter</tt> to format the record and then writes
 204      * the result to the current output stream.
 205      * <p>
 206      * If this is the first <tt>LogRecord</tt> to be written to a given
 207      * <tt>OutputStream</tt>, the <tt>Formatter</tt>'s "head" string is
 208      * written to the stream before the <tt>LogRecord</tt> is written.
 209      *
 210      * @param  record  description of the log event. A null record is
 211      *                 silently ignored and is not published
 212      */
 213     @Override
 214     public synchronized void publish(LogRecord record) {
 215         if (!isLoggable(record)) {
 216             return;
 217         }
 218         String msg;
 219         try {
 220             msg = getFormatter().format(record);
 221         } catch (Exception ex) {
 222             // We don't want to throw an exception here, but we
 223             // report the exception to any registered ErrorManager.
 224             reportError(null, ex, ErrorManager.FORMAT_FAILURE);
 225             return;
 226         }
 227 
 228         try {
 229             if (!doneHeader) {
 230                 writer.write(getFormatter().getHead(this));
 231                 doneHeader = true;
 232             }
 233             writer.write(msg);
 234         } catch (Exception ex) {
 235             // We don't want to throw an exception here, but we
 236             // report the exception to any registered ErrorManager.
 237             reportError(null, ex, ErrorManager.WRITE_FAILURE);
 238         }
 239     }
 240 
 241 
 242     /**
 243      * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>.
 244      * <p>
 245      * This method checks if the <tt>LogRecord</tt> has an appropriate level and
 246      * whether it satisfies any <tt>Filter</tt>.  It will also return false if
 247      * no output stream has been assigned yet or the LogRecord is null.
 248      * <p>
 249      * @param record  a <tt>LogRecord</tt>
 250      * @return true if the <tt>LogRecord</tt> would be logged.
 251      *
 252      */
 253     @Override
 254     public boolean isLoggable(LogRecord record) {
 255         if (writer == null || record == null) {
 256             return false;
 257         }
 258         return super.isLoggable(record);
 259     }
 260 
 261     /**
 262      * Flush any buffered messages.
 263      */
 264     @Override
 265     public synchronized void flush() {
 266         if (writer != null) {
 267             try {
 268                 writer.flush();
 269             } catch (Exception ex) {
 270                 // We don't want to throw an exception here, but we
 271                 // report the exception to any registered ErrorManager.
 272                 reportError(null, ex, ErrorManager.FLUSH_FAILURE);
 273             }
 274         }
 275     }
 276 
 277     private synchronized void flushAndClose() throws SecurityException {
 278         checkPermission();
 279         if (writer != null) {
 280             try {
 281                 if (!doneHeader) {
 282                     writer.write(getFormatter().getHead(this));
 283                     doneHeader = true;
 284                 }
 285                 writer.write(getFormatter().getTail(this));
 286                 writer.flush();
 287                 writer.close();
 288             } catch (Exception ex) {
 289                 // We don't want to throw an exception here, but we
 290                 // report the exception to any registered ErrorManager.
 291                 reportError(null, ex, ErrorManager.CLOSE_FAILURE);
 292             }
 293             writer = null;
 294             output = null;
 295         }
 296     }
 297 
 298     /**
 299      * Close the current output stream.
 300      * <p>
 301      * The <tt>Formatter</tt>'s "tail" string is written to the stream before it
 302      * is closed.  In addition, if the <tt>Formatter</tt>'s "head" string has not
 303      * yet been written to the stream, it will be written before the
 304      * "tail" string.
 305      *
 306      * @exception  SecurityException  if a security manager exists and if
 307      *             the caller does not have LoggingPermission("control").
 308      */
 309     @Override
 310     public synchronized void close() throws SecurityException {
 311         flushAndClose();
 312     }
 313 }