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