View Javadoc

1   package org.sourceforge.jemm.server;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.InputStreamReader;
6   
7   import org.apache.log4j.Logger;
8   import org.sourceforge.jemm.comm.connection.Connection;
9   import org.sourceforge.jemm.comm.connection.ConnectionException;
10  import org.sourceforge.jemm.comm.connection.ServerConnectionFactory;
11  import org.sourceforge.jemm.comm.connection.socket.SocketServerConnectionFactory;
12  
13  public class ShutdownRequestReceiver implements Runnable{
14      protected static final Logger LOG = Logger.getLogger(ShutdownRequestReceiver.class);
15  
16      protected final ServerConnectionFactory connectionFactory;
17      protected final ShutdownRequestListener shutdownListener;
18      protected boolean closing = false;
19         
20      public ShutdownRequestReceiver(ServerConnectionFactory connectionFactory,ShutdownRequestListener shutdownListener) {
21      	this.connectionFactory = connectionFactory;
22      	this.shutdownListener = shutdownListener;
23      }
24  
25      public ShutdownRequestReceiver(int port,ShutdownRequestListener shutdownListener) {
26      	this(new SocketServerConnectionFactory(port),shutdownListener);
27      }
28  
29      @Override
30      public void run() {
31          try {
32              LOG.info("awaiting shutdown request");
33              connectionFactory.initialise();
34              while (true) {
35                  Connection connection = connectionFactory.getClientConnection();
36                  processConnection(connection);
37              }
38          } catch (ConnectionException e) {
39              if (!closing)
40                  LOG.error("Unexpected exception whilst accepting connections",e);
41          }
42      }
43  
44      private void processConnection(Connection connection) {
45      	try {
46      		LOG.info("connection from " + connection.getConnectionName());
47      		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
48      		String command = br.readLine();
49      		if(command != null)
50      			if("shutdown".equalsIgnoreCase(command.trim()))
51      				shutdownListener.shutdownRequest();
52      					
53      	}catch(IOException ioe) {
54      		LOG.warn("Error caught whilst processing shutdown command",ioe);
55      	}
56  	}
57  
58  	public void shutdown() {
59          closing = true;
60          try {
61              // close the server socket to stop accepting new connections
62              connectionFactory.close();
63  
64          } catch (ConnectionException ce) {
65              LOG.warn("Exception thrown whilst terminating");
66          }
67      }
68  	
69  	public void start() {
70  		Thread t = new Thread(this);
71  		t.start();
72  	}
73  	
74  }