/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */

package org.bodington.server;

import java.util.logging.*;



import org.bodington.database.*;
import org.bodington.server.realm.*;
import org.bodington.server.resources.*;
import org.bodington.text.*;

import java.lang.reflect.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Calendar;

public class JobScheduler extends java.lang.Thread
    {
    private static JobScheduler the_instance;


    private boolean started=false;
    private boolean stopped=false;
    
    public String error;

    public int pause = 30*1000;  // thirty seconds worth of milliseconds
    
    public static JobScheduler getJobScheduler( boolean create )
        {
        if ( the_instance == null && create )
            the_instance = new JobScheduler();
        return the_instance;
        }
        
    private JobScheduler()
        {
        error=null;
        this.start();
        
        synchronized( this )
            {
            for ( int i=0; !started && !stopped && i<30; i++  )
                {
                try
                    {
                    this.wait( 10000 );
                    }
                catch ( InterruptedException iex )
                    {
                    }
                }
            }
        }


    public void deleteJob( Job job )
        throws BuildingServerException
	{
	Enumeration enum = JobResult.findJobResults( "job_id = " + job.getJobId() );
	JobResult job_result;
	while ( enum.hasMoreElements() )
	    {
	    job_result = (JobResult)enum.nextElement();
	    job_result.delete();
	    }
	job.delete();
	}
	
    public void addJob( String session_name, String method_name, String parameter )
        throws BuildingServerException
        {
        addJob( session_name, method_name, parameter, Job.REPEAT_TYPE_ONCE );
        }

    public void addJob( String session_name, String method_name, String parameter, int repeat_type )
        throws BuildingServerException
        {
	int i;
        User user = (User)BuildingContext.getContext().getUser();
        Resource resource = BuildingContext.getContext().getResource();
        
        /*
        if ( user == null || !user.getUserId().equals( user_id ) )
            throw new BuildingServerException( "Only sysadmin can add jobs to scheduler." );
        */
            
        Job j = new Job();
        j.setUserId( user.getUserId() );
        j.setResourceId( resource.getResourceId() );
        j.setSessionName( session_name );
        j.setMethodName( method_name );
        j.setParameter( parameter );
        j.setState( Job.STATE_OVERDUE );
        j.setSubmissionTime( new java.sql.Timestamp( System.currentTimeMillis() )       );
        j.setFromTime( new java.sql.Timestamp( System.currentTimeMillis() )       );
        j.setToTime( null );
	j.setRepeatSpec( 0 );
	
	Calendar cal = Calendar.getInstance();
	cal.setTime( j.getFromTime() );
	
	switch ( repeat_type )
	    {
	    case Job.REPEAT_TYPE_DAILY:
		j.setRepeatType( Job.REPEAT_TYPE_DAILY );
		break;
	    case Job.REPEAT_TYPE_WEEKLY:
		j.setRepeatType( Job.REPEAT_TYPE_WEEKLY );
		j.setRepeatSpecDayOfWeek( cal.get( Calendar.DAY_OF_WEEK ), true );
		break;
	    case Job.REPEAT_TYPE_MONTHLY_DAY:
		j.setRepeatType( Job.REPEAT_TYPE_MONTHLY_DAY );
		j.setRepeatSpecDayOfMonth( cal.get( Calendar.DATE ) );
		for ( i=Calendar.JANUARY; i<= Calendar.DECEMBER; i++ )
		    j.setRepeatSpecMonthOfYear( i, true );
		break;
	    case Job.REPEAT_TYPE_MONTHLY_WEEK:
		j.setRepeatType( Job.REPEAT_TYPE_MONTHLY_WEEK );
		j.setRepeatSpecWeekOfMonth( 1, Calendar.MONDAY, true );
		for ( i=Calendar.JANUARY; i<= Calendar.DECEMBER; i++ )
		    j.setRepeatSpecMonthOfYear( i, true );
		break;
	    default:
		j.setRepeatType( Job.REPEAT_TYPE_ONCE );
		break;
	    }
	    
        j.setRepeatPeriod( 1 );
	j.setFirstExecutionTime();
        j.save();
        }

    private void setJobState( Job j, int s )
        {
        try
            {
            j.setState( s );
            j.save();
            }
        catch ( Exception ex )
            {
	    Logger.getLogger( "org.bodington" ).logp( 
		Level.SEVERE, 
		"JobScheduler", 
		"setJobState", 
		ex.getMessage(), 
		ex );
            }
        }
        
    public void run()
        {
        Logger.getLogger( "org.bodington" ).info( "JobScheduler starting." );
        try
            {
            BuildingContext context=null;
            User sysadmin;
    		PrimaryKey sysadmin_user_id;
            
            synchronized ( this )
                {
		        try
			        {
                	context = BuildingContext.startContext();
                	context.setPoolOwner( "job_scheduler" );
        	        PassPhrase pass = PassPhrase.findPassPhraseByUserName( "sysadmin" );
        	        if ( pass==null )
        		        {
				        error = "Unknown sysadmin.";
	        	        stopped=true;
        		        return;
        		        }
        	        sysadmin = pass.getUser();
        	        Logger.getLogger( "org.bodington" ).fine( "User = " + sysadmin );
        	        Logger.getLogger( "org.bodington" ).fine( sysadmin.getUserId().toString() );
        	        sysadmin_user_id = sysadmin.getUserId();
        	        }
                catch ( Exception ex )
        	        {
        	        error = "Problem starting scheduler: " + ex.getMessage();
			Logger.getLogger( "org.bodington" ).logp( 
			    Level.SEVERE, 
			    "JobScheduler", 
			    "run", 
			    error, 
			    ex );
			stopped=true;
        	        return;
        	        }
        	    finally
        	    	{
                	if ( context!=null )
   	            		context.endContext();
        	    	}

                started=true;
                this.notify();
                }
            
	        Logger.getLogger( "org.bodington" ).info( "JobScheduler started." );
            
            int i;
            long now, exec;
            Enumeration enum;
            Job j;
	    JobResult job_result;
	    BigString message;
            Class c;
            Method m;
            JobSession session;
            Vector job_list=new Vector();
            User user;
            Class[] parameter_def = new Class[1];
	    parameter_def[0] = String.class;
	    Object[] parameter_list = new Object[1];
	    
            while ( true )
                {
                
                try
                    {
                    Logger.getLogger( "org.bodington" ).info( "JobScheduler looking for outstanding jobs." );

                	// start a context for sysadmin to fetch list of outstanding jobs
                	BuildingContext.startContext();
                	context = BuildingContext.getContext();
                	context.setPoolOwner( "job_scheduler" );
        	    	context.setUser( sysadmin );
	            	//context.setAuthenticationMethod( "internal" );
        			
                    enum = Job.findJobs( "state = " + Job.STATE_OVERDUE, "execution_time" );
                    
                	job_list.removeAllElements();
                	while ( enum.hasMoreElements() )
                    	{
                    	// stop adding jobs when the first one that is for execution later
                    	// is found
                    	j = (Job)enum.nextElement();
                    	if ( j.getExecutionTime().getTime() > System.currentTimeMillis() )
                        	break;
                    	job_list.addElement( j );
                    	}
	                    
                	// end the sysadmin context now the jobs are loaded
                	context.endContext();
                    }
                catch ( BuildingServerException bsex )
                    {
		    Logger.getLogger( "org.bodington" ).logp( 
			Level.SEVERE, 
			"JobScheduler", 
			"run", 
			"Error finding jobs to run: " + bsex.getMessage(), 
			bsex );
                    continue;
                    }
                    
                Logger.getLogger( "org.bodington" ).info( "JobScheduler finished looking for outstanding jobs." );
                
                    
                for ( i=0; i<job_list.size(); i++ )
                	{
                    j = (Job)job_list.elementAt( i );
                    
                    
		    message = null;
		    job_result = null;
                    Logger.getLogger( "org.bodington" ).fine( "Executing " + j.getSessionName() + "." + j.getMethodName() + "()" );
                    try
                        {
                        context = null;

                        // now we need a context for the owner of the job
			BuildingContext.startContext();
			context = BuildingContext.getContext();
			context.setPoolOwner( "job_scheduler" );
			user = User.findUser( j.getUserId() );
			if ( user == null )
				throw new NullPointerException( "Can't find owner of job." );
			context.setUser( user );
			//context.setAuthenticationMethod( "internal" );

			message = new BigString();
			message.setString( "Job Starting." );
			message.save();
			
			job_result = new JobResult();
			job_result.setJobId( j.getJobId() );
			job_result.setResultCode( JobResult.RESULT_INCOMPLETE );
			job_result.setBigStringId( message.getBigStringId() );
			job_result.setExecutionTime( new java.sql.Timestamp( System.currentTimeMillis() ) );
			job_result.save();
			
			context.setJobResult( job_result );
			
                        setJobState( j, Job.STATE_EXECUTING );
                        
                        c = Class.forName( j.getSessionName() );
                        if ( c==null )
                            {
                            Logger.getLogger( "org.bodington" ).severe( "Session class not found." );
			    message.setString( "Session class not found." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        if ( !org.bodington.server.JobSession.class.isAssignableFrom( c ) )
                            {
                            Logger.getLogger( "org.bodington" ).severe( "Session class isn't a type of JobSession." );
			    message.setString( "Session class isn't a type of JobSession." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        m = c.getMethod( j.getMethodName(), parameter_def );
                            
                        if ( m==null )
                            {
                            Logger.getLogger( "org.bodington" ).severe( "Method not found in session class." );
			    message.setString( "Method not found in session class." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        session = (JobSession)c.newInstance();
                        
                        
                        
                        // call the job now the context is set up for job owner
			parameter_list[0] = j.getParameter();
                        m.invoke( session, parameter_list );
                        
			job_result.setResultCode( JobResult.RESULT_OK );
			job_result.save();

			j.setState( Job.STATE_COMPLETED );
			// repeat job if necessary
			j.setNextExecutionTime();
			j.save();
			/*
                    	if ( j.getRepeatPeriod() > 0 )
			    {
			    now = System.currentTimeMillis();
				    exec = j.getExecutionTime().getTime();
			    while ( exec < now )
				    exec += (1000L * (long)j.getRepeatPeriod() );

			    j.setExecutionTime( new java.sql.Timestamp( exec ) );
			    setJobState( j, Job.STATE_OVERDUE );
			    }
                    	else
			    setJobState( j, Job.STATE_COMPLETED );
			*/
			}
		    catch ( InvocationTargetException itex )
                	{
                	Throwable targetex = itex.getTargetException();
			Logger.getLogger( "org.bodington" ).logp( 
			    Level.SEVERE, 
			    "JobScheduler", 
			    "run", 
			    "Error running job: " + targetex.getMessage(), 
			    targetex );
			try
			    {
			    if ( message!=null )
				{
				message.setString( message.getString() + "\nException executing job." + targetex );
				message.save();
				}
			    if ( job_result!=null )
				{
				job_result.setResultCode( JobResult.RESULT_ERROR );
				job_result.save();
				}
			    }
			catch ( Exception exin )
			    {
			    Logger.getLogger( "org.bodington" ).logp( 
				Level.SEVERE, 
				"JobScheduler", 
				"run", 
				"Error recording exception in job: " + exin.getMessage(), 
				exin );
			    }
			setJobState( j, Job.STATE_FAILED );
                        continue;
                	}
                    catch ( Exception ex )
                        {
			Logger.getLogger( "org.bodington" ).logp( 
			    Level.SEVERE, 
			    "JobScheduler", 
			    "run", 
			    "Exeption running job: " + ex.getMessage(), 
			    ex );
			try
			    {
			    if ( message!=null )
				{
				message.setString( message.getString() + "\nException executing job." + ex );
				message.save();
				}
			    if ( job_result!=null )
				{
				job_result.setResultCode( JobResult.RESULT_ERROR );
				job_result.save();
				}
			    }
			catch ( Exception exin )
			    {
			    Logger.getLogger( "org.bodington" ).logp( 
				Level.SEVERE, 
				"JobScheduler", 
				"run", 
				"Error recording exception in job: " + exin.getMessage(), 
				exin );
			    }
                        setJobState( j, Job.STATE_FAILED );
                        continue;
                        }
                    finally
                    	{
			// end the context no matter how things turned out
			if ( context!=null )
			    context.endContext();
                    	}
                    
                        
                    }
                    
                try 
                    {
                    this.sleep( pause );  // pause in milliseconds
                    }
                catch ( InterruptedException iex )
                    {
                    }
                    
                }
            }
        finally
            {
            stopped=true;
            the_instance = null;
            }
        }
    }
    
   
   