JAL-3032 adds Java 8 functionality (1/2)
[jalview.git] / srcjar2 / org / apache / log4j / net / TelnetAppender.java
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.apache.log4j.net;
19
20 import org.apache.log4j.AppenderSkeleton;
21 import org.apache.log4j.helpers.LogLog;
22 import org.apache.log4j.spi.LoggingEvent;
23
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.io.InterruptedIOException;
27 import java.net.ServerSocket;
28 import java.net.Socket;
29 import java.util.Enumeration;
30 import java.util.Iterator;
31 import java.util.Vector;
32
33 /**
34   <p>The TelnetAppender is a log4j appender that specializes in
35   writing to a read-only socket.  The output is provided in a
36   telnet-friendly way so that a log can be monitored over TCP/IP.
37   Clients using telnet connect to the socket and receive log data.
38   This is handy for remote monitoring, especially when monitoring a
39   servlet.
40
41   <p>Here is a list of the available configuration options:
42
43   <table border=1>
44    <tr>
45    <th>Name</th>
46    <th>Requirement</th>
47    <th>Description</th>
48    <th>Sample Value</th>
49    </tr>
50
51    <tr>
52    <td>Port</td>
53    <td>optional</td>
54    <td>This parameter determines the port to use for announcing log events.  The default port is 23 (telnet).</td>
55    <td>5875</td>
56    </table>
57
58    @author <a HREF="mailto:jay@v-wave.com">Jay Funnell</a>
59 */
60
61 public class TelnetAppender extends AppenderSkeleton {
62
63   private static final String EOL = "\r\n";
64   private SocketHandler sh;
65   private int port = 23;
66
67   /** 
68       This appender requires a layout to format the text to the
69       attached client(s). */
70   public boolean requiresLayout() {
71     return true;
72   }
73
74   /** all of the options have been set, create the socket handler and
75       wait for connections. */
76   public void activateOptions() {
77     try {
78       sh = new SocketHandler(port);
79       sh.start();
80     }
81     catch(InterruptedIOException e) {
82       Thread.currentThread().interrupt();
83       e.printStackTrace();
84     } catch(IOException e) {
85       e.printStackTrace();
86     } catch(RuntimeException e) {
87       e.printStackTrace();
88     }
89     super.activateOptions();
90   }
91
92   public
93   int getPort() {
94     return port;
95   }
96
97   public
98   void setPort(int port) {
99     this.port = port;
100   }
101
102
103   /** shuts down the appender. */
104   public void close() {
105     if (sh != null) {
106         sh.close();
107         try {
108             sh.join();
109         } catch(InterruptedException ex) {
110             Thread.currentThread().interrupt();
111         }
112     }
113   }
114
115   /** Handles a log event.  For this appender, that means writing the
116     message to each connected client.  */
117   protected void append(LoggingEvent event) {
118       if(sh != null) {
119         sh.send(layout.format(event));
120         if(layout.ignoresThrowable()) {
121             String[] s = event.getThrowableStrRep();
122             if (s != null) {
123                 StringBuffer buf = new StringBuffer();
124                 for(int i = 0; i < s.length; i++) {
125                     buf.append(s[i]);
126                     buf.append(EOL);
127                 }
128                 sh.send(buf.toString());
129             }
130         }
131       }
132   }
133
134   //---------------------------------------------------------- SocketHandler:
135
136   /** The SocketHandler class is used to accept connections from
137       clients.  It is threaded so that clients can connect/disconnect
138       asynchronously. */
139   protected class SocketHandler extends Thread {
140
141     private Vector writers = new Vector();
142     private Vector connections = new Vector();
143     private ServerSocket serverSocket;
144     private int MAX_CONNECTIONS = 20;
145
146     public void finalize() {
147         close();
148     }
149       
150     /** 
151     * make sure we close all network connections when this handler is destroyed.
152     * @since 1.2.15 
153     */
154     public void close() {
155       synchronized(this) {
156         for(Enumeration e = connections.elements();e.hasMoreElements();) {
157             try {
158                 ((Socket)e.nextElement()).close();
159             } catch(InterruptedIOException ex) {
160                 Thread.currentThread().interrupt();
161             } catch(IOException ex) {
162             } catch(RuntimeException ex) {
163             }
164         }
165       }
166
167       try {
168         serverSocket.close();
169       } catch(InterruptedIOException ex) {
170           Thread.currentThread().interrupt();
171       } catch(IOException ex) {
172       } catch(RuntimeException ex) {
173       }
174     }
175
176     /** sends a message to each of the clients in telnet-friendly output. */
177     public synchronized void send(final String message) {
178       Iterator ce = connections.iterator();
179       for(Iterator e = writers.iterator();e.hasNext();) {
180         ce.next();
181         PrintWriter writer = (PrintWriter)e.next();
182         writer.print(message);
183         if(writer.checkError()) {
184           ce.remove();
185           e.remove();
186         }
187       }
188     }
189
190     /** 
191         Continually accepts client connections.  Client connections
192         are refused when MAX_CONNECTIONS is reached. 
193     */
194     public void run() {
195       while(!serverSocket.isClosed()) {
196         try {
197           Socket newClient = serverSocket.accept();
198           PrintWriter pw = new PrintWriter(newClient.getOutputStream());
199           if(connections.size() < MAX_CONNECTIONS) {
200             synchronized(this) {
201                 connections.addElement(newClient);
202                 writers.addElement(pw);
203                 pw.print("TelnetAppender v1.0 (" + connections.size()
204                             + " active connections)" + EOL + EOL);
205                 pw.flush();
206             }
207           } else {
208             pw.print("Too many connections." + EOL);
209             pw.flush();
210             newClient.close();
211           }
212         } catch(Exception e) {
213           if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
214               Thread.currentThread().interrupt();
215           }
216           if (!serverSocket.isClosed()) {
217             LogLog.error("Encountered error while in SocketHandler loop.", e);
218           }
219           break;
220         }
221       }
222
223       try {
224           serverSocket.close();
225       } catch(InterruptedIOException ex) {
226           Thread.currentThread().interrupt();
227       } catch(IOException ex) {
228       }
229     }
230
231     public SocketHandler(int port) throws IOException {
232       serverSocket = new ServerSocket(port);
233       setName("TelnetAppender-" + getName() + "-" + port);
234     }
235
236   }
237 }