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 Process _process;
36 private final int _port;
37 private final String _key;
38
39 ServerSocket _socket;
40
41 public Monitor(int port,String key)
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("STOP.KEY="+key);
60 }
61 }
62 catch(Exception e)
63 {
64 Config.debug(e);
65 System.err.println(e.toString());
66 }
67 finally
68 {
69 _port=port;
70 _key=key;
71 }
72
73 if (_socket!=null)
74 this.start();
75 else
76 System.err.println("WARN: Not listening on monitor port: "+_port);
77 }
78
79 public Process getProcess()
80 {
81 return _process;
82 }
83
84 public void setProcess(Process process)
85 {
86 _process = process;
87 }
88
89 @Override
90 public void run()
91 {
92 while (true)
93 {
94 Socket socket=null;
95 try{
96 socket=_socket.accept();
97
98 LineNumberReader lin=
99 new LineNumberReader(new InputStreamReader(socket.getInputStream()));
100 String key=lin.readLine();
101 if (!_key.equals(key))
102 continue;
103
104 String cmd=lin.readLine();
105 Config.debug("command=" + cmd);
106 if ("stop".equals(cmd))
107 {
108 try {socket.close();}catch(Exception e){e.printStackTrace();}
109 try {_socket.close();}catch(Exception e){e.printStackTrace();}
110 if (_process!=null)
111 _process.destroy();
112 System.exit(0);
113 }
114 else if ("status".equals(cmd))
115 {
116 socket.getOutputStream().write("OK\r\n".getBytes());
117 socket.getOutputStream().flush();
118 }
119 }
120 catch(Exception e)
121 {
122 Config.debug(e);
123 System.err.println(e.toString());
124 }
125 finally
126 {
127 if (socket!=null)
128 {
129 try{socket.close();}catch(Exception e){}
130 }
131 socket=null;
132 }
133 }
134 }
135
136 }