package org.maachang.connector ;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ConnectorAcceptThread.
 * 
 * @version 2008/05/25
 * @author masahito suzuki
 * @since MaachangBase 1.00
 */
class ConnectorAcceptThread extends Thread {
    
    private static final Log LOG = LogFactory.getLog( ConnectorAcceptThread.class ) ;
    private volatile boolean stopFlag = true ;
    private ConnectorManager man = null ;
    private byte[] headerBinary = null ;
    
    private ConnectorAcceptThread() {
        
    }
    
    public ConnectorAcceptThread( byte[] headerBinary,ConnectorManager man )
        throws Exception {
        if( man == null || man.isClosed() == true ) {
            throw new IllegalArgumentException( "引数は不正です" ) ;
        }
        this.headerBinary = headerBinary ;
        this.man = man ;
        this.stopFlag = false ;
        this.setDaemon( true ) ;
        this.start() ;
    }
    
    public void destroy() {
        setStop( true ) ;
    }
    
    public synchronized boolean isStop() {
        return stopFlag ;
    }
    
    private synchronized void setStop( boolean mode ) {
        this.stopFlag = mode ;
    }
    
    public void run() {
        boolean endFlag = false ;
        ThreadDeath threadDeach = null ;
        for( ;; ) {
            if( endFlag == true || isStop() == true ) {
                break ;
            }
            ServerSocket ss = this.man.getServerSocket() ;
            Socket s = null ;
            try {
                if( ( s = ss.accept() ) != null ) {
                    if( LOG.isDebugEnabled() ) {
                        LOG.debug(
                            new StringBuilder().
                            append("## accept:").
                            append( s.getInetAddress().getHostAddress() ).
                            append( "/" ).append( s.getPort() ).toString() ) ;
                    }
                    this.man.append( headerBinary,s ) ;
                }
            } catch( SocketTimeoutException st ) {
            } catch ( NullPointerException ne ) {
            } catch( OutOfMemoryError mem ) {
            } catch( Exception e ) {
            } catch( ThreadDeath td ) {
                endFlag = true ;
                threadDeach = td ;
            }
        }
        this.man = null ;
        setStop( true ) ;
        if( threadDeach != null ) {
            throw threadDeach ;
        }
    }
    
}

