FileDocCategorySizeDatePackage
SelectorThread.javaAPI DocGlassfish v2 API87344Mon Aug 27 15:07:16 BST 2007com.sun.enterprise.web.connector.grizzly

SelectorThread

public class SelectorThread extends Thread implements MBeanRegistration
This class implement an NIO socket HTTP Listener. This class supports three stagegy: Mode Blocking: This mode uses NIO blocking mode, and doesn't uses any of the java.nio.* classes. Mode Non-Blocking: This mode uses NIO non blocking mode and read the entire request stream before processing the request. The stragegy used is to find the content-lenght header and buffer bytes until the end of the stream is read.
author
Jean-Francois Arcand

Fields Summary
public static final String
SERVER_NAME
private Object[]
lock
protected int
serverTimeout
protected InetAddress
inet
protected int
port
protected ServerSocket
serverSocket
protected ServerSocketChannel
serverSocketChannel
The ServerSocketChannel used in blocking mode.
protected boolean
initialized
protected volatile boolean
running
protected String
domain
protected ObjectName
oname
protected ObjectName
globalRequestProcessorName
private ObjectName
keepAliveMbeanName
private ObjectName
pwcConnectionQueueMbeanName
private ObjectName
pwcFileCacheMbeanName
protected MBeanServer
mserver
protected ObjectName
processorWorkerThreadName
protected boolean
tcpNoDelay
protected int
linger
protected int
socketTimeout
protected int
maxKeepAliveRequests
protected boolean
oOBInline
protected String
compression
Compression value.
protected String
noCompressionUserAgents
protected String
restrictedUserAgents
protected String
compressableMimeTypes
protected int
compressionMinSize
private boolean
reuseAddress
Is the socket reuse socket enabled.
protected boolean
bufferResponse
Buffer the response until the buffer is full.
protected int
maxHttpHeaderSize
Default HTTP header buffer size.
protected int
minReadQueueLength
Number of polled Read*Task instance.
protected int
minProcessorQueueLength
Number of polled ProcessorTask instance.
protected int
maxPostSize
protected Selector
selector
The Selector used by the connector.
protected org.apache.coyote.Adapter
adapter
Associated adapter.
protected Pipeline
readPipeline
The queue shared by this thread and code>ReadTask
protected Pipeline
processorPipeline
The queue shared by this thread and the code>ProcessorTask.
protected PipelineStatistic
pipelineStat
Placeholder for Pipeline statistic.
protected String
pipelineClassName
The default Pipeline used.
protected int
maxProcessorWorkerThreads
Maximum number of WorkerThread
protected int
maxReadWorkerThreads
Maximum number of ReadWorkerThread
protected int
minWorkerThreads
Minimum numbers of WorkerThread created
protected int
minSpareThreads
Minimum numbers of WorkerThread before creating new thread. Not used in 9.x
protected int
threadsIncrement
The number used when increamenting the Pipeline thread pool.
protected int
threadsTimeout
The timeout used by the thread when processing a request.
protected boolean
useDirectByteBuffer
Is the ByteBuffer used by the ReadTask use direct ByteBuffer or not.
protected org.apache.coyote.RequestGroupInfo
globalRequestProcessor
Monitoring object used to store information.
private KeepAliveStats
keepAliveStats
Keep-alive stats
protected boolean
displayConfiguration
If true, display the NIO configuration information.
protected boolean
isMonitoringEnabled
Is monitoring already started.
protected int
currentConnectionNumber
The current number of simulatenous connection.
protected volatile boolean
isWaiting
Is this Selector currently in Wating mode?
protected int
requestBufferSize
The input request buffer size.
protected boolean
useByteBufferView
Create view ByteBuffer from another ByteBuffer
protected int
keepAliveTimeoutInSeconds
private int
kaTimeout
Number of seconds before idle keep-alive connections expire
protected boolean
recycleTasks
Recycle the Task after running them
protected static int
selectorTimeout
The Selector timeout value. By default, it is set to 60000 miliseconds (as in the j2se 1.5 ORB).
protected int
maxQueueSizeInBytes
Maximum pending connection before refusing requests.
protected Class
algorithmClass
The Algorithm used to predict the end of the NIO stream
protected String
algorithmClassName
The Algorithm used to parse the NIO stream.
public static final String
DEFAULT_ALGORITHM
The default NIO stream algorithm.
protected int
ssBackLog
Server socket backlog.
private long
nextKeysExpiration
Next time the exprireKeys() will delete keys.
protected String
defaultResponseType
The default response-type
protected String
forcedRequestType
The forced request-type
protected static String
rootFolder
The root folder where application are deployed
private ConcurrentLinkedQueue
keysToEnable
List of SelectionKey event to register next time the Selector wakeups. This is needed since there a bug in j2se 1.4.x that prevent registering selector event if the call is done on another thread.
protected ConcurrentLinkedQueue
processorTasks
ConcurrentLinkedQueue used as an object pool. If the list becomes empty, new ProcessorTask will be automatically added to the list.
protected ConcurrentLinkedQueue
readTasks
ConcurrentLinkedQueue used as an object pool. If the list becomes empty, new ReadTask will be automatically added to the list.
protected ConcurrentLinkedQueue
activeProcessorTasks
List of active ProcessorTask.
protected int
multiSelectorsCount
The number of SelectorReadThread
protected MultiSelectorThread[]
readThreads
The Selector used to register OP_READ
int
curReadThread
The current readThreads used to process OP_READ.
protected static Logger
logger
The logger used by the grizzly classes.
protected boolean
disableUploadTimeout
Flag to disable setting a different time-out on uploads.
protected int
uploadTimeout
Maximum timeout on uploads. 5 minutes as in Apache HTTPD server.
protected KeepAlivePipeline
keepAlivePipeline
Keep-Alive subsystem. If a client opens a socket but never close it, the SelectionKey will stay forever in the Selector keys, and this will eventualy produce a memory leak.
protected FileCacheFactory
fileCacheFactory
The FileCacheFactory associated with this Selector
protected int
secondsMaxAge
Timeout before remove the static resource from the cache.
protected int
maxCacheEntries
The maximum entries in the fileCache
protected long
minEntrySize
The maximum size of a cached resources.
protected long
maxEntrySize
The maximum size of a cached resources.
protected long
maxLargeFileCacheSize
The maximum cached bytes
protected long
maxSmallFileCacheSize
The maximum cached bytes
protected boolean
isFileCacheEnabled
Is the FileCache enabled.
protected boolean
isLargeFileCacheEnabled
Is the large FileCache enabled.
protected boolean
asyncExecution
Is asynchronous mode enabled?
protected AsyncHandler
asyncHandler
When the asynchronous mode is enabled, the execution of this object will be delegated to the AsyncHandler
protected static boolean
defaultAlgorithmInstalled
Is the DEFAULT_ALGORITHM used.
private Management
jmxManagement
The JMX Management class.
private ClassLoader
classLoader
The Classloader used to load instance of StreamAlgorithm.
protected boolean
enableNioLogging
Grizzly own debug flag.
private static final ConcurrentHashMap
selectorThreads
Static list of current instance of this class.
protected ConcurrentLinkedQueue
bannedKeys
Banned SelectionKey registration.
Constructors Summary
public SelectorThread()
Create the Selector object. Each instance of this class will listen to a specific port.

    
    
    
    // ---------------------------------------------------- Constructor --//
    
    
                        
     
    
Methods Summary
public voidaddBannedSelectionKey(java.nio.channels.SelectionKey key)
Add a SelectionKey to the banned list of SelectionKeys. A SelectionKey is banned when new registration aren't allowed on the Selector.

        bannedKeys.offer(key);
    
public voidcancelKey(java.nio.channels.SelectionKey key)
Cancel the current SelectionKey

        if (key == null){
            return;
        }

        keepAlivePipeline.untrap(key);       
        if (!processorPipeline.expireKey(key)){
            return;
        }

        if (enableNioLogging){
            logger.log(Level.INFO,"Closing SocketChannel " + 
                    key.channel());
        }

        Socket socket = ((SocketChannel)key.channel()).socket();
        try{
            if (!socket.isInputShutdown()){
                socket.shutdownInput();
            }
        } catch (IOException ex){
            ;
        }
        
        try{
            if (!socket.isOutputShutdown()){
                socket.shutdownOutput();
            }
        } catch (IOException ex){
            ;
        }

        try{
            if (!socket.isClosed()){
                socket.close();
            }
        } catch (IOException ex){
            ;
        } finally {
            try{
                // This is not needed but just to make sure the JDK isn't 
                // leaking any fd.
                if (key.channel().isOpen()){
                    key.channel().close();
                }
            } catch (IOException ex){
                logger.log(Level.FINEST,"selectorThread.unableToCloseKey", key);
            }
            if (isMonitoringEnabled()) {
                getRequestGroupInfo().decreaseCountOpenConnections();
            }
        }

        
        // Set the attachement to null so the Selector.java handleConnection
        // stop processing this key.
        key.attach(null);
        key.cancel();
        key = null;
    
public booleancancelThreadExecution(long cancelThreadID)
Cancel the threadID execution. Return true if it is successful.

param
id the thread name to cancel

   
        if ( multiSelectorsCount > 1 ){
            boolean cancelled = false;
            for (MultiSelectorThread readSelector : readThreads) {
                cancelled = ((SelectorReadThread)readSelector).
                        cancelThreadExecution(cancelThreadID);   
                if (cancelled) return true;
            }       
            return false;
        }
                       
        if (activeProcessorTasks.size() == 0) return false;
        
        Iterator<ProcessorTask> iterator = activeProcessorTasks.iterator();
        ProcessorTask processorTask;
        long threadID;
        while( iterator.hasNext() ){
            processorTask = iterator.next();
            threadID = processorTask.getWorkerThreadID();
            if (threadID == cancelThreadID){
                processorTask.cancelTask("Request cancelled.","500");
                logger.log(Level.WARNING,
                        "Thread Request Cancelled: " + threadID);     
                return processorTask.getPipeline().interruptThread(threadID);
            }
        }
        return false;
    
protected voidclearTasks()
Clear all cached Tasks

        processorTasks.clear();
        readTasks.clear();
    
private voidcloseActiveConnections()

        Set<SelectionKey> readyKeys = selector.keys();
        if (readyKeys.isEmpty()){
            return;
        }
        Iterator<SelectionKey> iterator = readyKeys.iterator();
        SelectionKey key;
        while (iterator.hasNext()) {
            key = iterator.next();
            if (key.channel() instanceof SocketChannel){
                cancelKey(key);
            } else {
                key.cancel();
            }
        }        
    
protected voidconfigureCompression(DefaultProcessorTask processorTask)

        processorTask.setCompression(compression);
        processorTask.addNoCompressionUserAgent(noCompressionUserAgents);
        processorTask.addCompressableMimeType(compressableMimeTypes);
        processorTask.setCompressionMinSize(compressionMinSize);
        processorTask.addRestrictedUserAgent(restrictedUserAgents);
    
protected ProcessorTaskconfigureProcessorTask(DefaultProcessorTask task)

        task.setAdapter(adapter);
        task.setMaxHttpHeaderSize(maxHttpHeaderSize);
        task.setBufferSize(requestBufferSize);
        task.setSelectorThread(this);               
        task.setRecycle(recycleTasks);
        task.setDefaultResponseType(defaultResponseType);
        task.setForcedRequestType(forcedRequestType);
        task.setMaxPostSize(maxPostSize);
        task.setTimeout(uploadTimeout);
        task.setDisableUploadTimeout(disableUploadTimeout);
 
        if ( keepAlivePipeline.dropConnection() ) {
            task.setDropConnection(true);
        }
        
        // Asynch extentions
        if ( asyncExecution ) {
            task.setEnableAsyncExecution(asyncExecution);
            task.setAsyncHandler(asyncHandler);          
        }
                
        task.setPipeline(processorPipeline);         
        configureCompression(task);
        
        return (ProcessorTask)task;        
    
protected voidconfigureReadThread(com.sun.enterprise.web.connector.grizzly.SelectorThread multiSelector)

        multiSelector.setMaxThreads(maxProcessorWorkerThreads);
        multiSelector.setBufferSize(requestBufferSize);
        multiSelector.setMaxKeepAliveRequests(maxKeepAliveRequests);
        multiSelector
                .setKeepAliveTimeoutInSeconds(keepAliveTimeoutInSeconds);
        multiSelector.maxQueueSizeInBytes = maxQueueSizeInBytes;
        multiSelector.fileCacheFactory = fileCacheFactory;     
        multiSelector.maxReadWorkerThreads = maxReadWorkerThreads;
        multiSelector.defaultResponseType = defaultResponseType;
        multiSelector.forcedRequestType = forcedRequestType;          
        multiSelector.minReadQueueLength = minReadQueueLength;
        multiSelector.maxHttpHeaderSize = maxHttpHeaderSize;
        multiSelector.isMonitoringEnabled = isMonitoringEnabled();
        multiSelector.pipelineStat = pipelineStat;
        multiSelector.globalRequestProcessor = globalRequestProcessor;

        if ( asyncExecution ) {
            multiSelector.asyncExecution = asyncExecution;
            multiSelector.asyncHandler = asyncHandler;
        }

        multiSelector.threadsIncrement = threadsIncrement;
        multiSelector.setPort(port);
        multiSelector.setAdapter(adapter);

        multiSelector.processorPipeline = processorPipeline;
        multiSelector.readPipeline = readPipeline;            
        multiSelector.readTasks = readTasks;
        multiSelector.processorTasks = processorTasks;   
        multiSelector.keepAlivePipeline = keepAlivePipeline;
        multiSelector.domain = domain;
        multiSelector.bufferResponse = bufferResponse;

        multiSelector.initEndpoint();
        multiSelector.start();
    
public voiddisableMonitoring()
Disable gathering of monitoring datas.

        disablePipelineStats();  
        if ( readThreads != null ) {
            for (int i = 0; i < readThreads.length; i++) {
                ((SelectorReadThread)readThreads[i]).isMonitoringEnabled = false;
            }
        }
        fileCacheFactory.setIsMonitoringEnabled(isMonitoringEnabled);        
    
protected voiddisablePipelineStats()
Removes PipelineStatistic from every Pipeline, when monitoring has been turned off.

        pipelineStat.stop();
        
        processorPipeline.setPipelineStatistic(null);
        pipelineStat.setProcessorPipeline(null);

        if (keepAlivePipeline != null){
            keepAlivePipeline.setKeepAliveStats(null);
        }

    
private voiddisplayConfiguration()
Display the Grizzly configuration parameters.

       if (displayConfiguration){
            logger.log(Level.INFO,
                    "\n Grizzly configuration for port " 
                    + port 
                    + "\n\t maxThreads: " 
                    + maxProcessorWorkerThreads 
                    + "\n\t minThreads: " 
                    + minWorkerThreads 
                    + "\n\t ByteBuffer size: " 
                    + requestBufferSize 
                    + "\n\t useDirectByteBuffer: "
                    + useDirectByteBuffer                       
                    + "\n\t useByteBufferView: "                        
                    + useByteBufferView                   
                    + "\n\t maxHttpHeaderSize: " 
                    + maxHttpHeaderSize
                    + "\n\t maxKeepAliveRequests: "
                    + maxKeepAliveRequests
                    + "\n\t keepAliveTimeoutInSeconds: "
                    + keepAliveTimeoutInSeconds
                    + "\n\t Static File Cache enabled: "                        
                    + isFileCacheEnabled                    
                    + "\n\t Stream Algorithm : "                        
                    + algorithmClassName        
                    + "\n\t Pipeline : "                        
                    + pipelineClassName                    
                    + "\n\t Round Robin Selector Algorithm enabled: "                        
                    + ( multiSelectorsCount > 1 )
                    + "\n\t Round Robin Selector pool size: "
                    + multiSelectorsCount
                    + "\n\t recycleTasks: "                        
                    + recycleTasks
                    + "\n\t Asynchronous Request Processing enabled: " 
                    + asyncExecution); 
        }
    
protected voiddoSelect()
Execute a Selector.select() operation.

        SelectionKey key = null;
        Set readyKeys;
        Iterator<SelectionKey> iterator;
        int selectorState; 

        try{
            selectorState = 0;
            enableSelectionKeys();                

            try{                
                selectorState = selector.select(selectorTimeout);
            } catch (CancelledKeyException ex){
                ;
            }

            if (!running) return;

            readyKeys = selector.selectedKeys();
            iterator = readyKeys.iterator();
            while (iterator.hasNext()) {
                key = iterator.next();
                iterator.remove();
                if (key.isValid()) {
                    handleConnection(key);
                } else {
                    cancelKey(key);
                }
            }
            
            expireIdleKeys();
            
            if (selectorState <= 0){
                selector.selectedKeys().clear();
                return;
            }
        } catch (Throwable t){
            if (key != null && key.isValid()){
                logger.log(Level.SEVERE,"selectorThread.errorOnRequest",t);
            } else {
                logger.log(Level.FINE,"selectorThread.errorOnRequest",t);
            }

            if ( key != null ){
                key.attach(null);
                key.cancel();
            }
        }
    
public voidenableCometSupport(boolean enableComet)
Enable Comet/Poll request support.

        if ( enableComet ){
            asyncExecution = true;
            setBufferResponse(false);    
            isFileCacheEnabled = false;
            isLargeFileCacheEnabled = false;
            asyncHandler = new DefaultAsyncHandler();
            asyncHandler.addAsyncFilter(new CometAsyncFilter()); 
            
            SelectorThread.logger()
                .log(Level.INFO,"Enabling Grizzly ARP Comet support.");
            
        } else {
            asyncExecution = false;
        }
    
public voidenableMonitoring()
Enable gathering of monitoring datas.

        isMonitoringEnabled = true;
        enablePipelineStats();      
        if ( readThreads != null ) {
            for (int i = 0; i < readThreads.length; i++) {
                ((SelectorReadThread)readThreads[i]).isMonitoringEnabled = true;
            }
        }
        fileCacheFactory.setIsMonitoringEnabled(isMonitoringEnabled);
    
protected voidenablePipelineStats()
Injects PipelineStatistic into every Pipeline, for monitoring purposes.

        pipelineStat.start();

        processorPipeline.setPipelineStatistic(pipelineStat);       
        pipelineStat.setProcessorPipeline(processorPipeline);

        if (keepAlivePipeline != null){
            keepAlivePipeline.setKeepAliveStats(keepAliveStats);
        }
    
public voidenableRcmSupport(boolean rcmSupport)
Enable Application Resource Allocation Grizzly Extension.

        if (rcmSupport){
            // Avoid dependency on that extension. If the package is renamed
            // an exception will be logged later when the SelectorThread start.
            pipelineClassName = "com.sun.enterprise.web.ara.IsolationPipeline";
        }        
    
public voidenableSelectionKeys()
Enable all registered interestOps. Due a a NIO bug, all interestOps invokation needs to occurs on the same thread as the selector thread.

        SelectionKey selectionKey;
        int size = keysToEnable.size();
        long currentTime = 0L;
        if (size > 0){
            currentTime = (Long)System.currentTimeMillis();
        }

        for (int i=0; i < size; i++) {
            selectionKey = keysToEnable.poll();
            
            // If the SelectionKey is used for continuation, do not allow
            // the key to be registered.
            if (asyncExecution && !bannedKeys.isEmpty() 
                    && bannedKeys.remove(selectionKey)){
                continue;
            }
            
            if (!selectionKey.isValid() || !keepAlivePipeline.trap(selectionKey)){
                cancelKey(selectionKey);
                continue;
            }

            selectionKey.interestOps(
                    selectionKey.interestOps() | SelectionKey.OP_READ);

            if (selectionKey.attachment() == null)
                selectionKey.attach(currentTime);
        } 
    
protected voidexpireIdleKeys()
Cancel keep-alive connections.

        if ( keepAliveTimeoutInSeconds <= 0 || !selector.isOpen()) return;
        long current = System.currentTimeMillis();

        if (current < nextKeysExpiration) {
            return;
        }
        nextKeysExpiration = current + kaTimeout;
        
        Set<SelectionKey> readyKeys = selector.keys();
        if (readyKeys.isEmpty()){
            return;
        }
        Iterator<SelectionKey> iterator = readyKeys.iterator();
        SelectionKey key;
        while (running && iterator.hasNext()) {
            key = iterator.next();          
            // Keep-alive expired
            Object attachment = key.attachment();
            if (attachment != null) {
                
                if ( !defaultAlgorithmInstalled 
                        && !(attachment instanceof Long)) { 
                    continue; 
                }
                    
                try{
                    long expire = (Long)attachment;
                    if (current - expire >= kaTimeout) {
                        if (enableNioLogging){
                            logger.log(Level.INFO,
                                    "Keep-Alive expired for SocketChannel " + 
                                    key.channel());
                        }          
                        cancelKey(key);
                    } else if (expire + kaTimeout < nextKeysExpiration){
                        nextKeysExpiration = expire + kaTimeout;
                    }
                } catch (ClassCastException ex){                            
                    if (logger.isLoggable(Level.FINEST)){
                        logger.log(Level.FINEST,
                                   "Invalid SelectionKey attachment",ex);
                    }
                }
            }
        }                    
    
public java.util.concurrent.ConcurrentLinkedQueuegetActiveProcessorTasks()

        return activeProcessorTasks;
    
public org.apache.coyote.AdaptergetAdapter()
Get the associated adapter.

return
the associated adapter

        return adapter;
    
public java.net.InetAddressgetAddress()

        return inet;
    
public java.lang.ClassgetAlgorithmClass()

        return algorithmClass;
    
public java.lang.StringgetAlgorithmClassName()

        return algorithmClassName;
    
public AsyncHandlergetAsyncHandler()
Return the AsyncHandler used when asynchronous execution is enabled.

        return asyncHandler;
    
public booleangetBufferResponse()
Return true if the reponse is buffered.

        return bufferResponse;
    
public intgetBufferSize()
Return the request input buffer size

        return requestBufferSize;
    
public java.lang.ClassLoadergetClassLoader()

        return classLoader;
    
public java.lang.StringgetCompressableMimeTypes()

        return compressableMimeTypes;
    
public java.lang.StringgetCompression()

        return compression;
    
public intgetCompressionMinSize()

        return compressionMinSize;
    
public intgetCountThreadsIdleStats()


        int ret = processorPipeline.getWaitingThread();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getWaitingThread();
        }

        return ret;
    
public intgetCountThreadsStats()
PWCThreadPool Stats


        int ret = processorPipeline.getCurrentThreadCount();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getCurrentThreadCount();
        }

        return ret;
    
public intgetCurReadThread()

        return curReadThread;
    
public intgetCurrentBusyProcessorThreads()
Provides the count of request threads that are currently being processed by the container

return
The count of busy threads

        int busy = 0;
        
        // multi selector support
        if (multiSelectorsCount > 1) {
            for (MultiSelectorThread readSelector : readThreads) {
                busy += ((SelectorReadThread)readSelector)
                                .getCurrentBusyProcessorThreads();   
            }

        } else {
            busy = processorPipeline.getCurrentThreadsBusy();
        }

        return busy;  
    
public intgetCurrentConnectionNumber()

        return currentConnectionNumber;
    
public intgetCurrentThreadCountStats()
HTTPListener Stats


        int ret = processorPipeline.getCurrentThreadCount();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getCurrentThreadCount();
        }

        return ret;
    
public intgetCurrentThreadsBusyStats()


        int ret = processorPipeline.getCurrentThreadsBusy();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getCurrentThreadsBusy();
        }
 
        return ret;
    
public java.lang.StringgetDefaultResponseType()

        return defaultResponseType;
    
public booleangetDisableUploadTimeout()
Get the flag that controls upload time-outs.

        return disableUploadTimeout;
    
public java.lang.StringgetDomain()

        return domain;
    
public booleangetEnableAsyncExecution()
Return true when asynchronous execution is enabled.

        return asyncExecution;
    
public java.lang.StringgetForcedRequestType()

        return forcedRequestType;
    
public org.apache.coyote.RequestGroupInfogetGlobalRequestProcessor()

        return globalRequestProcessor;
    
public javax.management.ObjectNamegetGlobalRequestProcessorName()

        return globalRequestProcessorName;
    
public java.net.InetAddressgetInet()

        return inet;
    
public intgetKaTimeout()

        return kaTimeout;
    
public javax.management.ObjectNamegetKeepAliveMbeanName()

        return keepAliveMbeanName;
    
public KeepAlivePipelinegetKeepAlivePipeline()

        return keepAlivePipeline;
    
public KeepAliveStatsgetKeepAliveStats()

        return keepAliveStats;
    
public intgetKeepAliveTimeoutInSeconds()
Gets the number of seconds before a keep-alive connection that has been idle times out and is closed.

return
Keep-alive timeout in number of seconds

        return keepAliveTimeoutInSeconds;
    
public java.util.concurrent.ConcurrentLinkedQueuegetKeysToEnable()

        return keysToEnable;
    
public booleangetLargeFileCacheEnabled()
Is the large file cache support enabled.

        return isLargeFileCacheEnabled;
    
public intgetLinger()

        return linger;
    
public static java.util.logging.LoggergetLogger()

        return logger;
    
public ManagementgetManagement()

        return jmxManagement;
    
public intgetMaxCacheEntries()
Return the maximum entries this cache can contains.

        return maxCacheEntries;
    
public longgetMaxEntrySize()
Get the maximum size a FileCacheEntry can have.

        return maxEntrySize;
    
public intgetMaxHttpHeaderSize()

        return maxHttpHeaderSize;
    
public intgetMaxKeepAliveRequests()

        return maxKeepAliveRequests;
    
public longgetMaxLargeCacheSize()
Get the maximum cache size

        return maxLargeFileCacheSize;
    
public intgetMaxPostSize()

        return maxPostSize;
    
public intgetMaxProcessorWorkerThreads()

        return maxProcessorWorkerThreads;
    
public intgetMaxQueueSizeInBytes()

        return maxQueueSizeInBytes;
    
public intgetMaxReadWorkerThreads()

        return maxReadWorkerThreads;
    
public longgetMaxSmallCacheSize()
Get the maximum cache size

        return maxSmallFileCacheSize;
    
public intgetMaxSpareThreads()

        return maxProcessorWorkerThreads;
    
public intgetMaxSpareThreadsStats()


        int ret = processorPipeline.getMaxSpareThreads();
 
        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getMaxSpareThreads();
        }

        return ret;
    
public intgetMaxThreads()

        return maxProcessorWorkerThreads;
    
public intgetMaxThreadsStats()


        int ret = processorPipeline.getMaxThreads();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getMaxThreads();
        }
        
        return ret;
    
public longgetMinEntrySize()
Get the maximum size a FileCacheEntry can have.

        return minEntrySize;
    
public intgetMinProcessorQueueLength()

        return minProcessorQueueLength;
    
public intgetMinReadQueueLength()

        return minReadQueueLength;
    
public intgetMinSpareThreads()

        return  minSpareThreads;
    
public intgetMinSpareThreadsStats()


        int ret = processorPipeline.getMinSpareThreads();

        if (readPipeline != null
                && readPipeline != processorPipeline) {
            ret += readPipeline.getMinSpareThreads();
        }

        return ret;
    
public intgetMinWorkerThreads()

        return minWorkerThreads;
    
public javax.management.MBeanServergetMserver()

        return mserver;
    
public longgetNextKeysExpiration()

        return nextKeysExpiration;
    
public java.lang.StringgetNoCompressionUserAgents()

        return noCompressionUserAgents;
    
public javax.management.ObjectNamegetObjectName()

        return oname;
    
public javax.management.ObjectNamegetOname()

        return oname;
    
public java.lang.StringgetPipelineClassName()

        return pipelineClassName;
    
public PipelineStatisticgetPipelineStat()

        return pipelineStat;
    
public intgetPort()

        return port;
    
public PipelinegetProcessorPipeline()

        return processorPipeline;
    
public ProcessorTaskgetProcessorTask()
Return a ProcessorTask from the pool. If the pool is empty, create a new instance.

        ProcessorTask processorTask = null;
        if (recycleTasks) {
            processorTask = processorTasks.poll();
        }
        
        if (processorTask == null){
            processorTask = newProcessorTask(false);
        } 
        
        if ( isMonitoringEnabled() ){
           activeProcessorTasks.offer(processorTask); 
        }

        
        return processorTask;
    
public java.util.concurrent.ConcurrentLinkedQueuegetProcessorTasks()

        return processorTasks;
    
public javax.management.ObjectNamegetProcessorWorkerThreadName()

        return processorWorkerThreadName;
    
public javax.management.ObjectNamegetPwcConnectionQueueMbeanName()

        return pwcConnectionQueueMbeanName;
    
public javax.management.ObjectNamegetPwcFileCacheMbeanName()

        return pwcFileCacheMbeanName;
    
public intgetQueueSizeInBytes()
Get the maximum pending connection this Pipeline can handle.

        return maxQueueSizeInBytes;
    
public PipelinegetReadPipeline()
Return the Pipeline used to handle OP_READ.

        return readPipeline;
    
public ReadTaskgetReadTask(java.nio.channels.SelectionKey key)
Return a ReadTask from the pool. If the pool is empty, create a new instance.

        ReadTask task = null;
        if ( recycleTasks ) {
            task = readTasks.poll();
        }
        
        if (task == null){
            task = newReadTask(); 
        }           

        task.setSelectionKey(key);
        return task;
    
public java.util.concurrent.ConcurrentLinkedQueuegetReadTasks()

        return readTasks;
    
public org.apache.coyote.RequestGroupInfogetRequestGroupInfo()

        return globalRequestProcessor;
    
public java.lang.StringgetRestrictedUserAgents()

        return restrictedUserAgents;
    
public booleangetReuseAddress()

        return reuseAddress;
    
public static java.lang.StringgetRootFolder()

        return rootFolder;
    
public static final com.sun.enterprise.web.connector.grizzly.SelectorThreadgetSelector(int port)
Return the SelectorThread which listen on port, or null if there is no SelectorThread.

        return selectorThreads.get(port);
    
public java.nio.channels.SelectorgetSelector()

        return selector;
    
private synchronized MultiSelectorThreadgetSelectorReadThread()
Return an instance of SelectorReadThread to use for registering OP_READ

        if (curReadThread == readThreads.length)
            curReadThread = 0;
        return readThreads[curReadThread++];
    
public intgetSelectorReadThreadsCount()

        return multiSelectorsCount;
    
public static intgetSelectorTimeout()

        return selectorTimeout;
    
public static final java.util.EnumerationgetSelectors()
Return an Enumeration of the active SelectorThreads

        return selectorThreads.elements();
    
public intgetServerSoTimeout()

        return serverTimeout;
    
public java.net.ServerSocketgetServerSocket()

        return serverSocket;
    
public java.nio.channels.ServerSocketChannelgetServerSocketChannel()

        return serverSocketChannel;
    
public intgetServerTimeout()

        return serverTimeout;
    
public intgetSoLinger()

        return linger;
    
public intgetSoTimeout()

        return socketTimeout;
    
public intgetSocketTimeout()

        return socketTimeout;
    
public intgetSsBackLog()

        return ssBackLog;
    
public booleangetTcpNoDelay()

        return tcpNoDelay;
    
public intgetThreadsIncrement()

        return threadsIncrement;
    
public intgetThreadsTimeout()

        return threadsTimeout;
    
public intgetTimeout()
Get the upload timeout.

        return uploadTimeout;
    
public static java.lang.StringgetWebAppRootPath()
Return the folder's root where application are deployed.

        return rootFolder;
    
protected voidhandleAccept(java.nio.channels.SelectionKey key)
Handle OP_ACCEPT

        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        SocketChannel channel = server.accept();

        if (enableNioLogging){
            logger.log(Level.INFO,"Handling OP_ACCEPT on SocketChannel " + 
                    channel);
        }
        
        if (channel != null) {
            if ( multiSelectorsCount > 1 ) {
                MultiSelectorThread srt = getSelectorReadThread();
                srt.addChannel(channel);
            } else {
                channel.configureBlocking(false);
                SelectionKey readKey = 
                        channel.register(selector, SelectionKey.OP_READ);
                setSocketOptions(((SocketChannel)readKey.channel()).socket());
                readKey.attach(System.currentTimeMillis());
            }

            if (isMonitoringEnabled()) {
                getRequestGroupInfo().increaseCountOpenConnections();
                pipelineStat.incrementTotalAcceptCount();
            }
        }
    
protected voidhandleConnection(java.nio.channels.SelectionKey key)
Handle an incoming operation on the channel. It is always an ACCEPT or a READ.

                                                    
        Task task = null;
        if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT){
            handleAccept(key);
            return;
        } else if ((key.readyOps() & SelectionKey.OP_READ) 
                                                    == SelectionKey.OP_READ) {
            task = handleRead(key);
        } 
 
        if ( ((SocketChannel)key.channel()).isOpen() ) {
            task.execute();
        } else {
            cancelKey(key);
        }
    
protected ReadTaskhandleRead(java.nio.channels.SelectionKey key)
Handle OP_READ

                   
        // disable OP_READ on key before doing anything else 
        key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
        
        if (enableNioLogging){
            logger.log(Level.INFO,"Handling OP_READ on SocketChannel " + 
                    key.channel());
        }      
        
        Object attach = key.attachment();
        if (!defaultAlgorithmInstalled) {
            if (key.isValid() && attach != null && attach instanceof ReadTask){
                key.attach(null);
                return (ReadTask)attach;
            }
        } 
        return getReadTask(key);
    
protected voidinitAlgorithm()
Load using reflection the Algorithm class.

        try{    
            if (classLoader == null){
                algorithmClass = Class.forName(algorithmClassName);
            } else {
                algorithmClass = classLoader.loadClass(algorithmClassName);
            }
            logger.log(Level.FINE,
                       "Using Algorithm: " + algorithmClassName);   
        } catch (ClassNotFoundException ex){
            logger.log(Level.FINE,
                       "Unable to load Algorithm: " + algorithmClassName);        
        }  finally {
            if ( algorithmClass == null ){
                algorithmClass = NoParsingAlgorithm.class;
            }
        }

        defaultAlgorithmInstalled = 
                algorithmClassName.equals(DEFAULT_ALGORITHM) ? true:false;
    
public voidinitEndpoint()
initialized the endpoint by creating the ServerScoketChannel and by initializing the server socket.

        SelectorThreadConfig.configure(this);
        
        initFileCacheFactory();
        initAlgorithm();
        initPipeline();
        initMonitoringLevel();
        
        setName("SelectorThread-" + port);
        
        try{
            // Create the socket listener
            serverSocketChannel = ServerSocketChannel.open();
            selector = Selector.open();

            serverSocket = serverSocketChannel.socket();
            serverSocket.setReuseAddress(reuseAddress);
            if ( inet == null)
                serverSocket.bind(new InetSocketAddress(port),ssBackLog);
            else
                serverSocket.bind(new InetSocketAddress(inet,port),ssBackLog);

            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (SocketException ex){
            throw new BindException(ex.getMessage() + ": " + port);
        }
        
        serverSocket.setSoTimeout(serverTimeout);
        
        if ( multiSelectorsCount > 1 ){
            readThreads = new MultiSelectorThread[multiSelectorsCount];
            initMultiSelectors();
        } 
        initProcessorTask(maxProcessorWorkerThreads);
        initReadTask(minReadQueueLength);                
        SelectorFactory.maxSelectors = maxProcessorWorkerThreads;

        initialized = true;           
        logger.log(Level.FINE,"Initializing Grizzly Non-Blocking Mode");                     
    
protected voidinitFileCacheFactory()
Initialize the fileCacheFactory associated with this instance

        
        if (asyncExecution){
            isFileCacheEnabled = false;
            isLargeFileCacheEnabled = false;
        }
        
        fileCacheFactory = FileCacheFactory.getFactory(port);
        fileCacheFactory.setIsEnabled(isFileCacheEnabled);
        fileCacheFactory.setLargeFileCacheEnabled(isLargeFileCacheEnabled);
        fileCacheFactory.setSecondsMaxAge(secondsMaxAge);
        fileCacheFactory.setMaxCacheEntries(maxCacheEntries);
        fileCacheFactory.setMinEntrySize(minEntrySize);
        fileCacheFactory.setMaxEntrySize(maxEntrySize);
        fileCacheFactory.setMaxLargeCacheSize(maxLargeFileCacheSize);
        fileCacheFactory.setMaxSmallCacheSize(maxSmallFileCacheSize);         
        fileCacheFactory.setIsMonitoringEnabled(isMonitoringEnabled);
        fileCacheFactory.setHeaderBBSize(requestBufferSize);
    
protected voidinitKeepAlivePipeline()
Initialize the keep-alive mechanism.

        keepAlivePipeline = new KeepAlivePipeline();
        keepAlivePipeline.setMaxKeepAliveRequests(maxKeepAliveRequests);
        keepAlivePipeline
            .setKeepAliveTimeoutInSeconds(keepAliveTimeoutInSeconds);
        keepAlivePipeline.setPort(port);
        keepAlivePipeline.setThreadsTimeout(threadsTimeout);

        keepAliveStats.setMaxConnections(maxKeepAliveRequests);
        keepAliveStats.setSecondsTimeouts(keepAliveTimeoutInSeconds);        
    
protected voidinitMonitoringLevel()

        pipelineStat = new PipelineStatistic(port);
        pipelineStat.setQueueSizeInBytes(maxQueueSizeInBytes);
    
protected voidinitMultiSelectors()
Initialize SelectorReadThread used to process OP_READ operations.

        for (int i = 0; i < readThreads.length; i++) {
            readThreads[i] = new SelectorReadThread();
            ((SelectorReadThread)readThreads[i]).countName = i;
            configureReadThread((SelectorReadThread)readThreads[i]);
        }
        curReadThread = 0;
    
protected voidinitPipeline()
Init the Pipelines used by the WorkerThreads.

     
                
        selectorThreads.put(port,this);
        
        initKeepAlivePipeline();
        
        processorPipeline = newPipeline(maxProcessorWorkerThreads, 
                                        minWorkerThreads, "http",
                                        port,Thread.MAX_PRIORITY);  
        processorPipeline.initPipeline();

        if ( maxReadWorkerThreads == 0){
            maxReadWorkerThreads = -1;
            logger.log(Level.WARNING,
                       "http-listener " + port + 
                       " is security-enabled and needs at least 2 threads");
        }
        
        // Only creates the pipeline if the max > 0, and the async mechanism
        // must not be enabled.
        if ( maxReadWorkerThreads > 0 && !asyncExecution){                        
            readPipeline = newPipeline(maxReadWorkerThreads, 
                                       minWorkerThreads, "read", 
                                       port,Thread.NORM_PRIORITY);
            readPipeline.initPipeline();
        } else {
            readPipeline = (maxReadWorkerThreads == 0 ? null:processorPipeline);
        }
    
protected voidinitProcessorTask(int size)
Create a pool of ProcessorTask

        for (int i=0; i < size; i++){           
            processorTasks.offer(newProcessorTask(false));
        }
    
protected voidinitReadTask(int size)
Create a pool of ReadTask

         
        ReadTask task;
        for (int i=0; i < size; i++){
            task = newReadTask();             
            readTasks.offer(task);    
        }
    
public booleanisBufferResponse()

        return bufferResponse;
    
public booleanisDisplayConfiguration()

        return displayConfiguration;
    
public booleanisEnableNioLogging()

        return enableNioLogging;
    
public booleanisFileCacheEnabled()
Is the fileCache enabled.

        return isFileCacheEnabled;
    
public booleanisInitialized()

        return initialized;
    
public booleanisIsMonitoringEnabled()

        return isMonitoringEnabled;
    
public booleanisMonitoringEnabled()
Returns true if monitoring has been enabled, false otherwise.

        return isMonitoringEnabled;
    
public booleanisRecycleTasks()

        return recycleTasks;
    
public booleanisRunning()

        return running;
    
public booleanisTcpNoDelay()

        return tcpNoDelay;
    
public booleanisUseByteBufferView()

        return useByteBufferView;
    
public booleanisUseDirectByteBuffer()

        return useDirectByteBuffer;
    
public static java.util.logging.Loggerlogger()
Return the logger used by the Grizzly classes.

        return logger;
    
protected PipelinenewPipeline(int maxThreads, int minThreads, java.lang.String name, int port, int priority)
Create a new Pipeline instance using the pipelineClassName value.

        
        Class className = null;                               
        Pipeline pipeline = null;                               
        try{           
            if ( classLoader == null ){
                className = Class.forName(pipelineClassName);
            } else {
                className = classLoader.loadClass(pipelineClassName);
            }
            pipeline = (Pipeline)className.newInstance();
        } catch (ClassNotFoundException ex){
            logger.log(Level.WARNING,
                       "Unable to load Pipeline: " + pipelineClassName);
            pipeline = new LinkedListPipeline();
        } catch (InstantiationException ex){
            logger.log(Level.WARNING,
                       "Unable to instantiate Pipeline: "
                       + pipelineClassName);
            pipeline = new LinkedListPipeline();
        } catch (IllegalAccessException ex){
            logger.log(Level.WARNING,
                       "Unable to instantiate Pipeline: "
                       + pipelineClassName);
            pipeline = new LinkedListPipeline();
        }
        
        if (logger.isLoggable(Level.FINE)){
            logger.log(Level.FINE,
                       "http-listener " + port + " uses pipeline: "
                       + pipeline.getClass().getName());
        }
        
        pipeline.setMaxThreads(maxThreads);
        pipeline.setMinThreads(minThreads);    
        pipeline.setName(name);
        pipeline.setPort(port);
        pipeline.setPriority(priority);
        pipeline.setQueueSizeInBytes(maxQueueSizeInBytes);
        pipeline.setThreadsIncrement(threadsIncrement);
        pipeline.setThreadsTimeout(threadsTimeout);
        
        return pipeline;
    
protected ProcessorTasknewProcessorTask(boolean initialize)
Create ProcessorTask objects and configure it to be ready to proceed request.

                                                      
        DefaultProcessorTask task = 
                new DefaultProcessorTask(initialize, bufferResponse);
        return configureProcessorTask(task);       
    
protected ReadTasknewReadTask()
Return a new ReadTask instance

        StreamAlgorithm streamAlgorithm = null;
        
        try{
            streamAlgorithm = (StreamAlgorithm)algorithmClass.newInstance();
        } catch (InstantiationException ex){
            logger.log(Level.WARNING,
                       "Unable to instantiate Algorithm: "+ algorithmClassName);
        } catch (IllegalAccessException ex){
            logger.log(Level.WARNING,
                       "Unable to instantiate Algorithm: " + algorithmClassName);
        } finally {
            if ( streamAlgorithm == null)
                streamAlgorithm = new NoParsingAlgorithm();
        }       
        streamAlgorithm.setPort(port);
        
        ReadTask task = null;
        
        /**
         * For performance reason, we need to avoid calling newInstance() when
         * the default configuration is used.
         */
        if ( !defaultAlgorithmInstalled ) {
            try{
                task = (ReadTask)streamAlgorithm.getReadTask(this).newInstance();
            } catch (InstantiationException ex){
                logger.log(Level.WARNING,
                           "Unable to instantiate Algorithm: "
                        + algorithmClassName);
            } catch (IllegalAccessException ex){
                logger.log(Level.WARNING,
                           "Unable to instantiate Algorithm: " 
                        + algorithmClassName);
            } finally {
                if ( task == null)
                    task = new DefaultReadTask();
            }  
        } else if ( maxReadWorkerThreads > 0 || asyncExecution ){
            task = new AsyncReadTask();
        } else {
            task = new DefaultReadTask();
        }
        task.setSelectorThread(this);     
        task.setPipeline(readPipeline);  
        task.setRecycle(recycleTasks);
        task.initialize(streamAlgorithm, useDirectByteBuffer,useByteBufferView);
       
        return task;
    
public voidpostDeregister()

        // Do nothing
    
public voidpostRegister(java.lang.Boolean registrationDone)

        // Do nothing
    
public voidpreDeregister()

        // Do nothing
    
public javax.management.ObjectNamepreRegister(javax.management.MBeanServer server, javax.management.ObjectName name)

        oname=name;
        mserver=server;
        domain=name.getDomain();
        return name;
    
protected voidrampUpProcessorTask()
Initialize ProcessorTask

        Iterator<ProcessorTask> iterator = processorTasks.iterator();
        while (iterator.hasNext()) {
            iterator.next().initialize();
        }
    
protected voidreconfigureAsyncExecution()
Reconfigure Grizzly Asynchronous Request Processing(ARP) internal objects.

        for(ProcessorTask task :processorTasks){
            if (task instanceof DefaultProcessorTask) {
                ((DefaultProcessorTask)task)
                    .setEnableAsyncExecution(asyncExecution);
                ((DefaultProcessorTask)task).setAsyncHandler(asyncHandler);  
            }
        }
        
        readTasks.clear();
        initReadTask(minReadQueueLength);   
    
protected voidregisterComponents()
Register JMX components.


        if( this.domain != null  && jmxManagement != null) {

            try {
                globalRequestProcessorName = new ObjectName(
                    domain + ":type=GlobalRequestProcessor,name=http" + port);
                jmxManagement.registerComponent(globalRequestProcessor,
                                                globalRequestProcessorName,
                                                null);
 
                keepAliveMbeanName = new ObjectName(
                    domain + ":type=PWCKeepAlive,name=http" + port);
                jmxManagement.registerComponent(keepAliveStats,
                                                keepAliveMbeanName,
                                                null);

                pwcConnectionQueueMbeanName = new ObjectName(
                    domain + ":type=PWCConnectionQueue,name=http" + port);
                jmxManagement.registerComponent(pipelineStat,
                                                pwcConnectionQueueMbeanName,
                                                null);
                
                pwcFileCacheMbeanName = new ObjectName(
                    domain + ":type=PWCFileCache,name=http" + port);
                jmxManagement.registerComponent(fileCacheFactory,
                                                pwcFileCacheMbeanName,
                                                null);                
            } catch (Exception ex) {
                logger.log(Level.WARNING,
                           "selectorThread.mbeanRegistrationException",
                           new Object[]{new Integer(port),ex});
            }
        }

    
public voidregisterKey(java.nio.channels.SelectionKey key)
Register a SelectionKey to this Selector running of this thread.

        if (key == null) return;
        
        if (keepAlivePipeline.dropConnection()) {
            cancelKey(key);
            return;
        }
        
        if (defaultAlgorithmInstalled){
            key.attach(null);
        }
        
        if (enableNioLogging){
            logger.log(Level.INFO,
                    "Registering SocketChannel for keep alive " +  
                    key.channel());
        }         
        // add SelectionKey & Op to list of Ops to enable
        keysToEnable.add(key);
        // tell the Selector Thread there's some ops to enable
        selector.wakeup();
        // wakeup() will force the SelectorThread to bail out
        // of select() to process your registered request
    
public voidremoveCacheEntry(java.lang.String contextPath)
Remove a context path from the FileCache.

  
        ConcurrentHashMap<String,FileCacheEntry> 
                cachedEntries = fileCacheFactory.getCache();
        
        if ( cachedEntries == null){
            return;
        }
        
        Iterator<String> iterator = cachedEntries.keySet().iterator();
        String cachedPath;
        while (iterator.hasNext()){
            cachedPath = iterator.next();
            if ( cachedPath.startsWith(contextPath) ){
                cachedEntries.remove(cachedPath).run();
            }            
        }
    
public voidreturnTask(Task task)
Returns the Task object to the pool.

        // Returns the object to the pool.
        if (task != null) {
            if (task.getType() == Task.PROCESSOR_TASK){
                                
                if ( isMonitoringEnabled() ){
                   activeProcessorTasks.remove(((DefaultProcessorTask)task));
                }  
                
                processorTasks.offer((DefaultProcessorTask)task);
            } else if (task.getType() == Task.READ_TASK){
                readTasks.offer((ReadTask)task);               
            }
        }
    
public voidrun()
Start the endpoint (this)

        try{
            startEndpoint();
        } catch (Exception ex){
            logger.log(Level.SEVERE,"selectorThread.errorOnRequest", ex);
        }
    
public voidsetActiveProcessorTasks(java.util.concurrent.ConcurrentLinkedQueue activeProcessorTasks)

        this.activeProcessorTasks = activeProcessorTasks;
    
public voidsetAdapter(org.apache.coyote.Adapter adapter)
Set the associated adapter.

param
adapter the new adapter

        this.adapter = adapter;
    
public voidsetAddress(java.net.InetAddress inet)

        this.inet=inet;
    
public voidsetAlgorithmClass(java.lang.Class algorithmClass)

        this.algorithmClass = algorithmClass;
    
public voidsetAlgorithmClassName(java.lang.String algorithmClassName)

        this.algorithmClassName = algorithmClassName;
    
public voidsetAsyncHandler(AsyncHandler asyncHandler)
Set the AsyncHandler used when asynchronous execution is enabled.

        this.asyncHandler = asyncHandler;     
    
public voidsetBufferResponse(boolean bufferResponse)
trueif the reponse willk be buffered.

        this.bufferResponse = bufferResponse;
    
public voidsetBufferSize(int requestBufferSize)
Set the request input buffer size

        this.requestBufferSize = requestBufferSize;
    
public voidsetClassLoader(java.lang.ClassLoader classLoader)
Set the ClassLoader used to load configurable classes (Pipeline, StreamAlgorithm).

        this.classLoader = classLoader;
    
public voidsetCompressableMimeTypes(java.lang.String compressableMimeTypes)

        this.compressableMimeTypes = compressableMimeTypes;
    
public voidsetCompression(java.lang.String compression)

        this.compression = compression;
    
public voidsetCompressionMinSize(int compressionMinSize)

        this.compressionMinSize = compressionMinSize;
    
public voidsetCurReadThread(int curReadThread)

        this.curReadThread = curReadThread;
    
public voidsetCurrentConnectionNumber(int currentConnectionNumber)

        this.currentConnectionNumber = currentConnectionNumber;
    
public voidsetDefaultResponseType(java.lang.String defaultResponseType)

        this.defaultResponseType = defaultResponseType;
    
public voidsetDisableUploadTimeout(boolean isDisabled)
Set the flag to control upload time-outs.

        disableUploadTimeout = isDisabled;
    
public voidsetDisplayConfiguration(boolean displayConfiguration)

        this.displayConfiguration = displayConfiguration;
    
public voidsetDomain(java.lang.String domain)

        this.domain = domain;
    
public voidsetEnableAsyncExecution(boolean asyncExecution)
Enable the AsyncHandler used when asynchronous

        this.asyncExecution = asyncExecution;     
        if (running){
            reconfigureAsyncExecution();
        }
    
public voidsetEnableNioLogging(boolean enableNioLogging)

        this.enableNioLogging = enableNioLogging;
    
public voidsetFileCacheIsEnabled(boolean isFileCacheEnabled)
Is the file caching mechanism enabled.

        this.isFileCacheEnabled = isFileCacheEnabled;
    
public voidsetForcedRequestType(java.lang.String forcedRequestType)

        this.forcedRequestType = forcedRequestType;
    
public voidsetGlobalRequestProcessor(org.apache.coyote.RequestGroupInfo globalRequestProcessor)

        this.globalRequestProcessor = globalRequestProcessor;
    
public voidsetGlobalRequestProcessorName(javax.management.ObjectName globalRequestProcessorName)

        this.globalRequestProcessorName = globalRequestProcessorName;
    
public voidsetInet(java.net.InetAddress inet)

        this.inet = inet;
    
public voidsetInitialized(boolean initialized)

        this.initialized = initialized;
    
public voidsetIsMonitoringEnabled(boolean isMonitoringEnabled)

        this.isMonitoringEnabled = isMonitoringEnabled;
    
public voidsetIsWaiting(boolean isWaiting)

        this.isWaiting = isWaiting;
    
public voidsetKaTimeout(int kaTimeout)

        this.kaTimeout = kaTimeout;
    
public voidsetKeepAliveMbeanName(javax.management.ObjectName keepAliveMbeanName)

        this.keepAliveMbeanName = keepAliveMbeanName;
    
public voidsetKeepAlivePipeline(KeepAlivePipeline keepAlivePipeline)

        this.keepAlivePipeline = keepAlivePipeline;
    
public voidsetKeepAliveStats(KeepAliveStats keepAliveStats)

        this.keepAliveStats = keepAliveStats;
    
public voidsetKeepAliveThreadCount(int threadCount)
Sets the number of keep-alive threads.

param
threadCount Number of keep-alive threads

        keepAlivePipeline.setMaxThreads(threadCount);
    
public voidsetKeepAliveTimeoutInSeconds(int timeout)
Sets the number of seconds before a keep-alive connection that has been idle times out and is closed.

param
timeout Keep-alive timeout in number of seconds

        keepAliveTimeoutInSeconds = timeout;
        keepAliveStats.setSecondsTimeouts(timeout);
    
public voidsetKeysToEnable(java.util.concurrent.ConcurrentLinkedQueue keysToEnable)

        this.keysToEnable = keysToEnable;
    
public voidsetLargeFileCacheEnabled(boolean isLargeEnabled)
Is the large file cache support enabled.

        this.isLargeFileCacheEnabled = isLargeEnabled;
    
public voidsetLinger(int linger)

        this.linger = linger;
    
public static voidsetLogger(java.util.logging.Logger l)
Set the logger used by this instance.

        if ( l != null )
            logger = l;
    
public voidsetManagement(Management jmxManagement)

        this.jmxManagement = jmxManagement;
    
public voidsetMaxCacheEntries(int mEntries)
Set the maximum entries this cache can contains.

        maxCacheEntries = mEntries;
    
public voidsetMaxEntrySize(long mEntrySize)
Set the maximum size a FileCacheEntry can have.

        maxEntrySize = mEntrySize;
    
public voidsetMaxHttpHeaderSize(int maxHttpHeaderSize)

        this.maxHttpHeaderSize = maxHttpHeaderSize;
    
public voidsetMaxKeepAliveRequests(int mkar)
Set the maximum number of Keep-Alive requests that we will honor.

        maxKeepAliveRequests = mkar;
    
public voidsetMaxLargeCacheSize(long mCacheSize)
Set the maximum cache size

        maxLargeFileCacheSize = mCacheSize;
    
public voidsetMaxPostSize(int maxPostSize)

        this.maxPostSize = maxPostSize;
    
public voidsetMaxProcessorWorkerThreads(int maxProcessorWorkerThreads)

        this.maxProcessorWorkerThreads = maxProcessorWorkerThreads;
    
public voidsetMaxQueueSizeInBytes(int maxQueueSizeInBytes)

        this.maxQueueSizeInBytes = maxQueueSizeInBytes;
    
public voidsetMaxReadWorkerThreads(int maxReadWorkerThreads)

        this.maxReadWorkerThreads = maxReadWorkerThreads;
    
public voidsetMaxSmallCacheSize(long mCacheSize)
Set the maximum cache size

        maxSmallFileCacheSize = mCacheSize;
    
public voidsetMaxSpareThreads(int maxThreads)

    
public voidsetMaxThreads(int maxThreads)

        if ( maxThreads == 1 ) {
            maxProcessorWorkerThreads = 5;
        } else {
            maxProcessorWorkerThreads = maxThreads;
        }
    
public voidsetMinEntrySize(long mSize)
Set the maximum size a FileCacheEntry can have.

        minEntrySize = mSize;
    
public voidsetMinProcessorQueueLength(int minProcessorQueueLength)

        this.minProcessorQueueLength = minProcessorQueueLength;
    
public voidsetMinReadQueueLength(int minReadQueueLength)

        this.minReadQueueLength = minReadQueueLength;
    
public voidsetMinSpareThreads(int minSpareThreads)

        this.minSpareThreads = minSpareThreads;
    
public voidsetMinThreads(int minWorkerThreads)
The minimun threads created at startup.

        this.minWorkerThreads = minWorkerThreads;
    
public voidsetMinWorkerThreads(int minWorkerThreads)

        this.minWorkerThreads = minWorkerThreads;
    
public voidsetMserver(javax.management.MBeanServer mserver)

        this.mserver = mserver;
    
public voidsetNextKeysExpiration(long nextKeysExpiration)

        this.nextKeysExpiration = nextKeysExpiration;
    
public voidsetNoCompressionUserAgents(java.lang.String noCompressionUserAgents)

        this.noCompressionUserAgents = noCompressionUserAgents;
    
public voidsetOname(javax.management.ObjectName oname)

        this.oname = oname;
    
public voidsetPipelineClassName(java.lang.String pipelineClassName)

        this.pipelineClassName = pipelineClassName;
    
public voidsetPipelineStat(PipelineStatistic pipelineStat)

        this.pipelineStat = pipelineStat;
    
public voidsetPort(int port)

        this.port=port;
    
public voidsetProcessorPipeline(Pipeline processorPipeline)

        this.processorPipeline = processorPipeline;
    
public voidsetProcessorTasks(java.util.concurrent.ConcurrentLinkedQueue processorTasks)

        this.processorTasks = processorTasks;
    
public voidsetProcessorWorkerThreadName(javax.management.ObjectName processorWorkerThreadName)

        this.processorWorkerThreadName = processorWorkerThreadName;
    
public voidsetPwcConnectionQueueMbeanName(javax.management.ObjectName pwcConnectionQueueMbeanName)

        this.pwcConnectionQueueMbeanName = pwcConnectionQueueMbeanName;
    
public voidsetPwcFileCacheMbeanName(javax.management.ObjectName pwcFileCacheMbeanName)

        this.pwcFileCacheMbeanName = pwcFileCacheMbeanName;
    
public voidsetReadPipeline(Pipeline readPipeline)

        this.readPipeline = readPipeline;
    
public voidsetReadTasks(java.util.concurrent.ConcurrentLinkedQueue readTasks)

        this.readTasks = readTasks;
    
public voidsetRecycleTasks(boolean recycleTasks)

        this.recycleTasks = recycleTasks;
    
public voidsetRestrictedUserAgents(java.lang.String restrictedUserAgents)

        this.restrictedUserAgents = restrictedUserAgents;
    
public voidsetReuseAddress(boolean reuseAddress)

        this.reuseAddress = reuseAddress;
    
public static voidsetRootFolder(java.lang.String aRootFolder)

        rootFolder = aRootFolder;
    
public voidsetRunning(boolean running)

        this.running = running;
    
public voidsetSecondsMaxAge(int sMaxAges)
The timeout in seconds before remove a FileCacheEntry from the fileCache

        secondsMaxAge = sMaxAges;
    
public voidsetSelector(java.nio.channels.Selector selector)

        this.selector = selector;
    
public voidsetSelectorReadThreadsCount(int multiSelectorsCount)

        this.multiSelectorsCount = multiSelectorsCount;
    
public static voidsetSelectorTimeout(int aSelectorTimeout)

        selectorTimeout = aSelectorTimeout;
    
public voidsetServerSoTimeout(int i)

        serverTimeout=i;
    
public voidsetServerSocket(java.net.ServerSocket serverSocket)

        this.serverSocket = serverSocket;
    
public voidsetServerSocketChannel(java.nio.channels.ServerSocketChannel serverSocketChannel)

        this.serverSocketChannel = serverSocketChannel;
    
public voidsetServerTimeout(int timeout)
Sets the timeout in ms of the server sockets created by this server. This method allows the developer to make servers more or less responsive to having their server sockets shut down.

By default this value is 1000ms.

        this.serverTimeout = timeout;
    
public voidsetSoLinger(int i)

        linger=i;
    
public voidsetSoTimeout(int i)

        socketTimeout=i;
    
protected voidsetSocketOptions(java.net.Socket socket)

        try{
            if(linger >= 0 ) {
                socket.setSoLinger( true, linger);
            }
        } catch (SocketException ex){
            logger.log(Level.WARNING,
                        "setSoLinger exception ",ex);
        }
        
        try{
            if( tcpNoDelay )
                socket.setTcpNoDelay(tcpNoDelay);
        } catch (SocketException ex){
            logger.log(Level.WARNING,
                        "setTcpNoDelay exception ",ex);
        }
        
        try{
            if ( maxReadWorkerThreads != 0)
                socket.setReuseAddress(reuseAddress);
        } catch (SocketException ex){
            logger.log(Level.WARNING,
                        "setReuseAddress exception ",ex);
        }   
        
        try{
            if(oOBInline){
                socket.setOOBInline(oOBInline);
            }
        } catch (SocketException ex){
            logger.log(Level.WARNING,
                        "setOOBInline exception ",ex);
        }        
        
    
public voidsetSocketTimeout(int socketTimeout)

        this.socketTimeout = socketTimeout;
    
public voidsetSsBackLog(int ssBackLog)

        this.ssBackLog = ssBackLog;
    
public voidsetTcpNoDelay(boolean b)

        tcpNoDelay=b;
    
public voidsetThreadsIncrement(int threadsIncrement)

        this.threadsIncrement = threadsIncrement;
    
public voidsetThreadsTimeout(int threadsTimeout)

        this.threadsTimeout = threadsTimeout;
    
public voidsetUploadTimeout(int uploadTimeout)
Set the upload timeout.

        this.uploadTimeout = uploadTimeout ;
    
public voidsetUseByteBufferView(boolean useByteBufferView)

        this.useByteBufferView = useByteBufferView;
    
public voidsetUseDirectByteBuffer(boolean useDirectByteBuffer)

        this.useDirectByteBuffer = useDirectByteBuffer;
    
public static voidsetWebAppRootPath(java.lang.String rf)
Set the document root folder

        rootFolder = rf;
    
public voidstartEndpoint()
Start the Acceptor Thread and wait for incoming connection, in a non blocking mode.

        running = true;
        
        kaTimeout = keepAliveTimeoutInSeconds * 1000;
        rampUpProcessorTask();
        registerComponents();
 
        displayConfiguration();

        startPipelines();
        startListener();
    
protected voidstartListener()
Start a non blocking Selector object.

        synchronized(lock){
            while (running && selector.isOpen()) {
                doSelect();
            }       

            try{
                closeActiveConnections();
                stopPipelines();
                stopSelectorReadThread();

                try{
                    if ( serverSocket != null )
                        serverSocket.close();
                } catch (Throwable ex){
                    logger.log(Level.SEVERE,
                            "selectorThread.closeSocketException",ex);
                }

                try{
                    if ( serverSocketChannel != null)
                        serverSocketChannel.close();
                } catch (Throwable ex){
                    logger.log(Level.SEVERE,
                            "selectorThread.closeSocketException",ex);
                }

                try{
                    if ( selector != null)
                        selector.close();
                } catch (Throwable ex){
                    logger.log(Level.SEVERE,
                            "selectorThread.closeSocketException",ex);
                }
                unregisterComponents();
            } catch (Throwable t){
                logger.log(Level.SEVERE,"selectorThread.stopException",t);
            } 
        }
    
protected voidstartPipelines()
Starts the Pipeline used by this Selector

        if (readPipeline != null){
            readPipeline.startPipeline();
        }

        processorPipeline.startPipeline();        
    
public voidstopEndpoint()

        if (!running) return;
        running = false;
        synchronized(lock){
            // Wait for the main thread to stop.
            clearTasks();
        }
    
protected voidstopPipelines()
Stop the Pipeline used by this Selector

        if ( keepAlivePipeline != null )
            keepAlivePipeline.stopPipeline();        

        if (readPipeline != null){
            readPipeline.stopPipeline();
        }
        
        processorPipeline.stopPipeline();

    
private voidstopSelectorReadThread()
Stop the extra SelectorReadThread

        if ( readThreads != null ){
            for (int i = 0; i < readThreads.length; i++) {
                readThreads[i].stopEndpoint();       
            }
        }
    
protected voidunregisterComponents()
Unregister components.


        if (this.domain != null && jmxManagement != null) {
            try {
                if (globalRequestProcessorName != null) {
                    jmxManagement.unregisterComponent(globalRequestProcessorName);
                }
                if (keepAliveMbeanName != null) {
                    jmxManagement.unregisterComponent(keepAliveMbeanName);
                }
                if (pwcConnectionQueueMbeanName != null) {
                    jmxManagement.unregisterComponent(pwcConnectionQueueMbeanName);
                }
                if (pwcFileCacheMbeanName != null) {
                    jmxManagement.unregisterComponent(pwcFileCacheMbeanName);
                }                    
            } catch (Exception ex) {
                logger.log(Level.WARNING,
                           "mbeanDeregistrationException",
                           new Object[]{new Integer(port),ex});
            }
        }
    
public voidwakeup()
Wakes up the Selector associated with this thread.

        selector.wakeup();