1 45 package org.openejb.server; 46 47 import java.io.*; 48 import java.net.*; 49 import java.util.*; 50 import org.openejb.*; 51 import org.openejb.util.SafeProperties; 52 53 62 public class ServiceDaemon implements ServerService, Runnable { 63 64 ServerService next; 65 66 Properties props; 67 String ip; 68 int port; 69 String name; 70 71 ServerSocket serverSocket; 72 73 76 boolean stop = true; 77 78 public ServiceDaemon(ServerService next) { 79 this.next = next; 80 } 81 82 89 public void init(Properties props) throws Exception { 90 this.props = props; 92 93 String p = props.getProperty("port"); 94 ip = props.getProperty("bind"); 95 name = props.getProperty("name"); 96 97 port = Integer.parseInt(p); 98 next.init(props); 100 } 101 102 public void start() throws ServiceException { 103 synchronized (this) { 104 if (!stop) 106 return; 107 108 stop = false; 109 try { 111 serverSocket = new ServerSocket(port, 20); 113 port = serverSocket.getLocalPort(); 114 ip = serverSocket.getInetAddress().getHostAddress(); 115 116 Thread d = new Thread (this); 117 d.setName("service." + next.getName() + "@" + d.hashCode()); 118 d.setDaemon(true); 119 d.start(); 120 } catch (Exception e) { 121 throw new ServiceException("Service failed to start.", e); 122 } 124 125 next.start(); 127 } 128 } 129 130 public void stop() throws ServiceException { 131 synchronized (this) { 133 if (stop) 135 return; 136 137 stop = true; 139 try { 140 this.notifyAll(); 141 } catch (Throwable t) { 142 t.printStackTrace(); 143 } 147 next.stop(); 149 } 150 } 151 152 public void service(InputStream in, OutputStream out) throws ServiceException, IOException { 153 throw new UnsupportedOperationException ("service(in,out)"); 154 } 155 156 public synchronized void service(final Socket socket) 157 throws ServiceException, IOException { 158 Thread d = new Thread (new Runnable () { 159 public void run() { 160 try { 161 next.service(socket); 162 } catch (SecurityException e) { 163 } catch (Throwable e) { 165 167 } finally { 168 try { 169 if (socket != null) 170 socket.close(); 171 } catch (Throwable t) { 172 } 175 } 176 } 177 }); 178 d.setDaemon(true); 179 d.start(); 180 } 181 182 185 public String getName() { 186 return name; 187 } 188 189 192 public String getIP() { 193 return ip; 194 } 195 196 199 public int getPort() { 200 return port; 201 } 202 203 public void run() { 204 205 Socket socket = null; 206 207 while (!stop) { 208 try { 209 socket = serverSocket.accept(); 210 socket.setTcpNoDelay(true); 211 if (!stop) service(socket); 212 } catch (SecurityException e) { 213 } catch (Throwable e) { 215 217 } 218 } 219 } 220 } 221 | Popular Tags |