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