1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.mortbay.start;
16 import java.io.InputStreamReader;
17 import java.io.LineNumberReader;
18 import java.net.InetAddress;
19 import java.net.ServerSocket;
20 import java.net.Socket;
21
22
23
24
25
26
27
28
29
30
31
32
33
34 public class Monitor extends Thread
35 {
36 private int _port = Integer.getInteger("STOP.PORT", -1).intValue();
37 private String _key = System.getProperty("STOP.KEY", null);
38
39 ServerSocket _socket;
40
41 Monitor()
42 {
43 try
44 {
45 if(_port<0)
46 return;
47 setDaemon(true);
48 setName("StopMonitor");
49 _socket=new ServerSocket(_port,1,InetAddress.getByName("127.0.0.1"));
50 if (_port==0)
51 {
52 _port=_socket.getLocalPort();
53 System.out.println(_port);
54 }
55
56 if (_key==null)
57 {
58 _key=Long.toString((long)(Long.MAX_VALUE*Math.random()+this.hashCode()+System.currentTimeMillis()),36);
59 System.out.println("-DSTOP.KEY="+_key);
60 }
61 }
62 catch(Exception e)
63 {
64 if (Main._debug)
65 e.printStackTrace();
66 else
67 System.err.println(e.toString());
68 }
69 if (_socket!=null)
70 this.start();
71 else
72 System.err.println("WARN: Not listening on monitor port: "+_port);
73 }
74
75 public void run()
76 {
77 while (true)
78 {
79 Socket socket=null;
80 try{
81 socket=_socket.accept();
82
83 LineNumberReader lin=
84 new LineNumberReader(new InputStreamReader(socket.getInputStream()));
85 String key=lin.readLine();
86 if (!_key.equals(key))
87 continue;
88
89 String cmd=lin.readLine();
90 if (Main._debug) System.err.println("command="+cmd);
91 if ("stop".equals(cmd))
92 {
93 try {socket.close();}catch(Exception e){e.printStackTrace();}
94 try {_socket.close();}catch(Exception e){e.printStackTrace();}
95 System.exit(0);
96 }
97 else if ("status".equals(cmd))
98 {
99 socket.getOutputStream().write("OK\r\n".getBytes());
100 socket.getOutputStream().flush();
101 }
102 }
103 catch(Exception e)
104 {
105 if (Main._debug)
106 e.printStackTrace();
107 else
108 System.err.println(e.toString());
109 }
110 finally
111 {
112 if (socket!=null)
113 {
114 try{socket.close();}catch(Exception e){}
115 }
116 socket=null;
117 }
118 }
119 }
120
121
122
123
124 public static void monitor()
125 {
126 new Monitor();
127 }
128
129 }