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     /**
 103      * Create a <tt>StreamHandler</tt>, with no current output stream.
 104      */
 105     public StreamHandler() {
 106         doWithControlPermission(this::configure);


 107     }
 108 
 109     /**
 110      * Create a <tt>StreamHandler</tt> with a given <tt>Formatter</tt>
 111      * and output stream.
 112      * <p>
 113      * @param out         the target output stream
 114      * @param formatter   Formatter to be used to format output
 115      */
 116     public StreamHandler(OutputStream out, Formatter formatter) {
 117         doWithControlPermission(() -> {
 118             configure();
 119             setFormatter(formatter);
 120             setOutputStream(out);
 121         });
 122     }
 123 
 124     /**
 125      * Change the output stream.
 126      * <P>
 127      * If there is a current output stream then the <tt>Formatter</tt>'s
 128      * tail string is written and the stream is flushed and closed.
 129      * Then the output stream is replaced with the new output stream.
 130      *
 131      * @param out   New output stream.  May not be null.
 132      * @exception  SecurityException  if a security manager exists and if
 133      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 134      */
 135     protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
 136         if (out == null) {
 137             throw new NullPointerException();
 138         }
 139         flushAndClose();
 140         output = out;
 141         doneHeader = false;
 142         String encoding = getEncoding();
 143         if (encoding == null) {
 144             writer = new OutputStreamWriter(output);
 145         } else {
 146             try {
 147                 writer = new OutputStreamWriter(output, encoding);
 148             } catch (UnsupportedEncodingException ex) {
 149                 // This shouldn't happen.  The setEncoding method
 150                 // should have validated that the encoding is OK.
 151                 throw new Error("Unexpected exception " + ex);
 152             }
 153         }
 154     }
 155 
 156     /**
 157      * Set (or change) the character encoding used by this <tt>Handler</tt>.
 158      * <p>
 159      * The encoding should be set before any <tt>LogRecords</tt> are written
 160      * to the <tt>Handler</tt>.
 161      *
 162      * @param encoding  The name of a supported character encoding.
 163      *        May be null, to indicate the default platform encoding.
 164      * @exception  SecurityException  if a security manager exists and if
 165      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 166      * @exception  UnsupportedEncodingException if the named encoding is
 167      *          not supported.
 168      */
 169     @Override
 170     public synchronized void setEncoding(String encoding)
 171                         throws SecurityException, java.io.UnsupportedEncodingException {
 172         super.setEncoding(encoding);
 173         if (output == null) {
 174             return;
 175         }
 176         // Replace the current writer with a writer for the new encoding.
 177         flush();
 178         if (encoding == null) {
 179             writer = new OutputStreamWriter(output);
 180         } else {
 181             writer = new OutputStreamWriter(output, encoding);
 182         }
 183     }
 184 
 185     /**
 186      * Format and publish a <tt>LogRecord</tt>.
 187      * <p>
 188      * The <tt>StreamHandler</tt> first checks if there is an <tt>OutputStream</tt>
 189      * and if the given <tt>LogRecord</tt> has at least the required log level.
 190      * If not it silently returns.  If so, it calls any associated
 191      * <tt>Filter</tt> to check if the record should be published.  If so,
 192      * it calls its <tt>Formatter</tt> to format the record and then writes
 193      * the result to the current output stream.
 194      * <p>
 195      * If this is the first <tt>LogRecord</tt> to be written to a given
 196      * <tt>OutputStream</tt>, the <tt>Formatter</tt>'s "head" string is
 197      * written to the stream before the <tt>LogRecord</tt> is written.
 198      *
 199      * @param  record  description of the log event. A null record is
 200      *                 silently ignored and is not published
 201      */
 202     @Override
 203     public synchronized void publish(LogRecord record) {
 204         if (!isLoggable(record)) {
 205             return;
 206         }
 207         String msg;
 208         try {
 209             msg = getFormatter().format(record);
 210         } catch (Exception ex) {
 211             // We don't want to throw an exception here, but we
 212             // report the exception to any registered ErrorManager.
 213             reportError(null, ex, ErrorManager.FORMAT_FAILURE);
 214             return;
 215         }
 216 
 217         try {
 218             if (!doneHeader) {
 219                 writer.write(getFormatter().getHead(this));
 220                 doneHeader = true;
 221             }
 222             writer.write(msg);
 223         } catch (Exception ex) {
 224             // We don't want to throw an exception here, but we
 225             // report the exception to any registered ErrorManager.
 226             reportError(null, ex, ErrorManager.WRITE_FAILURE);
 227         }
 228     }
 229 
 230 
 231     /**
 232      * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>.
 233      * <p>
 234      * This method checks if the <tt>LogRecord</tt> has an appropriate level and
 235      * whether it satisfies any <tt>Filter</tt>.  It will also return false if
 236      * no output stream has been assigned yet or the LogRecord is null.
 237      * <p>
 238      * @param record  a <tt>LogRecord</tt>
 239      * @return true if the <tt>LogRecord</tt> would be logged.
 240      *
 241      */
 242     @Override
 243     public boolean isLoggable(LogRecord record) {
 244         if (writer == null || record == null) {
 245             return false;
 246         }
 247         return super.isLoggable(record);
 248     }
 249 
 250     /**
 251      * Flush any buffered messages.
 252      */
 253     @Override
 254     public synchronized void flush() {
 255         if (writer != null) {
 256             try {
 257                 writer.flush();
 258             } catch (Exception ex) {
 259                 // We don't want to throw an exception here, but we
 260                 // report the exception to any registered ErrorManager.
 261                 reportError(null, ex, ErrorManager.FLUSH_FAILURE);
 262             }
 263         }
 264     }
 265 
 266     private synchronized void flushAndClose() throws SecurityException {
 267         checkPermission();
 268         if (writer != null) {
 269             try {
 270                 if (!doneHeader) {
 271                     writer.write(getFormatter().getHead(this));
 272                     doneHeader = true;
 273                 }
 274                 writer.write(getFormatter().getTail(this));
 275                 writer.flush();
 276                 writer.close();
 277             } catch (Exception ex) {
 278                 // We don't want to throw an exception here, but we
 279                 // report the exception to any registered ErrorManager.
 280                 reportError(null, ex, ErrorManager.CLOSE_FAILURE);
 281             }
 282             writer = null;
 283             output = null;
 284         }
 285     }
 286 
 287     /**
 288      * Close the current output stream.
 289      * <p>
 290      * The <tt>Formatter</tt>'s "tail" string is written to the stream before it
 291      * is closed.  In addition, if the <tt>Formatter</tt>'s "head" string has not
 292      * yet been written to the stream, it will be written before the
 293      * "tail" string.
 294      *
 295      * @exception  SecurityException  if a security manager exists and if
 296      *             the caller does not have LoggingPermission("control").
 297      */
 298     @Override
 299     public synchronized void close() throws SecurityException {
 300         flushAndClose();
 301     }
 302 }
--- EOF ---