package net.mar;
import java.sql.SQLException;
import java.sql.Statement;



/*
 * Created on 13-May-2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author mar
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class CancelThread implements Runnable{
    Statement stmt;
    boolean cancelled=false;
    boolean finished=false;
    StringBuffer newStr;
    int timeout=3600; // default 1 hour
    
    public CancelThread(){
        
    }
    
    /**
     * @param newStmt
     * @param timeout
     */
    public CancelThread(Statement stmt, int timeout) {
        super();
        this.stmt = stmt;
        this.timeout = timeout;
    }
    
    public void setStmt(Statement stmt){
        this.stmt=stmt;
    }
    public void setTimeoutInSecomds(int duration){
        timeout=duration;
    }
    public synchronized boolean getCancelled(){
        return cancelled;
    }
    public synchronized void setFinished(){
        finished=true;
    }
    
    public synchronized void doCancel() {
     //   System.out.println("doCancel "+finished +" "+stmt);
        if (stmt != null && !finished){
            try {
               // System.out.println("cancelling");
            stmt.cancel();
            cancelled=true;
            
            }
            catch (SQLException se){
            //System.out.println(se);   
            }
            catch (Exception e) {
                
            }       
    } 
        stmt=null;
    }
    public void run() {
        try {
    //    System.out.println("running");
        Thread.sleep(timeout*1000);
    //    System.out.println("cancelling");
        doCancel();
        }
        catch (InterruptedException ie){
            // If interrupted this might be from detecting browser closing or query finished so
            // do a cancel anyway. If finished will throw an exception saying stmt already closed
            
            //System.out.println("I've been interupted "+newStr);           
          doCancel();
    }
        
    }
}
    

