You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by sy...@apache.org on 2004/03/11 16:38:32 UTC

cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

sylvain     2004/03/11 07:38:31

  Modified:    src/blocks/cron/java/org/apache/cocoon/components/cron
                        QuartzJobScheduler.java TestCronJob.java
                        QuartzJobExecutor.java
                        AbstractPipelineCallingCronJob.java
               src/blocks/cron/java/org/apache/cocoon/environment/background
                        BackgroundEnvironment.java
  Log:
  Refactor job launching to setup an environment that allows normal use of the sourceresolver, including "cocoon:" protocol
  
  Revision  Changes    Path
  1.11      +99 -81    cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/QuartzJobScheduler.java
  
  Index: QuartzJobScheduler.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/QuartzJobScheduler.java,v
  retrieving revision 1.10
  retrieving revision 1.11
  diff -u -r1.10 -r1.11
  --- QuartzJobScheduler.java	8 Mar 2004 13:43:42 -0000	1.10
  +++ QuartzJobScheduler.java	11 Mar 2004 15:38:31 -0000	1.11
  @@ -23,6 +23,7 @@
   
   import org.apache.avalon.framework.CascadingException;
   import org.apache.avalon.framework.activity.Disposable;
  +import org.apache.avalon.framework.activity.Initializable;
   import org.apache.avalon.framework.activity.Startable;
   import org.apache.avalon.framework.component.Component;
   import org.apache.avalon.framework.configuration.Configurable;
  @@ -38,6 +39,7 @@
   import org.apache.avalon.framework.service.Serviceable;
   import org.apache.avalon.framework.thread.ThreadSafe;
   import org.apache.cocoon.Constants;
  +import org.apache.cocoon.environment.background.BackgroundEnvironment;
   import org.quartz.CronTrigger;
   import org.quartz.Job;
   import org.quartz.JobDataMap;
  @@ -46,9 +48,7 @@
   import org.quartz.SchedulerException;
   import org.quartz.SimpleTrigger;
   import org.quartz.Trigger;
  -
   import org.quartz.impl.DirectSchedulerFactory;
  -
   import org.quartz.simpl.RAMJobStore;
   
   import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
  @@ -66,8 +66,11 @@
    */
   public class QuartzJobScheduler
   extends AbstractLogEnabled
  -implements JobScheduler, Component, ThreadSafe, Serviceable, Configurable, Startable, Disposable, Contextualizable {
  -    /** ThreadPool policy RUN */
  +implements JobScheduler, Component, ThreadSafe, Serviceable, Configurable, Startable, Disposable,
  +    Contextualizable, Initializable {
  +	private org.apache.cocoon.environment.Context environmentContext;
  +
  +	/** ThreadPool policy RUN */
       private static final String POLICY_RUN = "RUN";
   
       /** ThreadPool policy WAIT */
  @@ -93,6 +96,9 @@
   
       /** Map key for the service manager */
       static final String DATA_MAP_MANAGER = "QuartzJobScheduler.ServiceManager";
  +    
  +    /** Map key for the environment context (needed by BackgroundEnvironment) */
  +    static final String DATA_MAP_ENV_CONTEXT = "QuartzJobScheduler.EnvironmentContext";
   
       /** Map key for the logger */
       static final String DATA_MAP_LOGGER = "QuartzJobScheduler.Logger";
  @@ -116,23 +122,29 @@
       static final String DEFAULT_QUARTZ_SCHEDULER_NAME = "Cocoon";
   
       /** The PooledExecutor instance */
  -    private PooledExecutor m_executor;
  +    private PooledExecutor executor;
   
       /** The quartz scheduler */
  -    private Scheduler m_scheduler;
  +    private Scheduler scheduler;
   
       /** The ServiceManager instance */
  -    private ServiceManager m_manager;
  +    private ServiceManager manager;
  +    
  +    /** The configuration, parsed in initialize() */
  +    private Configuration config;
   
       /** Should we wait for running jobs to terminate on shutdown ? */
       private boolean m_shutdownGraceful;
   
  +	/** The Cocoon enviroment in which jobs will operate */
  +	private BackgroundEnvironment jobEnvironment;
  +
       /* (non-Javadoc)
        * @see org.apache.cocoon.components.cron.JobScheduler#getJobNames()
        */
       public String[] getJobNames() {
           try {
  -            final String[] names = m_scheduler.getJobNames(DEFAULT_QUARTZ_JOB_GROUP);
  +            final String[] names = scheduler.getJobNames(DEFAULT_QUARTZ_JOB_GROUP);
               Arrays.sort(names);
   
               return names;
  @@ -148,7 +160,7 @@
        */
       public JobSchedulerEntry getJobSchedulerEntry(String jobname) {
           try {
  -            return new QuartzJobSchedulerEntry(jobname, m_scheduler);
  +            return new QuartzJobSchedulerEntry(jobname, scheduler);
           } catch (final Exception e) {
               getLogger().error("cannot create QuartzJobSchedulerEntry", e);
           }
  @@ -260,25 +272,7 @@
        */
       public void configure(final Configuration config)
       throws ConfigurationException {
  -        try {
  -            // If cocoon reloads (or is it the container that reload us?) 
  -            // we cannot create the same scheduler again
  -            final String runID = new Date().toString().replace(' ', '_');
  -            final ThreadPool pool = createThreadPool(config.getChild("thread-pool"));
  -            DirectSchedulerFactory.getInstance().createScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME, runID, pool,
  -                                                                 new RAMJobStore());
  -            // m_scheduler = DirectSchedulerFactory.getInstance().getScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME, runID);
  -            m_scheduler = DirectSchedulerFactory.getInstance().getScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME);
  -        } catch (final SchedulerException se) {
  -            throw new ConfigurationException("cannot create a quartz scheduler", se);
  -        }
  -
  -        final Configuration[] triggers = config.getChild("triggers").getChildren("trigger");
  -        createTriggers(triggers);
  -
  -        if (getLogger().isDebugEnabled() && (triggers.length == 0)) {
  -            getLogger().debug("no triggers configured at startup");
  -        }
  +    	this.config = config;
       }
   
       /* (non-Javadoc)
  @@ -292,22 +286,49 @@
                                     : "immediately (killing running jobs)"));
               }
   
  -            m_scheduler.shutdown(m_shutdownGraceful);
  -            m_scheduler = null;
  +            scheduler.shutdown(m_shutdownGraceful);
  +            scheduler = null;
           } catch (final SchedulerException se) {
               getLogger().error("failure during scheduler shutdown", se);
           }
   
  -        m_executor = null;
  +        this.executor = null;
       }
   
   	/* (non-Javadoc)
   	 * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
   	 */
   	public void contextualize(Context context) throws ContextException {
  -		org.apache.cocoon.environment.Context c = (org.apache.cocoon.environment.Context)context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);
  -		System.out.println("context: " + c.getRealPath("/") );
  -	}    
  +		this.environmentContext = (org.apache.cocoon.environment.Context)context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);
  +	}
  +	
  +	public void initialize() throws Exception {
  +		try {
  +			// If cocoon reloads (or is it the container that reload us?) 
  +			// we cannot create the same scheduler again
  +			final String runID = new Date().toString().replace(' ', '_');
  +			final ThreadPool pool = createThreadPool(this.config.getChild("thread-pool"));
  +			DirectSchedulerFactory.getInstance().createScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME, runID, pool,
  +																 new RAMJobStore());
  +			// scheduler = DirectSchedulerFactory.getInstance().getScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME, runID);
  +			scheduler = DirectSchedulerFactory.getInstance().getScheduler(DEFAULT_QUARTZ_SCHEDULER_NAME);
  +		} catch (final SchedulerException se) {
  +			throw new ConfigurationException("cannot create a quartz scheduler", se);
  +		}
  +
  +		this.jobEnvironment = new BackgroundEnvironment(getLogger(), this.environmentContext, this.manager);
  +
  +		final Configuration[] triggers = this.config.getChild("triggers").getChildren("trigger");
  +		createTriggers(triggers);
  +		
  +		// We're finished with the configuration
  +		this.config = null;
  +
  +		if (getLogger().isDebugEnabled() && (triggers.length == 0)) {
  +			getLogger().debug("no triggers configured at startup");
  +		}
  +
  +	}
   
       /* (non-Javadoc)
        * @see org.apache.cocoon.components.cron.JobScheduler#fireTarget(java.lang.Object)
  @@ -323,13 +344,13 @@
           Object job = null;
   
           try {
  -            job = m_manager.lookup(jobrole);
  +            job = manager.lookup(jobrole);
   
               return fireJob(jobrole, job);
           } catch (final ServiceException se) {
               getLogger().error("cannot fire job " + jobrole, se);
           } finally {
  -            m_manager.release(job);
  +            manager.release(job);
           }
   
           return false;
  @@ -355,7 +376,7 @@
           Object job = null;
   
           try {
  -            job = m_manager.lookup(jobrole);
  +            job = manager.lookup(jobrole);
   
               if (job instanceof ConfigurableCronJob) {
                   ((ConfigurableCronJob)job).setup(params, objects);
  @@ -365,7 +386,7 @@
           } catch (final ServiceException se) {
               getLogger().error("cannot fire job " + jobrole, se);
           } finally {
  -            m_manager.release(job);
  +            manager.release(job);
           }
   
           return false;
  @@ -415,7 +436,7 @@
       public void removeJob(final String name)
       throws NoSuchElementException {
           try {
  -            if (m_scheduler.deleteJob(name, DEFAULT_QUARTZ_JOB_GROUP)) {
  +            if (scheduler.deleteJob(name, DEFAULT_QUARTZ_JOB_GROUP)) {
                   getLogger().info("job " + name + " removed by request");
               } else {
                   getLogger().error("couldn't remove requested job " + name);
  @@ -431,7 +452,7 @@
        */
       public void service(final ServiceManager manager)
       throws ServiceException {
  -        m_manager = manager;
  +        this.manager = manager;
       }
   
       /* (non-Javadoc)
  @@ -439,7 +460,7 @@
        */
       public void start()
       throws Exception {
  -        m_scheduler.start();
  +        scheduler.start();
       }
   
       /* (non-Javadoc)
  @@ -447,7 +468,7 @@
        */
       public void stop()
       throws Exception {
  -        m_scheduler.pause();
  +        scheduler.pause();
       }
   
       /**
  @@ -511,7 +532,7 @@
                           final boolean canRunConcurrently, final Parameters params, final Map objects)
       throws CascadingException {
           try {
  -            final JobDetail jobdetail = m_scheduler.getJobDetail(name, DEFAULT_QUARTZ_JOB_GROUP);
  +            final JobDetail jobdetail = scheduler.getJobDetail(name, DEFAULT_QUARTZ_JOB_GROUP);
   
               if (jobdetail != null) {
                   removeJob(name);
  @@ -521,8 +542,9 @@
   
           jobDataMap.put(DATA_MAP_NAME, name);
           jobDataMap.put(DATA_MAP_LOGGER, getLogger());
  -        jobDataMap.put(DATA_MAP_MANAGER, m_manager);
  +        jobDataMap.put(DATA_MAP_MANAGER, manager);
           jobDataMap.put(DATA_MAP_RUN_CONCURRENT, new Boolean(canRunConcurrently));
  +        jobDataMap.put(DATA_MAP_ENV_CONTEXT, this.environmentContext);
   
           if (null != params) {
               jobDataMap.put(DATA_MAP_PARAMETERS, params);
  @@ -540,7 +562,7 @@
           }
   
           try {
  -            m_scheduler.scheduleJob(detail, trigger);
  +            scheduler.scheduleJob(detail, trigger);
           } catch (final SchedulerException se) {
               throw new CascadingException(se.getMessage(), se);
           }
  @@ -567,51 +589,51 @@
   
           if (useQueueing) {
               if (queueSize > 0) {
  -                m_executor = new PooledExecutor(new BoundedBuffer(queueSize));
  +                this.executor = new PooledExecutor(new BoundedBuffer(queueSize));
               } else {
  -                m_executor = new PooledExecutor(new LinkedQueue());
  +                this.executor = new PooledExecutor(new LinkedQueue());
               }
           } else {
  -            m_executor = new PooledExecutor();
  +            this.executor = new PooledExecutor();
           }
   
           final int maxPoolSize = poolConfig.getChild("max-pool-size").getValueAsInteger(-1);
   
           if (maxPoolSize > 0) {
  -            m_executor.setMaximumPoolSize(maxPoolSize);
  +            this.executor.setMaximumPoolSize(maxPoolSize);
           } else {
  -            m_executor.setMaximumPoolSize(PooledExecutor.DEFAULT_MAXIMUMPOOLSIZE);
  +            this.executor.setMaximumPoolSize(PooledExecutor.DEFAULT_MAXIMUMPOOLSIZE);
           }
   
           final int minPoolSize = poolConfig.getChild("min-pool-size").getValueAsInteger(-1);
   
           if (minPoolSize > 0) {
  -            m_executor.setMinimumPoolSize(minPoolSize);
  +            this.executor.setMinimumPoolSize(minPoolSize);
           } else {
  -            m_executor.setMinimumPoolSize(PooledExecutor.DEFAULT_MINIMUMPOOLSIZE);
  +            this.executor.setMinimumPoolSize(PooledExecutor.DEFAULT_MINIMUMPOOLSIZE);
           }
   
           final int keepAliveTimeMs = poolConfig.getChild("keep-alive-time-ms").getValueAsInteger(-1);
   
           if (keepAliveTimeMs > 0) {
  -            m_executor.setKeepAliveTime(keepAliveTimeMs);
  +            this.executor.setKeepAliveTime(keepAliveTimeMs);
           } else {
  -            m_executor.setKeepAliveTime(PooledExecutor.DEFAULT_KEEPALIVETIME);
  +            this.executor.setKeepAliveTime(PooledExecutor.DEFAULT_KEEPALIVETIME);
           }
   
           final String blockPolicy = poolConfig.getChild("block-policy").getValue(null);
   
           if (blockPolicy != null) {
               if (blockPolicy.equalsIgnoreCase(POLICY_ABORT)) {
  -                m_executor.abortWhenBlocked();
  +                this.executor.abortWhenBlocked();
               } else if (blockPolicy.equalsIgnoreCase(POLICY_DISCARD)) {
  -                m_executor.discardWhenBlocked();
  +                this.executor.discardWhenBlocked();
               } else if (blockPolicy.equalsIgnoreCase(POLICY_DISCARD_OLDEST)) {
  -                m_executor.discardOldestWhenBlocked();
  +                this.executor.discardOldestWhenBlocked();
               } else if (blockPolicy.equalsIgnoreCase(POLICY_RUN)) {
  -                m_executor.runWhenBlocked();
  +                this.executor.runWhenBlocked();
               } else if (blockPolicy.equalsIgnoreCase(POLICY_WAIT)) {
  -                m_executor.waitWhenBlocked();
  +                this.executor.waitWhenBlocked();
               } else {
                   getLogger().warn("Unknown block-policy configuration '" + blockPolicy + "'. Should be one of '" +
                                    POLICY_ABORT + "','" + POLICY_DISCARD + "','" + POLICY_DISCARD_OLDEST + "','" +
  @@ -622,14 +644,14 @@
           m_shutdownGraceful = poolConfig.getChild("shutdown-graceful").getValueAsBoolean(true);
   
           final int shutdownWaitTimeMs = poolConfig.getChild("shutdown-wait-time-ms").getValueAsInteger(-1);
  -        final ThreadPool pool = new ThreadPool(m_executor, shutdownWaitTimeMs);
  +        final ThreadPool pool = new ThreadPool(this.executor, shutdownWaitTimeMs);
           pool.enableLogging(getLogger());
   
           if (getLogger().isInfoEnabled()) {
               getLogger().info("using a PooledExecutor as ThreadPool with queueing=" + useQueueing +
                                (useQueueing ? (",queue-size=" + ((queueSize > 0) ? ("" + queueSize) : "default")) : "") +
  -                             ",max-pool-size=" + m_executor.getMaximumPoolSize() + ",min-pool-size=" +
  -                             m_executor.getMinimumPoolSize() + ",keep-alive-time-ms=" + m_executor.getKeepAliveTime() +
  +                             ",max-pool-size=" + this.executor.getMaximumPoolSize() + ",min-pool-size=" +
  +                             this.executor.getMinimumPoolSize() + ",keep-alive-time-ms=" + this.executor.getKeepAliveTime() +
                                ",block-policy='" + blockPolicy + "',shutdown-wait-time-ms=" +
                                ((shutdownWaitTimeMs > 0) ? ("" + shutdownWaitTimeMs) : "default"));
           }
  @@ -676,13 +698,13 @@
       private boolean fireJob(final String name, final Object job) {
           try {
               if (job instanceof CronJob) {
  -                m_executor.execute(new Runnable() {
  +                this.executor.execute(new Runnable() {
                           public void run() {
                               ((CronJob)job).execute(name);
                           }
                       });
               } else if (job instanceof Runnable) {
  -                m_executor.execute((Runnable)job);
  +                this.executor.execute((Runnable)job);
               } else {
                   getLogger().error("job named '" + name + "' is of invalid class: " + job.getClass().getName());
   
  @@ -703,11 +725,9 @@
        * @author <a href="mailto:giacomo@otego.com">Giacomo Pati</a>
        * @version CVS $Id$
        */
  -    private static class ThreadPool
  -    extends AbstractLogEnabled
  -    implements org.quartz.spi.ThreadPool {
  +    private static class ThreadPool extends AbstractLogEnabled implements org.quartz.spi.ThreadPool {
           /** Our executor thread pool */
  -        private PooledExecutor m_executor;
  +        private PooledExecutor executor;
   
           /** How long to wait for running jobs to terminate on disposition */
           private int m_shutdownWaitTimeMs;
  @@ -717,7 +737,7 @@
            */
           public ThreadPool(final PooledExecutor executor, final int shutownWaitTimeMs) {
               super();
  -            m_executor = executor;
  +            this.executor = executor;
               m_shutdownWaitTimeMs = shutownWaitTimeMs;
           }
   
  @@ -725,7 +745,7 @@
            * @see org.quartz.spi.ThreadPool#getPoolSize()
            */
           public int getPoolSize() {
  -            return m_executor.getMaximumPoolSize();
  +            return this.executor.getMaximumPoolSize();
           }
   
           /* (non-Javadoc)
  @@ -739,7 +759,7 @@
            */
           public boolean runInThread(final Runnable job) {
               try {
  -                m_executor.execute(job);
  +                this.executor.execute(job);
               } catch (final InterruptedException ie) {
                   getLogger().error("Cronjob failed", ie);
               }
  @@ -752,27 +772,25 @@
            */
           public void shutdown(final boolean waitForJobsToComplete) {
               if (waitForJobsToComplete) {
  -                m_executor.shutdownAfterProcessingCurrentlyQueuedTasks();
  +                this.executor.shutdownAfterProcessingCurrentlyQueuedTasks();
               } else {
  -                m_executor.shutdownNow();
  +                this.executor.shutdownNow();
               }
   
               try {
                   if (m_shutdownWaitTimeMs > 0) {
  -                    if (!m_executor.awaitTerminationAfterShutdown(m_shutdownWaitTimeMs)) {
  +                    if (!this.executor.awaitTerminationAfterShutdown(m_shutdownWaitTimeMs)) {
                           getLogger().warn("scheduled cron jobs are not terminating within " + m_shutdownWaitTimeMs +
                                            "ms, Will shut them down by interruption");
  -                        m_executor.interruptAll();
  -                        m_executor.shutdownNow();
  +                        this.executor.interruptAll();
  +                        this.executor.shutdownNow();
                       }
                   }
   
  -                m_executor.awaitTerminationAfterShutdown();
  +                this.executor.awaitTerminationAfterShutdown();
               } catch (final InterruptedException ie) {
                   getLogger().error("cannot shutdown Executor", ie);
               }
           }
       }
  -
  -
   }
  
  
  
  1.6       +52 -44    cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/TestCronJob.java
  
  Index: TestCronJob.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/TestCronJob.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- TestCronJob.java	5 Mar 2004 13:01:49 -0000	1.5
  +++ TestCronJob.java	11 Mar 2004 15:38:31 -0000	1.6
  @@ -15,16 +15,20 @@
    */
   package org.apache.cocoon.components.cron;
   
  -import java.io.IOException;
   import java.io.InputStream;
   import java.io.InputStreamReader;
   import java.util.Date;
   import java.util.Map;
   
  +import org.apache.avalon.framework.CascadingRuntimeException;
   import org.apache.avalon.framework.configuration.Configurable;
   import org.apache.avalon.framework.configuration.Configuration;
   import org.apache.avalon.framework.configuration.ConfigurationException;
   import org.apache.avalon.framework.parameters.Parameters;
  +import org.apache.avalon.framework.service.ServiceManager;
  +import org.apache.avalon.framework.service.Serviceable;
  +import org.apache.excalibur.source.Source;
  +import org.apache.excalibur.source.SourceResolver;
   
   
   /**
  @@ -36,8 +40,8 @@
    *
    * @since 2.1.1
    */
  -public class TestCronJob extends AbstractPipelineCallingCronJob
  -    implements CronJob, Configurable, ConfigurableCronJob {
  +public class TestCronJob extends ServiceableCronJob
  +    implements CronJob, Configurable, ConfigurableCronJob, Serviceable {
       
       /** Parameter key for the message */
       public static final String PARAMETER_MESSAGE = "TestCronJob.Parameter.Message";
  @@ -56,6 +60,9 @@
       
       /** The pipeline to be called */
       private String pipeline = null;
  +    
  +    /** The service manager */
  +    private ServiceManager manager;
   
       /* (non-Javadoc)
        * @see org.apache.avalon.framework.configuration.Configurable#configure(org.apache.avalon.framework.configuration.Configuration)
  @@ -66,44 +73,48 @@
           m_sleep = config.getChild("sleep").getValueAsInteger(11000);
           pipeline = config.getChild("pipeline").getValue("samples/hello-world/hello.xhtml");
       }
  -
  -    /* (non-Javadoc)
  -     * @see org.apache.cocoon.components.cron.CronJob#execute(java.lang.String)
  -     */
  +    
  +    public void service(ServiceManager manager) {
  +    	this.manager = manager;
  +    }
  +    
       public void execute(String name) {
  -        getLogger().info("CronJob " + name + " launched at " + new Date() + " with message '" + m_msg +
  -                         "' and sleep timeout of " + m_sleep + "ms");
  -        
  -        InputStream is = null;
  -        try {
  -            is = process(pipeline);
  -        } catch (Exception e) {
  -            getLogger().error("error in execution of TestCronJob", e);
  -        } 
  -        StringBuffer sb = new StringBuffer();
  -        try {        
  -            InputStreamReader reader = new InputStreamReader(is);
  -            sb = new StringBuffer();
  -            char[] b = new char[8192];
  -            int n;
  -
  -            while((n = reader.read(b)) > 0) {
  -                sb.append(b, 0, n); 
  -            } 
  -        } catch( IOException ioe ) {
  -            getLogger().error("error trying to read the InputStream returned by the Pipeline processor");
  -        }
  -        getLogger().info("Cronjob " + name + " called pipeline " + pipeline + 
  -            " and received following content:\n" + sb.toString() );
  +		getLogger().info("CronJob " + name + " launched at " + new Date() + " with message '" + m_msg +
  +						 "' and sleep timeout of " + m_sleep + "ms");
  +		
  +		try {
  +			SourceResolver resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
  +			Source src = resolver.resolveURI("cocoon://" + pipeline);
  +			InputStream is = src.getInputStream();
  +			
  +			InputStreamReader reader = new InputStreamReader(is);
  +			StringBuffer sb = new StringBuffer();
  +			char[] b = new char[8192];
  +			int n;
  +
  +			while((n = reader.read(b)) > 0) {
  +				sb.append(b, 0, n); 
  +			}
  +			
  +			reader.close();
  +			resolver.release(src);
  +			manager.release(resolver);
  +			
  +			getLogger().info("Cronjob " + name + " called pipeline " + pipeline + 
  +				" and received following content:\n" + sb.toString() );
          
  -        try {
  -            Thread.sleep(m_sleep);
  -        } catch (final InterruptedException ie) {
  -            //getLogger().error("CronJob " + name + " interrupted", ie);
  -        }
  -
  -        getLogger().info("CronJob " + name + " finished at " + new Date() + " with message '" + m_msg +
  -                         "' and sleep timeout of " + m_sleep + "ms");
  +			try {
  +				Thread.sleep(m_sleep);
  +			} catch (final InterruptedException ie) {
  +				//getLogger().error("CronJob " + name + " interrupted", ie);
  +			}
  +
  +			getLogger().info("CronJob " + name + " finished at " + new Date() + " with message '" + m_msg +
  +							 "' and sleep timeout of " + m_sleep + "ms");
  +			
  +		} catch(Exception e) {
  +		    throw new CascadingRuntimeException("CronJob " + name + " raised an exception", e);
  +		}
       }
   
       /* (non-Javadoc)
  @@ -116,8 +127,5 @@
               pipeline = params.getParameter(PARAMETER_PIPELINE, pipeline );
               
           }
  -    }
  -
  -
  -    
  +    }    
   }
  
  
  
  1.6       +23 -3     cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/QuartzJobExecutor.java
  
  Index: QuartzJobExecutor.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/QuartzJobExecutor.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- QuartzJobExecutor.java	5 Mar 2004 13:01:49 -0000	1.5
  +++ QuartzJobExecutor.java	11 Mar 2004 15:38:31 -0000	1.6
  @@ -15,11 +15,16 @@
    */
   package org.apache.cocoon.components.cron;
   
  +import java.io.OutputStream;
  +import java.net.MalformedURLException;
   import java.util.Map;
   
   import org.apache.avalon.framework.logger.Logger;
   import org.apache.avalon.framework.parameters.Parameters;
   import org.apache.avalon.framework.service.ServiceManager;
  +import org.apache.cocoon.components.CocoonComponentManager;
  +import org.apache.cocoon.environment.background.BackgroundEnvironment;
  +import org.apache.cocoon.util.NullOutputStream;
   import org.quartz.Job;
   import org.quartz.JobDataMap;
   import org.quartz.JobExecutionContext;
  @@ -38,6 +43,9 @@
   implements Job {
       /** Map key for the run status */
       static final String DATA_MAP_KEY_ISRUNNING = "QuartzJobExecutor.isRunning";
  +    
  +    /** Shared instance (no state, as it does nothing) */
  +    static final OutputStream NULL_OUTPUT = new NullOutputStream();
   
       /* (non-Javadoc)
        * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
  @@ -69,7 +77,18 @@
   
           Object job = null;
           String jobrole = null;
  -        ServiceManager manager = null;
  +        
  +        ServiceManager manager = (ServiceManager)data.get(QuartzJobScheduler.DATA_MAP_MANAGER);
  +		org.apache.cocoon.environment.Context envContext =
  +			(org.apache.cocoon.environment.Context)data.get(QuartzJobScheduler.DATA_MAP_ENV_CONTEXT);
  +        BackgroundEnvironment env;
  +		try {
  +			env = new BackgroundEnvironment(logger, envContext, manager);
  +		} catch (MalformedURLException mue) {
  +			// Unlikely to happen
  +			throw new JobExecutionException(mue);
  +		}
  +        CocoonComponentManager.enterEnvironment(env, env.getManager(), env.getProcessor());
   
           try {
               jobrole = (String)data.get(QuartzJobScheduler.DATA_MAP_ROLE);
  @@ -77,7 +96,6 @@
               if (null == jobrole) {
                   job = data.get(QuartzJobScheduler.DATA_MAP_OBJECT);
               } else {
  -                manager = (ServiceManager)data.get(QuartzJobScheduler.DATA_MAP_MANAGER);
                   job = manager.lookup(jobrole);
               }
   
  @@ -106,6 +124,8 @@
               }
           } finally {
               data.put(DATA_MAP_KEY_ISRUNNING, Boolean.FALSE);
  +            
  +            CocoonComponentManager.leaveEnvironment();
   
               if (null != manager) {
                   manager.release(job);
  
  
  
  1.3       +6 -2      cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/AbstractPipelineCallingCronJob.java
  
  Index: AbstractPipelineCallingCronJob.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/AbstractPipelineCallingCronJob.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- AbstractPipelineCallingCronJob.java	5 Mar 2004 13:01:49 -0000	1.2
  +++ AbstractPipelineCallingCronJob.java	11 Mar 2004 15:38:31 -0000	1.3
  @@ -34,8 +34,12 @@
    * method which calls a Cocoon pipeline internally. It uses the 
    * <code>org.apache.cocoon.environment.background.BackgroundEnvironment</code>
    * to avoid an external call.
  + * <p>
  + * Some enhancements have been made on the scheduler that make this class now
  + * useless as the regular sourceresolver mechanism can be used.
    *
  - * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a> 
  + * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a>
  + * @deprecated Use the usual sourceresolver mechanism with a "cocoon://" URI
    * @version CVS $Id$
    *
    * @since 2.1.4
  
  
  
  1.3       +61 -3     cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background/BackgroundEnvironment.java
  
  Index: BackgroundEnvironment.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background/BackgroundEnvironment.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- BackgroundEnvironment.java	5 Mar 2004 13:01:50 -0000	1.2
  +++ BackgroundEnvironment.java	11 Mar 2004 15:38:31 -0000	1.3
  @@ -19,14 +19,23 @@
   import java.io.IOException;
   import java.io.OutputStream;
   import java.net.MalformedURLException;
  +import java.util.Map;
   
  +import org.apache.avalon.framework.component.ComponentManager;
  +import org.apache.avalon.framework.component.WrapperComponentManager;
   import org.apache.avalon.framework.logger.Logger;
  +import org.apache.avalon.framework.service.ServiceManager;
  +import org.apache.cocoon.Processor;
  +import org.apache.cocoon.components.pipeline.ProcessingPipeline;
   import org.apache.cocoon.environment.AbstractEnvironment;
  +import org.apache.cocoon.environment.Context;
  +import org.apache.cocoon.environment.Environment;
   import org.apache.cocoon.environment.ObjectModelHelper;
   import org.apache.cocoon.environment.Request;
   import org.apache.cocoon.environment.commandline.CommandLineContext;
   import org.apache.cocoon.environment.commandline.CommandLineRequest;
   import org.apache.cocoon.environment.commandline.CommandLineResponse;
  +import org.apache.cocoon.util.NullOutputStream;
   
   /**
    * A simple implementation of <code>org.apache.cocoon.environment.Environment</code>
  @@ -38,7 +47,36 @@
    * @since 2.1.4
    */
   public class BackgroundEnvironment extends AbstractEnvironment {
  -
  +	
  +	private ComponentManager manager;
  +	
  +	public BackgroundEnvironment(Logger logger, Context ctx, ServiceManager manager) throws MalformedURLException {
  +		super("", null, new File(ctx.getRealPath("/")), null);
  +		
  +		this.enableLogging(logger);
  +		
  +		this.manager = new WrapperComponentManager(manager);
  +		
  +		this.outputStream = new NullOutputStream();    
  +     
  +		// TODO Would special Background*-objects have advantages?
  +		Request request = new CommandLineRequest(this, "", "", null, null, null);
  +		this.objectModel.put(ObjectModelHelper.REQUEST_OBJECT, request);  
  +		this.objectModel.put(ObjectModelHelper.RESPONSE_OBJECT,
  +							 new CommandLineResponse());
  +		this.objectModel.put(ObjectModelHelper.CONTEXT_OBJECT, ctx);
  +	}
  +	
  +	/** Needed by CocoonComponentManager.enterEnvironment */
  +	public ComponentManager getManager() {
  +		return this.manager;
  +	}
  +	
  +	/** Needed by CocoonComponentManager.enterEnvironment */
  +	public Processor getProcessor() {
  +		return NullProcessor.INSTANCE;
  +	}
  +	
       /**
        * @param uri
        * @param view
  @@ -100,5 +138,25 @@
       public boolean isExternal() {
           return false;
       }
  -
  +    
  +    /** Dumb implementation needed by CocoonComponentManager.enterEnvironment() */
  +    public static class NullProcessor implements Processor {
  +    	
  +    	public static final Processor INSTANCE = new NullProcessor();
  +
  +		public boolean process(Environment environment) throws Exception {
  +			throw new UnsupportedOperationException();
  +		}
  +		public ProcessingPipeline buildPipeline(Environment environment) throws Exception {
  +			throw new UnsupportedOperationException();
  +		}
  +
  +		public Map getComponentConfigurations() {
  +			throw new UnsupportedOperationException();
  +		}
  +
  +		public Processor getRootProcessor() {
  +			throw new UnsupportedOperationException();
  +		}
  +    }
   }
  
  
  

Re: cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

Posted by Joerg Heinicke <jo...@gmx.de>.
On 11.03.2004 22:57, Sylvain Wallez wrote:

>> quoting Eclipse: "The private field QuartzJobScheduler.jobEnvironment 
>> is never read locally."
>>
>> Is it needed?
> 
> Well, if Eclipse says no, I guess it's right ;-)
> 
> Seriously, this refactoring went through several iterations and the 
> location of the environment move several times: it was initially a 
> singleton, but I later changed this when I realized that background 
> request processing can use request attributes, and that therefore a 
> singleton wasn't suitable.

Thanks. I only asked, because the last time I removed such unused code I 
broke some hidden magic code, because there happened something not obvious.

Joerg

Re: cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

Posted by Sylvain Wallez <sy...@apache.org>.
Joerg Heinicke wrote:

> On 11.03.2004 16:38, sylvain@apache.org wrote:
>
>> sylvain     2004/03/11 07:38:31
>>
>>   Modified:    src/blocks/cron/java/org/apache/cocoon/components/cron
>>                         QuartzJobScheduler.java TestCronJob.java
>>                         QuartzJobExecutor.java
>>                         AbstractPipelineCallingCronJob.java
>>                
>> src/blocks/cron/java/org/apache/cocoon/environment/background
>>                         BackgroundEnvironment.java
>>   Log:
>>   Refactor job launching to setup an environment that allows normal 
>> use of the sourceresolver, including "cocoon:" protocol
>
>
> ...
>
>>   +    /** The Cocoon enviroment in which jobs will operate */
>>   +    private BackgroundEnvironment jobEnvironment;
>
>
> quoting Eclipse: "The private field QuartzJobScheduler.jobEnvironment 
> is never read locally."
>
> Is it needed?


Well, if Eclipse says no, I guess it's right ;-)

Seriously, this refactoring went through several iterations and the 
location of the environment move several times: it was initially a 
singleton, but I later changed this when I realized that background 
request processing can use request attributes, and that therefore a 
singleton wasn't suitable.

Sylvain

-- 
Sylvain Wallez                                  Anyware Technologies
http://www.apache.org/~sylvain           http://www.anyware-tech.com
{ XML, Java, Cocoon, OpenSource }*{ Training, Consulting, Projects }


Re: cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

Posted by Joerg Heinicke <jo...@gmx.de>.
On 11.03.2004 16:38, sylvain@apache.org wrote:

> sylvain     2004/03/11 07:38:31
> 
>   Modified:    src/blocks/cron/java/org/apache/cocoon/components/cron
>                         QuartzJobScheduler.java TestCronJob.java
>                         QuartzJobExecutor.java
>                         AbstractPipelineCallingCronJob.java
>                src/blocks/cron/java/org/apache/cocoon/environment/background
>                         BackgroundEnvironment.java
>   Log:
>   Refactor job launching to setup an environment that allows normal use of the sourceresolver, including "cocoon:" protocol

...

>   +	/** The Cocoon enviroment in which jobs will operate */
>   +	private BackgroundEnvironment jobEnvironment;

quoting Eclipse: "The private field QuartzJobScheduler.jobEnvironment is 
never read locally."

Is it needed?

Joerg

Re: cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

Posted by Sylvain Wallez <sy...@apache.org>.
Reinhard Pötz wrote:

> sylvain@apache.org wrote:
>
>>  Index: AbstractPipelineCallingCronJob.java
>>  ===================================================================
>>  RCS file: 
>> /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/AbstractPipelineCallingCronJob.java,v 
>>
>>  retrieving revision 1.2
>>  retrieving revision 1.3
>>  diff -u -r1.2 -r1.3
>>  --- AbstractPipelineCallingCronJob.java    5 Mar 2004 13:01:49 
>> -0000    1.2
>>  +++ AbstractPipelineCallingCronJob.java    11 Mar 2004 15:38:31 
>> -0000    1.3
>>  @@ -34,8 +34,12 @@
>>    * method which calls a Cocoon pipeline internally. It uses the    
>> * 
>> <code>org.apache.cocoon.environment.background.BackgroundEnvironment</code> 
>>
>>    * to avoid an external call.
>>  + * <p>
>>  + * Some enhancements have been made on the scheduler that make this 
>> class now
>>  + * useless as the regular sourceresolver mechanism can be used.
>>    *
>>  - * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a> 
>>  + * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a>
>>  + * @deprecated Use the usual sourceresolver mechanism with a 
>> "cocoon://" URI
>>  
>>
> I think we can remove it complety as the cron block is marked as 
> unstable.


+1.

I wanted to keep it a bit until people currently using it migrate to 
regular use of "cocoon:" URLs. Now removing it is actually better to 
invite people to migrate ;-)

Sylvain

-- 
Sylvain Wallez                                  Anyware Technologies
http://www.apache.org/~sylvain           http://www.anyware-tech.com
{ XML, Java, Cocoon, OpenSource }*{ Training, Consulting, Projects }


Re: cvs commit: cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/environment/background BackgroundEnvironment.java

Posted by Reinhard Pötz <re...@apache.org>.
sylvain@apache.org wrote:

>  Index: AbstractPipelineCallingCronJob.java
>  ===================================================================
>  RCS file: /home/cvs/cocoon-2.1/src/blocks/cron/java/org/apache/cocoon/components/cron/AbstractPipelineCallingCronJob.java,v
>  retrieving revision 1.2
>  retrieving revision 1.3
>  diff -u -r1.2 -r1.3
>  --- AbstractPipelineCallingCronJob.java	5 Mar 2004 13:01:49 -0000	1.2
>  +++ AbstractPipelineCallingCronJob.java	11 Mar 2004 15:38:31 -0000	1.3
>  @@ -34,8 +34,12 @@
>    * method which calls a Cocoon pipeline internally. It uses the 
>    * <code>org.apache.cocoon.environment.background.BackgroundEnvironment</code>
>    * to avoid an external call.
>  + * <p>
>  + * Some enhancements have been made on the scheduler that make this class now
>  + * useless as the regular sourceresolver mechanism can be used.
>    *
>  - * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a> 
>  + * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a>
>  + * @deprecated Use the usual sourceresolver mechanism with a "cocoon://" URI
>  
>
I think we can remove it complety as the cron block is marked as unstable.

--
Reinhard