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