
import java.net.*;
/*
 * Handles incoming request threads
 * ref: http://www.informit.com/guides/content.asp?g=java&seqNum=237&rl=1
 */

public class RequestThread extends Thread 
{
  
	private ThreadPool queue;
    private boolean running;
    private boolean processing = false;
    private int threadNumber;
    private ConnectionHandler connectionhandler;


    public RequestThread( ThreadPool queue, int threadNumber, String connectionhandlerClassName )
    {
        this.queue = queue;
        this.threadNumber = threadNumber;
        try
        {
            // Create the request handler
            this.connectionhandler = ( ConnectionHandler )( Class.forName( connectionhandlerClassName ).newInstance() );
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

  
    public boolean isProcessing()
    {
        return this.processing;
    }

    /**
     * If a thread is waiting, then wake it up and tell it to die
     */
    public void killThread()
    {
        System.out.println( "[" + threadNumber + "]: Attempting to kill thread..." );
        this.running = false;
    }

    /**
     * The threadÕs main processing loop
     */
    public void run()
    {
        this.running = true;
        while( running )
        {
            try
            {
                // Obtain the next pending socket from the queue; only process requests if 
                // it is still running. The shutdown mechanism will wake up the threads at this
                // point, so the state could have changed to not running here.
                Object o = queue.getNextObject();
                if( running )
                {
                    // Cast the object to a Socket
                    Socket socket = ( Socket )o;

                    // Mark ourselves as processing a request
                    this.processing = true;
                    System.out.println( "[" + threadNumber + "]: Processing request..." );

                    // Handle the request
                    this.connectionhandler.processrequest( socket );

                    // Finished processing, so make it available for the next request
                    this.processing = false;
                    System.out.println( "[" + threadNumber + "]: Finished Processing request..." );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }

        System.out.println( "[" + threadNumber + "]: Thread shutting down..." );
    }
}