KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > daemon > SimpleDaemon


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 /* @version $Id: SimpleDaemon.java 155409 2005-02-26 12:57:06Z dirkv $ */
18
19 package org.apache.commons.daemon;
20
21 import java.io.*;
22 import java.net.*;
23 import java.text.SimpleDateFormat JavaDoc;
24 import java.util.Date JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.Vector JavaDoc;
27 import org.apache.commons.daemon.Daemon;
28 import org.apache.commons.daemon.DaemonController;
29 import org.apache.commons.daemon.DaemonContext;
30
31 public class SimpleDaemon implements Daemon, Runnable JavaDoc {
32
33     private ServerSocket server=null;
34     private Thread JavaDoc thread=null;
35     private DaemonController controller=null;
36     private boolean stopping=false;
37     private String JavaDoc directory=null;
38     private Vector JavaDoc handlers=null;
39
40     public SimpleDaemon() {
41         super();
42         System.err.println("SimpleDaemon: instance "+this.hashCode()+
43                            " created");
44         this.handlers=new Vector JavaDoc();
45     }
46
47     protected void finalize() {
48         System.err.println("SimpleDaemon: instance "+this.hashCode()+
49                            " garbage collected");
50     }
51
52     /**
53      * init and destroy were added in jakarta-tomcat-daemon.
54      */

55     public void init(DaemonContext context)
56     throws Exception JavaDoc {
57         System.err.println("SimpleDaemon: instance "+this.hashCode()+
58                            " init");
59
60         int port=1200;
61
62         String JavaDoc[] a = context.getArguments();
63
64         if (a.length>0) port=Integer.parseInt(a[0]);
65         if (a.length>1) this.directory=a[1];
66         else this.directory="/tmp";
67
68         /* Dump a message */
69         System.err.println("SimpleDaemon: loading on port "+port);
70
71         /* Set up this simple daemon */
72         this.controller=context.getController();
73         this.server=new ServerSocket(port);
74         this.thread=new Thread JavaDoc(this);
75     }
76
77     public void start() {
78         /* Dump a message */
79         System.err.println("SimpleDaemon: starting");
80
81         /* Start */
82         this.thread.start();
83     }
84
85     public void stop()
86     throws IOException, InterruptedException JavaDoc {
87         /* Dump a message */
88         System.err.println("SimpleDaemon: stopping");
89
90         /* Close the ServerSocket. This will make our thread to terminate */
91         this.stopping=true;
92         this.server.close();
93
94         /* Wait for the main thread to exit and dump a message */
95         this.thread.join(5000);
96         System.err.println("SimpleDaemon: stopped");
97     }
98
99     public void destroy() {
100         System.err.println("SimpleDaemon: instance "+this.hashCode()+
101                            " destroy");
102     }
103
104     public void run() {
105         int number=0;
106
107         System.err.println("SimpleDaemon: started acceptor loop");
108         try {
109             while(!this.stopping) {
110                 Socket socket=this.server.accept();
111                 Handler handler=new Handler(socket,this,this.controller);
112                 handler.setConnectionNumber(number++);
113                 handler.setDirectoryName(this.directory);
114                 new Thread JavaDoc(handler).start();
115             }
116         } catch (IOException e) {
117             /* Don't dump any error message if we are stopping. A IOException
118                is generated when the ServerSocket is closed in stop() */

119             if (!this.stopping) e.printStackTrace(System.err);
120         }
121
122         /* Terminate all handlers that at this point are still open */
123         Enumeration JavaDoc openhandlers=this.handlers.elements();
124         while (openhandlers.hasMoreElements()) {
125             Handler handler=(Handler)openhandlers.nextElement();
126             System.err.println("SimpleDaemon: dropping connection "+
127                                handler.getConnectionNumber());
128             handler.close();
129         }
130
131         System.err.println("SimpleDaemon: exiting acceptor loop");
132     }
133
134     protected void addHandler(Handler handler) {
135         synchronized (handler) {
136             this.handlers.add(handler);
137         }
138     }
139
140     protected void removeHandler(Handler handler) {
141         synchronized (handler) {
142             this.handlers.remove(handler);
143         }
144     }
145
146     public static class Handler implements Runnable JavaDoc {
147
148         private DaemonController controller=null;
149         private SimpleDaemon parent=null;
150         private String JavaDoc directory=null;
151         private Socket socket=null;
152         private int number=0;
153
154         public Handler(Socket s, SimpleDaemon p, DaemonController c) {
155             super();
156             this.socket=s;
157             this.parent=p;
158             this.controller=c;
159         }
160
161         public void run() {
162             this.parent.addHandler(this);
163             System.err.println("SimpleDaemon: connection "+this.number+
164                                " opened from "+this.socket.getInetAddress());
165             try {
166                 InputStream in=this.socket.getInputStream();
167                 OutputStream out=this.socket.getOutputStream();
168                 handle(in,out);
169                 this.socket.close();
170             } catch (IOException e) {
171                 e.printStackTrace(System.err);
172             }
173             System.err.println("SimpleDaemon: connection "+this.number+
174                                " closed");
175             this.parent.removeHandler(this);
176         }
177
178         public void close() {
179             try {
180                 this.socket.close();
181             } catch (IOException e) {
182                 e.printStackTrace(System.err);
183             }
184         }
185
186         public void setConnectionNumber(int number) {
187             this.number=number;
188         }
189
190         public int getConnectionNumber() {
191             return(this.number);
192         }
193
194         public void setDirectoryName(String JavaDoc directory) {
195             this.directory=directory;
196         }
197
198         public String JavaDoc getDirectoryName() {
199             return(this.directory);
200         }
201
202         public void log(String JavaDoc name)
203         throws IOException {
204             OutputStream file=new FileOutputStream(name,true);
205             PrintStream out=new PrintStream(file);
206             SimpleDateFormat JavaDoc fmt=new SimpleDateFormat JavaDoc();
207
208             out.println(fmt.format(new Date JavaDoc()));
209             out.close();
210             file.close();
211         }
212
213         public void handle(InputStream in, OutputStream os) {
214             PrintStream out=new PrintStream(os);
215
216             while(true) {
217                 try {
218                     /* If we don't have data in the System InputStream, we want
219                        to ask to the user for an option. */

220                     if (in.available()==0) {
221                         out.println();
222                         out.println("Please select one of the following:");
223                         out.println(" 1) Shutdown");
224                         out.println(" 2) Reload");
225                         out.println(" 3) Create a file");
226                         out.println(" 4) Disconnect");
227                         out.print("Your choiche: ");
228                     }
229
230                     /* Read an option from the client */
231                     int x=in.read();
232
233                     switch (x) {
234                         /* If the socket was closed, we simply return */
235                         case -1:
236                             return;
237
238                         /* Attempt to shutdown */
239                         case '1':
240                             out.println("Attempting a shutdown...");
241                             try {
242                                 this.controller.shutdown();
243                             } catch (IllegalStateException JavaDoc e) {
244                                 out.println();
245                                 out.println("Can't shutdown now");
246                                 e.printStackTrace(out);
247                             }
248                             break;
249
250                         /* Attempt to reload */
251                         case '2':
252                             out.println("Attempting a reload...");
253                             try {
254                                 this.controller.reload();
255                             } catch (IllegalStateException JavaDoc e) {
256                                 out.println();
257                                 out.println("Can't reload now");
258                                 e.printStackTrace(out);
259                             }
260                             break;
261
262                         /* Disconnect */
263                         case '3':
264                             String JavaDoc name=this.getDirectoryName()+
265                                         "/SimpleDaemon."+
266                                         this.getConnectionNumber()+
267                                         ".tmp";
268                             try {
269                                 this.log(name);
270                                 out.println("File '"+name+"' created");
271                             } catch (IOException e) {
272                                 e.printStackTrace(out);
273                             }
274                             break;
275
276                         /* Disconnect */
277                         case '4':
278                             out.println("Disconnecting...");
279                             return;
280
281                         /* Discard any carriage return / newline characters */
282                         case '\r':
283                         case '\n':
284                             break;
285
286                         /* We got something that we weren't supposed to get */
287                         default:
288                             out.println("Unknown option '"+(char)x+"'");
289                             break;
290
291                     }
292
293                 /* If we get an IOException we return (disconnect) */
294                 } catch (IOException e) {
295                     System.err.println("SimpleDaemon: IOException in "+
296                                        "connection "+
297                                        this.getConnectionNumber());
298                     return;
299                 }
300             }
301         }
302     }
303 }
304
Popular Tags