/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.web.connector.grizzly;

import com.sun.enterprise.web.connector.grizzly.handlers.NoParsingHandler;
import java.io.IOException;
import java.net.Socket;

/**
 * Process a blocking socket. By default, SSL is using blocking mode.
 *
 * @author Jean-Francois Arcand
 */
public class ReadBlockingTask extends ReadTask{
    
    /**
     * The <code>PipelineStatistic</code> objects used when gathering statistics.
     */
    protected PipelineStatistic pipelineStat;
            
    
    /**
     * The <code>Handler</code> used to pre-process the request.
     */
    private NoParsingHandler handler;
    
            
    public ReadBlockingTask(){
        type = READ_TASK;
        taskContext = new TaskContext();
        taskEvent = new TaskEvent(taskContext);
        taskEvent.setStatus(TaskEvent.START);
    }
    
    
    /**
     * Force this task to always use the same <code>ProcessorTask</code> 
     * instance.
     */
    public void attachProcessor(ProcessorTask processorTask){
        handler = new NoParsingHandler(selectorThread.getPort());
        
        this.processorTask = processorTask;
        processorTask.addTaskListener(this);
        addTaskListener(processorTask);
        
        processorTask.useAlternateKeepAlive(false);
        processorTask.setHandler(handler);  
    }
    
    
    /**
     * Dispatch an Http request to a <code>ProcessorTask</code>
     */
    public void doTask() throws IOException {
        handler.attachChannel(processorTask.getSocket().getChannel());

        // Notify the ProcessorTask that we are ready to process the request.
        fireTaskEvent(taskEvent);
    }
    
    
    /**
     * Gracefully close the blocking socket.
     */
    protected void finishConnection(){
        Socket socket = processorTask.getSocket();
        
        // Are we using SSL
        if (selectorThread.getSSLImplementation() == null){
            try{
                if (!socket.isInputShutdown()){
                    socket.shutdownInput();
                }
            } catch (IOException ioe){
                ;
            }
            try{
                if (!socket.isOutputShutdown()){
                    socket.shutdownOutput();
                }
            } catch (IOException ex){
                ;
            }
        }

        try{
            socket.close();   
        } catch (IOException ex){
            ;
        } finally {
            if (isMonitoringEnabled()) {
                getRequestGroupInfo().decreaseCountOpenConnections();
            }
        }
    } 

    
    /**
     * Receive notification from other <code>Task</code> and recycle this task.
     */
    public void taskEvent(TaskEvent event){
        if ( event.getStatus() == TaskEvent.COMPLETED){
            finishConnection();

            // We must recycle only if we are sure ProcessorTask has completed its
            // processing. If not, 
            if (recycle) {
                processorTask.recycle();
                selectorThread.returnTask(this);
            }
        }
    }


    /**
     * Return the current <code>Socket</code> used by this instance
     * @return socket the current <code>Socket</code> used by this instance
     */
    protected Socket getSocket(){
        return processorTask.getSocket();
    }
    
    
    /**
     * Set the <code>PipelineStatistic</code> object used to gather statistic;
     */
    public void setPipelineStatistic(PipelineStatistic pipelineStatistic){
        this.pipelineStat = pipelineStatistic;
    }
    
    
    /**
     * Return the <code>PipelineStatistic</code> object used
     * to gather statistic;
     */
    public PipelineStatistic getPipelineStatistic(){
        return pipelineStat;
    }
}
