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 import java.net.*;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 
  34 /**
  35  * Simple network logging <tt>Handler</tt>.
  36  * <p>
  37  * <tt>LogRecords</tt> are published to a network stream connection.  By default
  38  * the <tt>XMLFormatter</tt> class is used for formatting.
  39  * <p>
  40  * <b>Configuration:</b>
  41  * By default each <tt>SocketHandler</tt> is initialized using the following
  42  * <tt>LogManager</tt> configuration properties where <tt>&lt;handler-name&gt;</tt>
  43  * refers to the fully-qualified class name of the handler.
  44  * If properties are not defined
  45  * (or have invalid values) then the specified default values are used.
  46  * <ul>
  47  * <li>   &lt;handler-name&gt;.level
  48  *        specifies the default level for the <tt>Handler</tt>
  49  *        (defaults to <tt>Level.ALL</tt>). </li>
  50  * <li>   &lt;handler-name&gt;.filter
  51  *        specifies the name of a <tt>Filter</tt> class to use
  52  *        (defaults to no <tt>Filter</tt>). </li>
  53  * <li>   &lt;handler-name&gt;.formatter
  54  *        specifies the name of a <tt>Formatter</tt> class to use
  55  *        (defaults to <tt>java.util.logging.XMLFormatter</tt>). </li>
  56  * <li>   &lt;handler-name&gt;.encoding
  57  *        the name of the character set encoding to use (defaults to
  58  *        the default platform encoding). </li>
  59  * <li>   &lt;handler-name&gt;.host
  60  *        specifies the target host name to connect to (no default). </li>
  61  * <li>   &lt;handler-name&gt;.port
  62  *        specifies the target TCP port to use (no default). </li>
  63  * </ul>
  64  * <p>
  65  * For example, the properties for {@code SocketHandler} would be:
  66  * <ul>
  67  * <li>   java.util.logging.SocketHandler.level=INFO </li>
  68  * <li>   java.util.logging.SocketHandler.formatter=java.util.logging.SimpleFormatter </li>
  69  * </ul>
  70  * <p>
  71  * For a custom handler, e.g. com.foo.MyHandler, the properties would be:
  72  * <ul>
  73  * <li>   com.foo.MyHandler.level=INFO </li>
  74  * <li>   com.foo.MyHandler.formatter=java.util.logging.SimpleFormatter </li>
  75  * </ul>
  76  * <p>
  77  * The output IO stream is buffered, but is flushed after each
  78  * <tt>LogRecord</tt> is written.
  79  *
  80  * @since 1.4
  81  */
  82 
  83 public class SocketHandler extends StreamHandler {
  84     private Socket sock;
  85     private String host;
  86     private int port;
  87 
  88     // Private PrivilegedAction to configure a SocketHandler from LogManager
  89     // properties and/or default values as specified in the class
  90     // javadoc.
  91     private class ConfigureAction implements PrivilegedAction<Void> {
  92         @Override
  93         public Void run() {
  94             LogManager manager = LogManager.getLogManager();
  95             String cname = SocketHandler.this.getClass().getName();
  96 
  97             setLevel(manager.getLevelProperty(cname +".level", Level.ALL));
  98             setFilter(manager.getFilterProperty(cname +".filter", null));
  99             setFormatter(manager.getFormatterProperty(cname +".formatter", new XMLFormatter()));
 100             try {
 101                 setEncoding(manager.getStringProperty(cname +".encoding", null));
 102             } catch (Exception ex) {
 103                 try {
 104                     setEncoding(null);
 105                 } catch (Exception ex2) {
 106                     // doing a setEncoding with null should always work.
 107                     // assert false;
 108                 }
 109             }
 110             port = manager.getIntProperty(cname + ".port", 0);
 111             host = manager.getStringProperty(cname + ".host", null);
 112             return null;
 113         }
 114     }
 115 
 116     /**
 117      * Create a <tt>SocketHandler</tt>, using only <tt>LogManager</tt> properties
 118      * (or their defaults).
 119      * @throws IllegalArgumentException if the host or port are invalid or
 120      *          are not specified as LogManager properties.
 121      * @throws IOException if we are unable to connect to the target
 122      *         host and port.
 123      */
 124     public SocketHandler() throws IOException {
 125         // We are going to use the logging defaults.
 126         try {
 127             AccessController.doPrivileged(new ConfigureAction() {
 128                 @Override
 129                 public Void run() {
 130                     super.run();
 131                     try {
 132                         connect();
 133                     } catch (IOException ioe) {
 134                         throw new UncheckedIOException(ioe);
 135                     }
 136                     return null;
 137                 }
 138             }, null, LogManager.controlPermission);
 139         } catch (UncheckedIOException uioe) {
 140             System.err.println("SocketHandler: connect failed to " + host + ":" + port);
 141             throw uioe.getCause();
 142         }
 143     }
 144 
 145     /**
 146      * Construct a <tt>SocketHandler</tt> using a specified host and port.
 147      *
 148      * The <tt>SocketHandler</tt> is configured based on <tt>LogManager</tt>
 149      * properties (or their default values) except that the given target host
 150      * and port arguments are used. If the host argument is empty, but not
 151      * null String then the localhost is used.
 152      *
 153      * @param host target host.
 154      * @param port target port.
 155      *
 156      * @throws IllegalArgumentException if the host or port are invalid.
 157      * @throws IOException if we are unable to connect to the target
 158      *         host and port.
 159      */
 160     public SocketHandler(String host, int port) throws IOException {
 161         AccessController.doPrivileged(new ConfigureAction(), null, LogManager.controlPermission);
 162         this.port = port;
 163         this.host = host;
 164         connect();
 165     }
 166 
 167     private void connect() throws IOException {
 168         // Check the arguments are valid.
 169         if (port == 0) {
 170             throw new IllegalArgumentException("Bad port: " + port);
 171         }
 172         if (host == null) {
 173             throw new IllegalArgumentException("Null host name: " + host);
 174         }
 175 
 176         // Try to open a new socket.
 177         sock = new Socket(host, port);
 178         OutputStream out = sock.getOutputStream();
 179         BufferedOutputStream bout = new BufferedOutputStream(out);
 180         setOutputStream(bout);
 181     }
 182 
 183     /**
 184      * Close this output stream.
 185      *
 186      * @exception  SecurityException  if a security manager exists and if
 187      *             the caller does not have <tt>LoggingPermission("control")</tt>.
 188      */
 189     @Override
 190     public synchronized void close() throws SecurityException {
 191         super.close();
 192         if (sock != null) {
 193             try {
 194                 sock.close();
 195             } catch (IOException ix) {
 196                 // drop through.
 197             }
 198         }
 199         sock = null;
 200     }
 201 
 202     /**
 203      * Format and publish a <tt>LogRecord</tt>.
 204      *
 205      * @param  record  description of the log event. A null record is
 206      *                 silently ignored and is not published
 207      */
 208     @Override
 209     public synchronized void publish(LogRecord record) {
 210         if (!isLoggable(record)) {
 211             return;
 212         }
 213         super.publish(record);
 214         flush();
 215     }
 216 }