KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > essiembre > library > scheduler > SchedulerServlet


1 /*
2  * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
3  *
4  * This file is part of Essiembre Scheduler.
5  *
6  * Essiembre Scheduler is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Essiembre Scheduler is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Essiembre Scheduler; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307 USA
20  */

21 package com.essiembre.library.scheduler;
22
23
24 import java.io.InputStream JavaDoc;
25 import java.io.InputStreamReader JavaDoc;
26 import java.text.DateFormat JavaDoc;
27 import java.text.SimpleDateFormat JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.Calendar JavaDoc;
30 import java.util.Timer JavaDoc;
31 import java.util.Vector JavaDoc;
32
33 import javax.servlet.http.HttpServlet JavaDoc;
34
35 import org.exolab.castor.mapping.Mapping;
36 import org.exolab.castor.xml.Unmarshaller;
37
38 import org.xml.sax.InputSource JavaDoc;
39
40
41 /**
42  * This servlet adds easy support for scheduled jobs in J2EE applications.
43  * It takes care of creating and starting a defined set of
44  * <code>SchedulerTask</code> objects. The frequency of those scheduled
45  * tasks (when should it be run, how often, etc), are defined
46  * in a XML configuration file.
47  * <p>
48  * For easy configuration steps of this servlet and other information
49  * on how to best use this J2EE scheduler library, refer to its online
50  * documentation. A link to this J2EE scheduler project home page is
51  * provided on <a HREF="https://sourceforge.net/projects/esslibraries/"
52  * target="top">sourceforge project page</a>.
53  *
54  *
55  * @author Pascal Essiembre
56  * @version $Id: SchedulerServlet.java,v 1.3 2004/06/08 02:50:40 essiembre Exp $
57  */

58 public class SchedulerServlet
59         extends HttpServlet JavaDoc {
60
61     /**
62      * Initializes all required <code>Timer</code> classes along with their
63      * respective <code>SchedulerTask</code> instances.
64      *
65      * @throws javax.servlet.ServletException If something goes wrong
66      * in initialization.
67      */

68     public void init() throws javax.servlet.ServletException JavaDoc {
69
70         try {
71
72             Mapping mapping = new Mapping(
73                     this.getClass().getClassLoader());
74             String JavaDoc config =
75                     getServletConfig().getInitParameter("config");
76             SchedulerTasks tasks = null;
77             Vector JavaDoc taskVector = null;
78
79
80             // Load the mapping information from the file
81
InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(
82                     getClass().getResourceAsStream("SchedulerMapping.xml"));
83             mapping.loadMapping(new InputSource JavaDoc(reader));
84
85             // Unmarshal the data
86
InputStream JavaDoc input = getServletContext().getResourceAsStream(config);
87             Unmarshaller unmar = new Unmarshaller(mapping);
88             tasks = (SchedulerTasks) unmar.unmarshal(new InputSource JavaDoc(input));
89             taskVector = tasks.getTasksList();
90             
91             // Load and run timers
92
for (int i = 0; i < taskVector.size(); i++) {
93                 SchedulerTaskInfo taskInfo =
94                         (SchedulerTaskInfo) taskVector.get(i);
95                 SchedulerTask task = createSchedulerTask(taskInfo);
96                 launchTimer(task, taskInfo);
97             }
98
99         } catch (Exception JavaDoc e) {
100             throw new RuntimeException JavaDoc("ERROR in SchedulerServler.init():" + e);
101         }
102     }
103
104
105     /**
106      * Creates and instantiate a <code>SchedulerTask</code> based on
107      * the provided <code>SchedulerTask</code> object.
108      *
109      * @param taskInfo a <code>SchedulerTaskInfo</code> object.
110      * @return a <code>SchedulerTask</code> object.
111      *
112      */

113     private SchedulerTask createSchedulerTask(SchedulerTaskInfo taskInfo) {
114
115         try {
116         
117             Class JavaDoc taskObject = Class.forName(taskInfo.getTask());
118             SchedulerTask task = (SchedulerTask) taskObject.newInstance();
119             task.setInitParameters(taskInfo.getParameters());
120             task.setServletConfig(getServletConfig());
121             return task;
122
123         } catch (java.lang.ClassNotFoundException JavaDoc e) {
124             throw new RuntimeException JavaDoc(
125                     "ERROR in SchedulerServlet.createSchedulerTask(). "
126                     + "Provided class name does not exists. "
127                     + "Exception is: " + e);
128         } catch (java.lang.IllegalAccessException JavaDoc e) {
129             throw new RuntimeException JavaDoc(
130                     "ERROR in SchedulerServlet.createSchedulerTask(). "
131                     + "Cannot instantiate provided class name. "
132                     + "Exception is: " + e);
133         } catch (java.lang.InstantiationException JavaDoc e) {
134             throw new RuntimeException JavaDoc(
135                     "ERROR in SchedulerServlet.createSchedulerTask(). "
136                     + "Cannot instantiate provided class name. "
137                     + "Exception is: " + e);
138         }
139     }
140
141     
142     /**
143      * Launches a <code>Timer</code> object with the provided task information.
144      *
145      * @param task a <code>SchedulerTask</code> object.
146      * @param taskInfo a <code>SchedulerTaskInfo</code> object.
147      *
148      */

149     private void launchTimer(SchedulerTask task, SchedulerTaskInfo taskInfo) {
150         
151         Timer JavaDoc timer = new Timer JavaDoc(true);
152         Date JavaDoc time = null;
153         
154         /*
155          * Parse the date from taskInfo if provided.
156          */

157         if (taskInfo.getTime() != null) {
158
159             // Create the date formert
160
DateFormat JavaDoc formatter = null;
161             
162             
163             /*
164              * Check for which format was provide yyyy-MM-dd HH:mm:ss,
165              * HH:mm:ss or yyy-MM-dd
166              */

167             if (taskInfo.getTime().indexOf("-") > 0
168              && taskInfo.getTime().indexOf(":") > 0) {
169             
170                 // Full Date yyyy-MM-dd HH:mm:ss
171
formatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
172             } else if (taskInfo.getTime().indexOf("-") > 0
173                     && taskInfo.getTime().indexOf(":") < 0) {
174                         
175                 // Just the date yyyy-MM-dd
176
formatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd");
177             } else if (taskInfo.getTime().indexOf("-") < 0
178                     && taskInfo.getTime().indexOf(":") > 0) {
179                 
180                 // Just a time HH:mm:ss
181
formatter = new SimpleDateFormat JavaDoc("HH:mm:ss");
182             }
183             
184             try {
185                time = formatter.parse(taskInfo.getTime());
186             } catch (java.text.ParseException JavaDoc e) {
187                throw new IllegalArgumentException JavaDoc(
188                      "ERROR in SchedulerTask.setTime(String). "
189                    + "Could not parse date provided date: '" + time + "'. "
190                    + "Exception is: " + e);
191             }
192             
193             // In case of just time, Add the appropriate date
194
if (taskInfo.getTime().indexOf("-") < 0
195              && taskInfo.getTime().indexOf(":") > 0) {
196
197                 // Get the User provided Time
198
Calendar JavaDoc userCal = Calendar.getInstance();
199                 userCal.setTime(time);
200                 
201                 // Get System Calendar Date
202
Calendar JavaDoc sys = Calendar.getInstance();
203             
204                 // Set the date for the time provided
205
userCal.set(Calendar.YEAR, sys.get(java.util.Calendar.YEAR));
206                 userCal.set(Calendar.MONTH, sys.get(java.util.Calendar.MONTH));
207                 userCal.set(Calendar.DAY_OF_MONTH,
208                                                 sys.get(Calendar.DAY_OF_MONTH));
209
210                  // Compare the two dates.
211
if (userCal.getTime().getTime() < sys.getTime().getTime()) {
212                     
213                     // Time has passed. Add one day
214
userCal.add(Calendar.DAY_OF_MONTH, 1);
215                 }
216             
217                 // Set the time object
218
time = userCal.getTime();
219             }
220         }
221         
222         /*
223          * Execute the proper Timer method call based on arguments in taskInfo
224          * If not method excactly match the number and type of supplied
225          * arguments, we throw an error.
226          */

227         if (time != null && taskInfo.getPeriod() == null
228                 && taskInfo.getDelay() == null) {
229             timer.schedule(task, time);
230         } else if (time != null && taskInfo.getPeriod() != null
231                 && taskInfo.getDelay() == null) {
232             timer.schedule(
233                     task, time, SchedulerUtil.parseTime(taskInfo.getPeriod()));
234         } else if (time == null && taskInfo.getPeriod() == null
235                 && taskInfo.getDelay() != null) {
236             timer.schedule(task, SchedulerUtil.parseTime(taskInfo.getDelay()));
237
238         } else if (time == null && taskInfo.getPeriod() != null
239                 && taskInfo.getDelay() != null) {
240             timer.schedule(task, SchedulerUtil.parseTime(taskInfo.getDelay()),
241                     SchedulerUtil.parseTime(taskInfo.getPeriod()));
242         } else {
243             throw new RuntimeException JavaDoc(
244                       "ERROR in SchedulerServlet.launchTimer(). "
245                     + "No Timer.shedule() method could be found matching "
246                     + "supplied arguments. ");
247         }
248     }
249 }
Popular Tags