shuber      2004/09/08 14:27:36 CEST

  Modified files:
    core                 project.xml 
    core/src/java/org/jahia/registries ServicesRegistry.java 
    core/src/java/org/jahia/tools/files FileWatcher.java 
  Added files:
    core/src/java/org/jahia/tools/files FileWatcherJob.java 
    core/src/java/org/jahia/services/scheduler 
                                               SchedulerService.java 
                                               SchedulerServiceImpl.java 
  Log:
  - Introducing new scheduler service into Jahia
  - Using new scheduler service to replace Timer based implementation of FileWatchers.
  
  Revision  Changes    Path
  1.27      +9 -1      jahia/core/project.xml
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/project.xml.diff?r1=1.26&r2=1.27&f=h
  1.8       +9 -0      jahia/core/src/java/org/jahia/registries/ServicesRegistry.java
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/src/java/org/jahia/registries/ServicesRegistry.java.diff?r1=1.7&r2=1.8&f=h
  1.1       +15 -0     
jahia/core/src/java/org/jahia/services/scheduler/SchedulerService.java (new)
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/src/java/org/jahia/services/scheduler/SchedulerService.java?rev=1.1&content-type=text/plain
  1.1       +123 -0    
jahia/core/src/java/org/jahia/services/scheduler/SchedulerServiceImpl.java (new)
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/src/java/org/jahia/services/scheduler/SchedulerServiceImpl.java?rev=1.1&content-type=text/plain
  1.3       +68 -113   jahia/core/src/java/org/jahia/tools/files/FileWatcher.java
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/src/java/org/jahia/tools/files/FileWatcher.java.diff?r1=1.2&r2=1.3&f=h
  1.1       +85 -0     jahia/core/src/java/org/jahia/tools/files/FileWatcherJob.java 
(new)
http://jahia.mine.nu:8080/cgi-bin/cvsweb.cgi/jahia/core/src/java/org/jahia/tools/files/FileWatcherJob.java?rev=1.1&content-type=text/plain
  
  
  
  Index: project.xml
  ===================================================================
  RCS file: /cvs/jahia/core/project.xml,v
  retrieving revision 1.26
  retrieving revision 1.27
  diff -u -r1.26 -r1.27
  --- project.xml       11 Aug 2004 14:18:16 -0000      1.26
  +++ project.xml       8 Sep 2004 12:27:35 -0000       1.27
  @@ -1,4 +1,4 @@
  -<?xml version="1.0" encoding="UTF-8"?>
  +<?xml version="1.0" encoding="UTF-8"?>
   
   <project>
     <pomVersion>3</pomVersion>
  @@ -525,6 +525,14 @@
         </properties>
       </dependency>
       <dependency>
  +      <groupId>opensymphony</groupId>
  +      <artifactId>quartz</artifactId>
  +      <version>1.4.0</version>
  +      <properties>
  +        <war.bundle>true</war.bundle>
  +      </properties>
  +    </dependency>
  +    <dependency>
         <groupId>oreilly</groupId>
         <artifactId>cos</artifactId>
         <version>20021105</version>
  
  
  
  Index: ServicesRegistry.java
  ===================================================================
  RCS file: /cvs/jahia/core/src/java/org/jahia/registries/ServicesRegistry.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- ServicesRegistry.java     28 Jul 2004 14:13:33 -0000      1.7
  +++ ServicesRegistry.java     8 Sep 2004 12:27:35 -0000       1.8
  @@ -94,6 +94,8 @@
   import org.jahia.services.urlrewriting.URLRewritingService;
   import org.apache.commons.configuration.Configuration;
   import org.apache.commons.configuration.PropertiesConfiguration;
  +import java.util.Iterator;
  +import org.jahia.services.scheduler.SchedulerService;
   
   import org.apache.jetspeed.om.common.portlet.MutablePortletApplication;
   import org.apache.jetspeed.components.portletregistry.PortletRegistryComponent;
  @@ -231,6 +233,8 @@
   
       private final String METADATA_SERVICE = "MetadataService";
   
  +    private final String SCHEDULER_SERVICE = "SchedulerService";
  +
       // Jetspeed engine
       private Engine jetspeed = null;
       private static final String JETSPEED_CONFIG = "jetspeed.properties";
  @@ -294,6 +298,7 @@
           classNames.add(JAHIA_GROUP_MANAGER_SERVICE);
           classNames.add(JAHIA_USER_MANAGER_SERVICE);
           classNames.add(JAHIA_SITE_USER_MANAGER_SERVICE);
  +        classNames.add (SCHEDULER_SERVICE);
           classNames.add(JAHIA_TEMPLATES_DEPLOYER_SERVICE);
           classNames.add(JAHIA_WEBAPPS_DEPLOYER_SERVICE);
           classNames.add(JAHIA_FILE_WATCHER_SERVICE);
  @@ -627,6 +632,10 @@
           return (MetadataService) registry.get(this.METADATA_SERVICE);
       }
   
  +    public SchedulerService getSchedulerService() {
  +        return (SchedulerService) registry.get(this.SCHEDULER_SERVICE);
  +    }
  +
       /** Default constructor, creates a new <code>ServiceRegistry</code> instance.
        */
       private ServicesRegistry () {
  
  
  
  Index: FileWatcherJob.java
  ====================================================================
  package org.jahia.tools.files;
  
  import org.quartz.StatefulJob;
  import org.quartz.JobExecutionContext;
  import org.quartz.JobExecutionException;
  import org.quartz.JobDataMap;
  import java.util.Vector;
  import java.io.File;
  
  public class FileWatcherJob implements StatefulJob {
      public FileWatcherJob () {
      }
  
      public void execute (JobExecutionContext context)
          throws JobExecutionException {
  
          //logger.debug("Checking files in directory " + m_Folder.toString() + "...");
          JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
          FileWatcher fileWatcher = (FileWatcher) jobDataMap.get("fileWatcher");
  
          /** The Vector of new files **/
          Vector newFiles = checkFiles(fileWatcher.getFolder(),
                                       fileWatcher.getFileOnly(),
                                       fileWatcher.getCheckDate(),
                                       fileWatcher.getLastCheckTime());
  
          // Notify Observers if number of files > 0
          if (newFiles.size() > 0) {
              fileWatcher.externalSetChanged(); // Alert the Observable Object That 
there are change in the folder
              fileWatcher.notifyObservers(newFiles);
          }
      }
  
      /**
       * Checks new files and builds the Vector of files
       * to pass to Observers
       *
       */
      protected Vector checkFiles (File folder, boolean fileOnly,
                                   boolean checkDate, long lastCheckTime) {
  
          Vector newFiles = new Vector();
          if (folder.isDirectory()) {
  
              if (!checkDate) {
  
                  File[] files = folder.listFiles();
                  if (files == null) {
                      return newFiles;
                  }
                  int size = files.length;
  
                  for (int i = 0; i < size; i++) {
                      // logger.debug("FileWatcher found new file " + 
files[i].getName() );
                      if (files[i].canWrite()) {
                          if (!fileOnly) {
                              newFiles.add(files[i]);
                          } else if (files[i].isFile()) {
                              newFiles.add(files[i]);
                          }
                      }
                  }
  
              } else {
  
                  File[] files = folder.listFiles();
                  if (files == null) {
                      return newFiles;
                  }
                  int size = files.length;
  
                  for (int i = 0; i < size; i++) {
  
                      if (files[i].lastModified() > lastCheckTime) {
                          newFiles.add(files[i]);
                      }
                  }
  
              }
  
          }
          return newFiles;
  
      }
  }
  
  
  
  Index: FileWatcher.java
  ===================================================================
  RCS file: /cvs/jahia/core/src/java/org/jahia/tools/files/FileWatcher.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- FileWatcher.java  21 May 2004 15:37:06 -0000      1.2
  +++ FileWatcher.java  8 Sep 2004 12:27:35 -0000       1.3
  @@ -26,6 +26,18 @@
   import java.util.Timer;
   import java.util.TimerTask;
   import java.util.Vector;
  +import org.quartz.JobExecutionContext;
  +import org.quartz.Job;
  +import org.quartz.JobDetail;
  +import org.quartz.Trigger;
  +import org.jahia.registries.ServicesRegistry;
  +import org.quartz.SimpleTrigger;
  +import org.quartz.Scheduler;
  +import org.jahia.exceptions.JahiaException;
  +import org.quartz.JobExecutionException;
  +import org.quartz.StatefulJob;
  +import org.quartz.JobDataMap;
  +import java.io.Serializable;
   
   /**
    * An Observer/Observable Implementation of a Deamon Thread
  @@ -42,7 +54,7 @@
    * @author Khue ng
    * @version 1.0
    */
  -public class FileWatcher extends Observable {
  +public class FileWatcher extends Observable implements Serializable {
   
       private static org.apache.log4j.Logger logger =
               org.apache.log4j.Logger.getLogger(FileWatcher.class);
  @@ -57,7 +69,8 @@
      private long m_Interval;
   
      /** The internal Thread Timer **/
  -   private Timer m_Timer;
  +    private JobDetail jobDetail;
  +    private Trigger trigger;
   
      /** Both file and directory or only file **/
      private boolean m_FileOnly = true;
  @@ -71,36 +84,6 @@
      /** the Last Time the Folder was checked **/
      private long m_LastCheckTime;
   
  -   /** The Vector of new files **/
  -   Vector m_NewFiles = new Vector();
  -
  -
  -   /**
  -    * Inner TimerTask Class used to schedule Thread Task
  -    *
  -    */
  -   public class FileWatcherTask extends TimerTask {
  -
  -      public void run() {
  -
  -          //logger.debug("Checking files in directory " + m_Folder.toString() + 
"...");
  -
  -         // Check for new files
  -         synchronized(m_NewFiles) {
  -
  -            m_NewFiles.clear();
  -            checkFiles();
  -
  -            // Notify Observers if number of files > 0
  -            if ( m_NewFiles.size()>0 ){
  -               externalSetChanged();  // Alert the Observable Object That there are 
change in the folder
  -               notifyObservers(m_NewFiles);
  -            }
  -         }
  -      }
  -   }
  -
  -
      /**
       * Constructor
       *
  @@ -114,7 +97,8 @@
                          boolean checkDate,
                          long interval,
                          boolean fileOnly
  -                     ) throws IOException {
  +                        )
  +        throws IOException {
   
           setFolderPath(fullFolderPath);
           setCheckDate(checkDate);
  @@ -122,7 +106,6 @@
           setFileOnly(fileOnly);
      }
   
  -
      /**
       * Constructor
       * Precise if the Thread to Create is a Deamon or not
  @@ -139,7 +122,8 @@
                          long interval,
                          boolean fileOnly,
                          boolean isDeamon
  -                     ) throws IOException {
  +                        )
  +        throws IOException {
   
         setFolderPath(fullFolderPath);
         setCheckDate(checkDate);
  @@ -149,30 +133,49 @@
   
      }
   
  -
      /**
       * Creates the Timer Thread and starts it
       *
       * @Exception IOException
       */
  -   public void start() throws IOException {
  +    public void start ()
  +        throws IOException {
   
         initialize();
  -      m_Timer = new Timer(isDeamon());
   
  -      logger.debug("Time created, Check Interval=" + getInterval() + " (millis) " );
  +        logger.debug("Time created, Check Interval=" + getInterval() +
  +                     " (millis) ");
   
  -      m_Timer.schedule(new FileWatcherTask(), 0, getInterval());
  -
  -      logger.debug("Timer started() ");
  +        jobDetail = new JobDetail(m_FolderPath + "_Job", Scheduler.DEFAULT_GROUP,
  +                                  FileWatcherJob.class);
  +        JobDataMap jobDataMap = new JobDataMap();
  +        jobDataMap.put("fileWatcher", this);
  +        jobDetail.setJobDataMap(jobDataMap);
  +
  +        trigger = new SimpleTrigger(m_FolderPath + "_Trigger",
  +                                    Scheduler.DEFAULT_GROUP,
  +                                    SimpleTrigger.REPEAT_INDEFINITELY,
  +                                    m_Interval);
  +
  +
  +        try {
  +            ServicesRegistry.getInstance().getSchedulerService().scheduleJob(
  +                jobDetail, trigger);
  +        } catch (JahiaException je) {
  +            logger.error("Error while scheduling file watch for " + m_FolderPath, 
je);
  +        }
   
      }
   
      public void stop() {
  -       m_Timer.cancel();
  +        try {
  +            ServicesRegistry.getInstance().getSchedulerService().unscheduleJob(
  +                m_FolderPath + "_Trigger", Scheduler.DEFAULT_GROUP);
  +        } catch (JahiaException je) {
  +            logger.error("Error while scheduling file watch for " + m_FolderPath, 
je);
  +        }
      }
   
  -
      /**
       * Returns The Interval Values
       *
  @@ -182,7 +185,6 @@
         return m_Interval;
      }
   
  -
      /**
       * Set The Interval Values
       *
  @@ -200,7 +202,6 @@
         setChanged();
      }
   
  -
      /**
       * Returns The Path of the Folder to watch
       *
  @@ -210,7 +211,6 @@
         return m_FolderPath;
      }
   
  -
      /**
       * Set The FolderPath
       *
  @@ -220,7 +220,6 @@
         m_FolderPath = fullFolderPath;
      }
   
  -
      /**
       * set file only mode
       *
  @@ -230,6 +229,9 @@
         m_FileOnly = fileOnly;
      }
   
  +    public boolean getFileOnly() {
  +        return m_FileOnly;
  +    }
   
      /**
       * Returns The Check File Mode
  @@ -240,7 +242,6 @@
         return mCheckDate;
      }
   
  -
      /**
       * Set The Check File Mode ( by last modif date or returns all files found
       *
  @@ -250,7 +251,6 @@
       mCheckDate = checkDate;
      }
   
  -
      /**
       * Thread is a Deamon or not
       *
  @@ -260,7 +260,6 @@
         return m_IsDeamon;
      }
   
  -
      /**
       * Create a Deamon or User Thread
       *
  @@ -270,7 +269,13 @@
         m_IsDeamon = isDeamon;
      }
   
  -
  +    public File getFolder() {
  +        return m_Folder;
  +    }
  +
  +    public long getLastCheckTime() {
  +        return m_LastCheckTime;
  +    }
   
      /**
       * Verify if the Folder to watch exists.
  @@ -278,7 +283,8 @@
       *
       * @exception IOException
       */
  -   protected void initialize() throws IOException{
  +    protected void initialize ()
  +        throws IOException {
   
         logger.debug("Initializing file watcher"  );
   
  @@ -287,76 +293,25 @@
            ToChange : restore the last check time from ext. file !
         */
         m_LastCheckTime = System.currentTimeMillis();
  -
         logger.debug("Watching directory=" + getFolderPath()   );
  -
         File tmpFile = new File(getFolderPath());
  -
         if ( tmpFile != null && tmpFile.isDirectory() && !tmpFile.canWrite() ){
  -
  -          logger.debug("No write access to directory " + getFolderPath() + " 
tmpFile=" + tmpFile.toString());
  -
  +            logger.debug("No write access to directory " + getFolderPath() +
  +                         " tmpFile=" + tmpFile.toString());
         } else if ( !tmpFile.exists() ) {
  -
  -          logger.debug("Directory " + tmpFile.toString() + " does not exist, 
creating...");
  -
  +            logger.debug("Directory " + tmpFile.toString() +
  +                         " does not exist, creating...");
             tmpFile.mkdirs();
  -
  -          logger.debug("Directory " + tmpFile.toString() + " created 
successfully.");
  -
  +            logger.debug("Directory " + tmpFile.toString() +
  +                         " created successfully.");
             if ( tmpFile == null) {
  -              throw new IOException( "FileWatcher::initialize(), cannot create 
directory " + tmpFile.toString());
  +                throw new IOException(
  +                    "FileWatcher::initialize(), cannot create directory " +
  +                    tmpFile.toString());
             }
         }
         m_Folder = tmpFile;
  -
  -   }
  -
  -
  -   /**
  -    * Checks new files and builds the Vector of files
  -    * to pass to Observers
  -    *
  -    */
  -   protected void checkFiles(){
  -
  -      //Vector newFiles = new Vector();
  -      if ( m_Folder.isDirectory() ){
  -
  -
  -          if ( !getCheckDate() ) {
  -
  -             File[] files = m_Folder.listFiles();
  -             int size = files.length;
  -
  -             for ( int i=0; i<size ; i++ ){
  -                 // logger.debug("FileWatcher found new file " + files[i].getName() 
);
  -                if ( files[i].canWrite() ){
  -                    if ( !m_FileOnly ){
  -                        m_NewFiles.add(files[i]);
  -                    } else if ( files[i].isFile() ){
  -                        m_NewFiles.add(files[i]);
                       }
  -                }
  -             }
  -
  -          } else {
  -
  -             File[] files = m_Folder.listFiles();
  -             int size = files.length;
   
  -             for ( int i=0 ; i<size ; i++ ) {
  -
  -                if ( files[i].lastModified()>m_LastCheckTime ){
  -                   m_NewFiles.add(files[i]);
  -                }
  -             }
  -
  -          }
  -
  -      }
  -      //return newFiles;
  -
  -   }
   
   } // end Class FileWatcher
  
  
  
  Index: SchedulerService.java
  ====================================================================
  package org.jahia.services.scheduler;
  
  import org.jahia.services.JahiaInitializableService;
  import org.quartz.JobDetail;
  import org.quartz.Trigger;
  import org.jahia.exceptions.JahiaException;
  
  public abstract class SchedulerService extends JahiaInitializableService {
  
      public abstract void scheduleJob(JobDetail jobDetail, Trigger trigger)
          throws JahiaException;
  
      public abstract void unscheduleJob(String triggerName, String groupName)
          throws JahiaException;
  }
  
  
  
  Index: SchedulerServiceImpl.java
  ====================================================================
  package org.jahia.services.scheduler;
  
  import org.jahia.settings.SettingsBean;
  import org.jahia.exceptions.JahiaInitializationException;
  import org.quartz.SchedulerFactory;
  import org.quartz.Scheduler;
  import org.quartz.SchedulerException;
  import org.jahia.exceptions.JahiaException;
  import org.quartz.JobDetail;
  import org.quartz.Trigger;
  
  public class SchedulerServiceImpl extends SchedulerService {
  
      private static org.apache.log4j.Logger logger =
              org.apache.log4j.Logger.getLogger(SchedulerServiceImpl.class);
  
      private static SchedulerServiceImpl singletonInstance;
  
      private Scheduler scheduler = null;
      private boolean schedulerRunning = false;
  
      private SchedulerServiceImpl () {
      }
  
      /**
       * Return the unique service instance. If the instance does not exist,
       * a new instance is created.
       *
       * @return The unique service instance.
       */
      public synchronized static SchedulerServiceImpl getInstance () {
          if (singletonInstance == null) {
              singletonInstance = new SchedulerServiceImpl ();
          }
          return singletonInstance;
      }
  
      /**
       * Initializes the servlet dispatching service with parameters loaded
       * from the Jahia configuration file.
       * @param jSettings private settings object that contains Jahia
       * configuration parameters
       * @throws JahiaInitializationException thrown in the case of an error
       * during this initialization, that will be treated as a critical error
       * in Jahia and probably stop execution of Jahia once and for all.
       */
      public void init( SettingsBean jSettings )
          throws JahiaInitializationException {
  
          SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
  
          try {
              scheduler = schedFact.getScheduler();
              logger.debug("Starting scheduler...");
              scheduler.start();
              schedulerRunning = true;
          } catch (SchedulerException se) {
              if (se.getUnderlyingException() != null) {
                  throw new JahiaInitializationException(
                      "Error while initializing scheduler service",
                      se.getUnderlyingException());
              } else {
                  throw new JahiaInitializationException(
                      "Error while initializing scheduler service",
                      se);
              }
          }
  
      }
  
      public synchronized void shutdown ()
          throws JahiaException {
          try {
              logger.debug("Shutting down scheduler...");
              scheduler.shutdown();
              scheduler = null;
              schedulerRunning = false;
          } catch (SchedulerException se) {
              throw getJahiaException(se);
          }
      }
  
      public void scheduleJob(JobDetail jobDetail, Trigger trigger)
          throws JahiaException  {
          if (!schedulerRunning) {
              return;
          }
          try {
              scheduler.scheduleJob(jobDetail, trigger);
          } catch (SchedulerException se) {
              throw getJahiaException(se);
          }
      }
  
      public void unscheduleJob(String triggerName, String groupName)
          throws JahiaException {
          if (!schedulerRunning) {
              return;
          }
          try {
              scheduler.unscheduleJob(triggerName, groupName);
          } catch (SchedulerException se) {
              throw getJahiaException(se);
          }
      }
  
      private JahiaException getJahiaException(SchedulerException se) {
          if (se.getUnderlyingException() != null) {
              return new JahiaException("Error while shutting down scheduler service",
                                        "Error while shutting down scheduler service",
                                        JahiaException.SERVICE_ERROR,
                                        JahiaException.ERROR_SEVERITY,
                                        se.getUnderlyingException());
          } else {
              return new JahiaException("Error while shutting down scheduler service",
                                        "Error while shutting down scheduler service",
                                        JahiaException.SERVICE_ERROR,
                                        JahiaException.ERROR_SEVERITY,
                                        se);
          }
      }
  
  }
  

Reply via email to