Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
$URL$ $Id$ Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation Licensed under the Educational Community License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.osedu.org/licenses/ECL-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. /
 
 
 package org.sakaiproject.component.app.scheduler;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 import  org.quartz.CronTrigger;
 import  org.quartz.JobDataMap;
 import  org.quartz.JobDetail;
 import  org.quartz.JobListener;
 import  org.quartz.Scheduler;
 import  org.quartz.SchedulerException;
 import  org.quartz.SchedulerFactory;
 import  org.quartz.Trigger;
 import  org.quartz.TriggerListener;
 import  org.quartz.impl.StdSchedulerFactory;
 
 public class SchedulerManagerImpl implements SchedulerManager
 {
 
   public final static String
         SCHEDULER_LOADJOBS      = "scheduler.loadjobs";
   private DataSource dataSource;
   private String serverId;
   private Set<StringqrtzJobs;
   private Map<StringStringqrtzQualifiedJobs = new TreeMap<StringString>(); // map for SelectItems
   private String qrtzPropFile;
   private Properties qrtzProperties;
   private TriggerListener globalTriggerListener;
   private Boolean autoDdl;
 
   private static final String JOB_INTERFACE = "org.quartz.Job";
   private static final String STATEFULJOB_INTERFACE = "org.quartz.StatefulJob";
   
 
   private SchedulerFactory schedFactory;
   private Scheduler scheduler;
   private static final Log LOG = LogFactory.getLog(SchedulerManagerImpl.class);
 
   private LinkedList<TriggerListener>
       globalTriggerListeners = new LinkedList<TriggerListener>();
   private LinkedList<JobListener>
       globalJobListeners = new LinkedList<JobListener>();
 
       initialJobSchedule = null;
 
 public void init()
   {
 
 	InputStream propertiesInputStream = null;
     try
    {
      SqlService sqlService = org.sakaiproject.db.cover.SqlService
      .getInstance();
      // load quartz properties file
      propertiesInputStream = this.getClass().getResourceAsStream(
          );
       = new Properties();
      .load(propertiesInputStream);
      // now replace properties from those loaded in from components.xml
//      qrtzProperties.setProperty("org.quartz.dataSource.myDS.driver",
//          dataSource.getDriverClassName());
//      qrtzProperties.setProperty("org.quartz.dataSource.myDS.URL", dataSource
//          .getUrl());
//      qrtzProperties.setProperty("org.quartz.dataSource.myDS.user", dataSource
//          .getUsername());
//      qrtzProperties.setProperty("org.quartz.dataSource.myDS.password",
//          dataSource.getPassword());
        .setProperty("org.quartz.scheduler.instanceId");
//      if ("hsqldb".equalsIgnoreCase(sqlService.getVendor())){
//        qrtzProperties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.HSQLDBDelegate"); 
//      }
//      else if ("mysql".equalsIgnoreCase(sqlService.getVendor())){
//        qrtzProperties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
//      }
//      else if ("oracle".equalsIgnoreCase(sqlService.getVendor())){
//        qrtzProperties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.oracle.OracleDelegate");
//      }
//      else{
//        LOG.warn("sakai vendor not supported");
//      }
      // note: becuase job classes are jarred , it is impossible to iterate
      // through a directory by calling listFiles on a file object.
      // Therefore, we need the class list list from spring.
      // find quartz jobs from specified 'qrtzJobs' and verify they
      // that these jobs implement the Job interface
      Iterator<StringqrtzJobsIterator = .iterator();
      while (qrtzJobsIterator.hasNext())
      {
        String className = (StringqrtzJobsIterator.next();
        Class cl = null;
        try
        {
          cl = Class.forName(className);
        }
        catch (ClassNotFoundException e)
        {
          .warn("Could not locate class: " + className + " on classpath");
        }
        if (cl != null)
        {
          // check that each class implements the Job interface           
          if (doesImplementJobInterface(cl))
          {
            .put(cl.getName(), cl.getName());
          }
          else
          {
            .warn("Class: " + className
                + " does not implement quartz Job interface");
          }
        }
      }
   // run ddl
      if (.booleanValue()){
        try
        {
           sqlService.ddl(this.getClass().getClassLoader(), "quartz");
        }
        catch (Throwable t)
        {
          .warn(this + ".init(): "t);
        }
      }
      boolean isInitialStartup = isInitialStartup(sqlService);
      if (isInitialStartup && .booleanValue())
      {
    	  .info("Performing initial population of the Quartz tables.");
    	  sqlService.ddl(this.getClass().getClassLoader(), "init_locks");
      }
      /*
         Determine whether or not to load the jobs defined in the initialJobSchedules list. These jobs will be loaded
         under the following conditions:
            1) the server configuration property "scheduler.loadjobs" is "true"
            2) "scheduler.loadjobs" is "init" and this is the first startup for the scheduler (eg. this is a new Sakai instance)
         "scheduler.loadjobs" is set to "init" by default
       */
      String
          loadJobs = ServerConfigurationService.getString("init").trim();
          initSchedules = getInitialJobSchedules();
      
      boolean
          loadInitSchedules = (initSchedules != null) && (initSchedules.size() > 0) &&
                                (("init".equalsIgnoreCase(loadJobs) && isInitialStartup) ||
                                 "true".equalsIgnoreCase(loadJobs));
      if (loadInitSchedules)
          .debug ("Preconfigured jobs will be loaded");
      else
          .debug ("Preconfigured jobs will not be loaded");
      
      
      // start scheduler and load jobs
       = new StdSchedulerFactory();
       = .getScheduler();
      // loop through persisted jobs removing both the job and associated
      // triggers for jobs where the associated job class is not found
      String[] arrJobs = .getJobNames(Scheduler.DEFAULT_GROUP);
      for (int i = 0; i < arrJobs.lengthi++)
      {
        try
        {
          .getJobDetail(arrJobs[i],
              Scheduler.DEFAULT_GROUP);
        }
        catch (SchedulerException e)
        {
          .warn("scheduler cannot load class for persistent job:"
              + arrJobs[i]);
          .deleteJob(arrJobs[i], Scheduler.DEFAULT_GROUP);
        }
      }
      for (TriggerListener tListener : )
      {
          .addGlobalTriggerListener(tListener);
      }
      for (JobListener jListener : )
      {
          .addGlobalJobListener(jListener);
      }
      if (loadInitSchedules)
      {
          .debug ("Loading preconfigured jobs");
          loadInitialSchedules();
      }
      //scheduler.addGlobalTriggerListener(globalTriggerListener);
      .start();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new Error("Scheduler cannot start!");
    }
    finally {
    	if (propertiesInputStream != null) {
    		try {
				propertiesInputStream.close();
catch (IOException e) {
				.debug("exception in finaly block closing input stream");
			}
    	}
    }
    
  }
  private boolean doesImplementJobInterface(Class cl)
  {
    Class[] classArr = cl.getInterfaces();
    for (int i = 0; i < classArr.lengthi++)
    {
    	if (classArr[i].getName().equals() || 
    			classArr[i].getName().equals())
      {
        return true;
      }
    }
    return false;
  }

    
Runs an SQL select statement to determine if the Quartz lock rows exist in the database. If the rows do not exist this method assumes this is the first time the scheduler has been started. The select statement will be defined in the {vendor}/checkTables.sql file within the shared library deployed by this project. The statement should be of the form "SELECT COUNT(*) from QUARTZ_LOCKS;". If the count is zero it is assumed this is a new install. If the count is non-zero it is assumed the QUARTZ_LOCKS table has been initialized and this is not a new install.

Parameters:
sqlService
Returns:
  private boolean isInitialStartup(SqlService sqlService)
  {
      String
          checkTablesScript = sqlService.getVendor() + "/checkTables.sql";
      ClassLoader
          loader = this.getClass().getClassLoader();
      String
          chkStmt = null;
      InputStream
          in = null;
      BufferedReader
          r = null;
      try
      {
          // find the resource from the loader
          in = loader.getResourceAsStream(checkTablesScript);
          r = new BufferedReader(new InputStreamReader(in));
          chkStmt = r.readLine();
      }
      catch (Exception e)
      {
          .error("Could not read the file " + checkTablesScript + " to determine if this is a new installation. Preconfigured jobs will only be loaded if the server property scheduler.loadjobs is \"true\""e);
          return false;
      }
      finally
      {
          try
          {
              r.close();
          }
          catch (Exception e){}
          try
          {
              in.close();
          }
          catch (Exception e){}
      }
      List<Stringl = sqlService.dbRead(chkStmt);
      if (l != null && l.size() > 0) 
      {
    	  return (l.get(0).equalsIgnoreCase("0"));
      }
      else 
      {
    	  return false;
      }
  }

    
Loads jobs and schedules triggers for preconfigured jobs.
  private void loadInitialSchedules()
  {
      for (SpringInitialJobSchedule sched : getInitialJobSchedules())
      {
          SpringJobBeanWrapper
              wrapper = sched.getJobBeanWrapper();
          .debug ("Loading schedule for preconfigured job \"" + wrapper.getJobType() + "\"");
          JobDetail
              jd = new JobDetail (sched.getJobName(), Scheduler.DEFAULT_GROUP, wrapper.getJobClass(), falsetruetrue);
          JobDataMap
              map = jd.getJobDataMap();
          map.put(.wrapper.getBeanId());
          map.put(.wrapper.getJobType());
          if (SpringConfigurableJobBeanWrapper.class.isAssignableFrom(wrapper.getClass()))
          {
              SpringConfigurableJobBeanWrapper
                  confJob = (SpringConfigurableJobBeanWrapperwrapper;
              ConfigurableJobPropertyValidator
                  validator = confJob.getConfigurableJobPropertyValidator();
              Map<StringString>
                  conf = sched.getConfiguration();
              boolean
                  fail = false;
              for (ConfigurableJobProperty cProp : confJob.getConfigurableJobProperties())
              {
                  String
                      key = cProp.getLabelResourceKey(),
                      val = conf.get(key);
                  .debug ("job property '" + key + "' is set to '" + val + "'");
                  if (val == null && cProp.isRequired())
                  {
                      val = cProp.getDefaultValue();
                      if (val == null)
                      {
                          .error ("job property '" + key + "' is required but has no value; job '" + sched.getJobName() + "' of type '" + wrapper.getJobClass() + "' will not be configured");
                          fail = true;
                          break;
                      }
                      .debug ("job property '" + key + "' set to default value '" + val + "'");
                  }
                  if (val != null)
                  {
                      try
                      {
                          validator.assertValid(keyval);
                      }
                      catch (ConfigurableJobPropertyValidationException cjpve)
                      {
                          .error ("job property '" + key + "' was set to an invalid value '" + val + "'; job '" + sched.getJobName() + "' of type '" + wrapper.getJobClass() + "' will not be configured");
                          fail = true;
                          break;
                      }
                      map.put (keyval);
                  }
              }
              if (failcontinue;
          }
          try
          {
              .addJob(jdfalse);
          }
          catch (SchedulerException e)
          {
              .error ("Failed to schedule job '" + sched.getJobName() + "' of type '" + wrapper.getJobClass() + "'");
              continue;
          }
          Trigger trigger = null;
          try
          {
              trigger = new CronTrigger(sched.getTriggerName(), Scheduler.DEFAULT_GROUP,
                                                jd.getName(), Scheduler.DEFAULT_GROUP,
                                                sched.getCronExpression());
          }
          catch (ParseException e)
          {
              .error ("Error parsing cron exception. Failed to schedule job '" + sched.getJobName() + "' of type '" + wrapper.getJobClass() + "'");
          }
          try
          {
              .scheduleJob(trigger);
          }
          catch (SchedulerException e)
          {
              .error ("Trigger could not be scheduled. Failed to schedule job '" + sched.getJobName() + "' of type '" + wrapper.getJobClass() + "'");
          }
      }
  }


  

See also:
org.sakaiproject.api.app.scheduler.SchedulerManager.destroy()
  public void destroy()
  {
    try{
      if (!.isShutdown()){
        .shutdown();
      }
    }
    catch (Throwable t){
      .error("An error occurred while stopping the scheduler"t);
    }
  }
  {
      return ;
  }
  {
      if(jobSchedule == null || jobSchedule.size() < 1)
        return;
      
      .addAll(jobSchedule);
  }
  

Deprecated:
use setGlobalTriggerListeners(Set<TriggerListener>)
Returns:
Returns the globalTriggerListener.
  public TriggerListener getGlobalTriggerListener()
  {
    return ;
  }

  

Deprecated:
use getGlobalTriggerListeners()
Parameters:
globalTriggerListener The globalTriggerListener to set.
  public void setGlobalTriggerListener(TriggerListener globalTriggerListener)
  {
    this. = globalTriggerListener;
      if ( != null)
      {
          .addFirst(globalTriggerListener);
      }
  }
  public void setGlobalTriggerListeners (final List<TriggerListener> listeners)
  {
      .clear();
      if ( != null)
      {
      }
      if (listeners != null)
      {
          .addAll(listeners);
      }
  }
  public List<TriggerListener> getGlobalTriggerListeners()
  {
      return Collections.unmodifiableList();
  }
  public void setGlobalJobListeners (final List<JobListener> listeners)
  {
      .clear();
      if (listeners != null)
      {
          .addAll(listeners);
      }
  }
  public List<JobListener> getGlobalJobListeners()
  {
      return Collections.unmodifiableList();
  }

  

Returns:
Returns the serverId.
  public String getServerId()
  {
    return ;
  }

  

Parameters:
serverId The serverId to set.
  public void setServerId(String serverId)
  {
    this. = serverId;
  }

  

Returns:
Returns the dataSource.
  {
    return ;
  }

  

Parameters:
dataSource The dataSource to set.
  public void setDataSource(DataSource dataSource)
  {
    this. = dataSource;
  }

  

Returns:
Returns the qrtzQualifiedJobs.
  {
    return ;
  }

  

Parameters:
qrtzQualifiedJobs The qrtzQualifiedJobs to set.
  public void setQrtzQualifiedJobs(Map<StringStringqrtzQualifiedJobs)
  {
    this. = qrtzQualifiedJobs;
  }

  

Returns:
Returns the qrtzJobs.
  public Set<StringgetQrtzJobs()
  {
    return ;
  }

  

Parameters:
qrtzJobs The qrtzJobs to set.
  public void setQrtzJobs(Set<StringqrtzJobs)
  {
    this. = qrtzJobs;
  }

  

Returns:
Returns the qrtzPropFile.
  public String getQrtzPropFile()
  {
    return ;
  }

  

Parameters:
qrtzPropFile The qrtzPropFile to set.
  public void setQrtzPropFile(String qrtzPropFile)
  {
    this. = qrtzPropFile;
  }

  

Returns:
Returns the scheduler.
  public Scheduler getScheduler()
  {
    return ;
  }

  

Parameters:
scheduler The sched to set.
  public void setScheduler(Scheduler scheduler)
  {
    this. = scheduler;
  }

  

See also:
org.sakaiproject.api.app.scheduler.SchedulerManager.setAutoDdl(java.lang.Boolean)
  public void setAutoDdl(Boolean b)
  {
     = b;
  }
   public Map<StringJobBeanWrappergetBeanJobs() {
      return ;
   }
   public void registerBeanJob(String jobNameJobBeanWrapper job) {
      getBeanJobs().put(jobNamejob);
   }
   public JobBeanWrapper getJobBeanWrapper(String beanWrapperId) {
      return (JobBeanWrappergetBeanJobs().get(beanWrapperId);
   }
   
New to GrepCode? Check out our FAQ X