KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > services > controller > CronController


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2003 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64 package com.jcorporate.expresso.services.controller;
65
66 import com.jcorporate.expresso.core.controller.Block;
67 import com.jcorporate.expresso.core.controller.ControllerException;
68 import com.jcorporate.expresso.core.controller.ControllerRequest;
69 import com.jcorporate.expresso.core.controller.ControllerResponse;
70 import com.jcorporate.expresso.core.controller.ErrorCollection;
71 import com.jcorporate.expresso.core.controller.Input;
72 import com.jcorporate.expresso.core.controller.NonHandleableException;
73 import com.jcorporate.expresso.core.controller.Output;
74 import com.jcorporate.expresso.core.controller.State;
75 import com.jcorporate.expresso.core.controller.Transition;
76 import com.jcorporate.expresso.core.dbobj.ValidValue;
77 import com.jcorporate.expresso.core.misc.ConfigManager;
78 import com.jcorporate.expresso.core.utility.JobHandler;
79 import com.jcorporate.expresso.services.crontab.CronException;
80 import com.jcorporate.expresso.services.crontab.Crontab;
81 import com.jcorporate.expresso.services.crontab.CrontabEntry;
82 import org.apache.log4j.Logger;
83
84 import java.text.SimpleDateFormat JavaDoc;
85 import java.util.Calendar JavaDoc;
86 import java.util.Date JavaDoc;
87 import java.util.Iterator JavaDoc;
88 import java.util.List JavaDoc;
89 import java.util.Vector JavaDoc;
90
91
92 /**
93  * Crontab Controller allows for basic insight into the currently running
94  * crontabs on the system. It also allows for basic editing and removal of
95  * existing crontabs. It does not create new crontabs yet.
96  *
97  * @author Michael Rimov
98  * @version 1.0
99  * @since Expresso 5.3
100  */

101 public class CronController
102         extends com.jcorporate.expresso.core.controller.DBController {
103     /**
104      * the Log4j Logger
105      */

106     public static final transient Logger log = Logger.getLogger(CronController.class);
107
108     /**
109      * Creates an instance of CronController. Call setRequestingUid() and
110      * setDataContext() before using.
111      *
112      * @throws ControllerException upon initialization exception.
113      * @see com.jcorporate.expresso.core.dbobj.SecuredDBObject#SecuredDBObject
114      */

115     public CronController() throws ControllerException {
116         super();
117
118         State s = new State("list", "List Cron Jobs");
119         this.addState(s);
120         this.setInitialState("list");
121
122         s = new State("delete", "Delete");
123         s.addRequiredParameter("CronId");
124         this.addState(s);
125
126         s = new State("edit", "Edit");
127         s.addRequiredParameter("CronId");
128         this.addState(s);
129
130         s = new State("editUpdate", "Update Execution Time");
131         s.addRequiredParameter("CronId");
132         s.addRequiredParameter("minute");
133         s.addRequiredParameter("hour");
134         s.addRequiredParameter("day");
135         s.addRequiredParameter("dayofWeek");
136         s.addRequiredParameter("month");
137         s.addRequiredParameter("year");
138         this.addState(s);
139     }
140
141     /**
142      * Retrieve the title of the controller
143      *
144      * @return java.lang.String
145      */

146     public String JavaDoc getTitle() {
147         return "Cron Manager";
148     }
149
150     /**
151      * Build day of week valid values
152      *
153      * @param request ControllerRequest from which we grab the user's locale
154      * @return Vector of ValidValue objects for each day of the week
155      */

156     protected Vector JavaDoc buildDayOfWeekValidValues(ControllerRequest request) {
157         Vector JavaDoc returnValue = new Vector JavaDoc(8);
158         returnValue.add(new ValidValue("-1", "Unspecified"));
159
160         SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc("EEEE");
161         Calendar JavaDoc cal = Calendar.getInstance(request.getLocale());
162         cal.clear();
163
164         for (int i = 1; i < 8; i++) {
165             cal.set(Calendar.DAY_OF_WEEK, i);
166             returnValue.add(new ValidValue(Integer.toString(i),
167                     df.format(cal.getTime())));
168         }
169
170         return returnValue;
171     }
172
173     /**
174      * Build the crontab day valid values
175      *
176      * @return Vector of ValidValue objects 1-31
177      */

178     protected Vector JavaDoc buildDayValidValues() {
179         Vector JavaDoc returnValue = new Vector JavaDoc(32);
180         returnValue.add(new ValidValue("-1", "Unspecified"));
181
182         for (int i = 1; i < 32; i++) {
183             returnValue.add(new ValidValue(Integer.toString(i),
184                     Integer.toString(i)));
185         }
186
187         return returnValue;
188     }
189
190     /**
191      * Build the crontab hour valid values
192      *
193      * @return Vector of ValidValue objects: 1-24
194      */

195     protected Vector JavaDoc buildHourValidValues() {
196         Vector JavaDoc returnValue = new Vector JavaDoc(24);
197
198         for (int i = 0; i < 24; i++) {
199             returnValue.add(new ValidValue(Integer.toString(i),
200                     Integer.toString(i)));
201         }
202
203         return returnValue;
204     }
205
206     /**
207      * Build the crontab minute valid values
208      *
209      * @return Vector of minute valid values
210      */

211     protected Vector JavaDoc buildMinuteValidValue() {
212         Vector JavaDoc returnValue = new Vector JavaDoc(60);
213
214         for (int i = 0; i < 60; i++) {
215             returnValue.add(new ValidValue(Integer.toString(i),
216                     Integer.toString(i)));
217         }
218
219         return returnValue;
220     }
221
222     /**
223      * Build month valid values
224      *
225      * @param request ControllerRequest from which we grab the user's locale
226      * @return Vector of valid values for each month in the year
227      */

228     protected Vector JavaDoc buildMonthValidValues(ControllerRequest request) {
229         Vector JavaDoc returnValue = new Vector JavaDoc(8);
230         returnValue.add(new ValidValue("-1", "Unspecified"));
231
232         SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc("MMMM");
233         Calendar JavaDoc cal = Calendar.getInstance(request.getLocale());
234         cal.clear();
235
236         for (int i = 0; i < 12; i++) {
237             cal.set(Calendar.MONTH, i);
238             returnValue.add(new ValidValue(Integer.toString(i),
239                     df.format(cal.getTime())));
240         }
241
242         return returnValue;
243     }
244
245     /**
246      * Build the year valid values
247      *
248      * @param request ControllerRequest from which we grab the user's locale
249      * @return Vector of ValidValues for a 50 year span
250      */

251     protected Vector JavaDoc buildYearValidValues(ControllerRequest request) {
252         Vector JavaDoc returnValue = new Vector JavaDoc(51);
253         returnValue.add(new ValidValue("-1", "Unspecified"));
254
255         Calendar JavaDoc cal = Calendar.getInstance(request.getLocale());
256
257         for (int i = cal.get(Calendar.YEAR); i < (cal.get(Calendar.YEAR) + 50);
258              i++) {
259             returnValue.add(new ValidValue(Integer.toString(i),
260                     Integer.toString(i)));
261         }
262
263         return returnValue;
264     }
265
266     /**
267      * Make sure Cron Manager is synchronized before calling this function!
268      *
269      * @param crontab the crontab to search
270      * @param id the crontab incrementing id
271      * @return CrontabEntry or null if it cannot be found.
272      */

273     protected CrontabEntry findCronById(Crontab crontab, long id) {
274         List JavaDoc l = crontab.getAllEntries();
275
276         if (l.size() == 0) {
277             return null;
278         }
279
280         for (Iterator JavaDoc i = l.iterator(); i.hasNext();) {
281             CrontabEntry entry = (CrontabEntry) i.next();
282
283             if (entry.getCounter() == id) {
284                 return entry;
285             }
286         }
287
288         return null;
289     }
290
291     /**
292      * Deletes a specified crontab
293      *
294      * @param request The <code>ControllerRequest</code> object handed to us by
295      * the framework.
296      * @param response The <code>ControllerResponse</code> object handed to us
297      * by the framework.
298      * @throws ControllerException upon error
299      * @throws NonHandleableException upon fatal error
300      */

301     protected void runDeleteState(ControllerRequest request,
302                                   ControllerResponse response)
303             throws ControllerException, NonHandleableException {
304         ErrorCollection ec = request.getErrorCollection();
305
306         if (ec != null) {
307             response.saveErrors(ec);
308             transition("list", request, response);
309
310             return;
311         }
312
313         response.setTitle("Delete Crontab");
314
315         JobHandler jh = ConfigManager.getJobHandler(request.getDataContext());
316         Crontab crontab = jh.getCronManager();
317         String JavaDoc cronId = request.getParameter("CronId");
318         long cronNumber = Long.parseLong(cronId);
319         response.setTitle("Edit Cron Parameters");
320
321         CrontabEntry entry = null;
322
323         synchronized (crontab) {
324             entry = findCronById(crontab, cronNumber);
325
326             if (entry != null) {
327                 crontab.removeCrontabEntry(entry);
328                 response.add(new Output("result",
329                         "Deleted Entry Labelled: " + entry.getLabel()));
330
331                 Transition t = new Transition("list", this);
332                 response.add(t);
333             }
334         }
335
336         //We transition down here after synchronize is released so we don't
337
//hold crontab for too long.
338
if (entry == null) {
339             ec = new ErrorCollection();
340             ec.addError("Unable to find cron id of: " + cronId +
341                     ". it may have been removed from the queue");
342             transition("list", request, response);
343
344             return;
345         }
346     }
347
348     /**
349      * Prompts for editing a crontab entry.
350      *
351      * @param request The <code>ControllerRequest</code> object handed to us by
352      * the framework.
353      * @param response The <code>ControllerResponse</code> object handed to us
354      * by the framework.
355      * @throws ControllerException upon error
356      * @throws NonHandleableException upon fatal error
357      */

358     protected void runEditState(ControllerRequest request,
359                                 ControllerResponse response)
360             throws ControllerException, NonHandleableException {
361         ErrorCollection ec = request.getErrorCollection();
362
363         if (ec != null) {
364             response.saveErrors(ec);
365             transition("list", request, response);
366
367             return;
368         }
369
370         Vector JavaDoc minValidValue = buildMinuteValidValue();
371         Vector JavaDoc hourValidValue = buildHourValidValues();
372         Vector JavaDoc dayValidValue = buildDayValidValues();
373         Vector JavaDoc dayofWeekValidValue = buildDayOfWeekValidValues(request);
374         Vector JavaDoc monthValidValue = buildMonthValidValues(request);
375         Vector JavaDoc yearValidValue = buildYearValidValues(request);
376
377         JobHandler jh = ConfigManager.getJobHandler(request.getDataContext());
378         Crontab crontab = jh.getCronManager();
379         String JavaDoc cronId = request.getParameter("CronId");
380         long cronNumber = Long.parseLong(cronId);
381         response.setTitle("Edit Cron Parameters");
382
383         CrontabEntry entry = null;
384
385         synchronized (crontab) {
386             entry = findCronById(crontab, cronNumber);
387
388             if (entry != null) {
389                 response.add(new Output("subtitle",
390                         "Editing Entry Labelled: " + entry.getLabel()));
391
392                 Input i = new Input("minute", "Minute");
393                 i.setValidValues(minValidValue);
394                 i.setDefaultValue(Integer.toString(entry.getMinute()));
395                 response.add(i);
396
397                 i = new Input("hour", "Hour");
398                 i.setValidValues(hourValidValue);
399                 i.setDefaultValue(Integer.toString(entry.getHour()));
400                 response.add(i);
401
402                 i = new Input("day", "Day of Month");
403                 i.setValidValues(dayValidValue);
404                 i.setDefaultValue(Integer.toString(entry.getDayOfMonth()));
405                 response.add(i);
406
407                 i = new Input("dayofWeek", "Day of Week");
408                 i.setValidValues(dayofWeekValidValue);
409                 i.setDefaultValue(Integer.toString(entry.getDayOfWeek()));
410                 response.add(i);
411
412                 i = new Input("month", "Month");
413                 i.setValidValues(monthValidValue);
414                 i.setDefaultValue(Integer.toString(entry.getMonth()));
415                 response.add(i);
416
417                 i = new Input("year", "Year");
418                 i.setValidValues(yearValidValue);
419                 i.setDefaultValue(Integer.toString(entry.getYear()));
420                 response.add(i);
421
422                 Transition t = new Transition("list", this);
423                 response.add(t);
424
425                 t = new Transition("editUpdate", this);
426                 t.addParam("CronId", cronId);
427                 response.add(t);
428             }
429         }
430
431         //We transition down here after synchronize is released so we don't
432
//hold crontab for too long.
433
if (entry == null) {
434             ec = new ErrorCollection();
435             ec.addError("Unable to find cron id of: " + cronId +
436                     ". it may have been removed from the queue");
437             transition("list", request, response);
438
439             return;
440         }
441     }
442
443     /**
444      * Runs the processing of the edit state
445      *
446      * @param request The <code>ControllerRequest</code> object handed to us by
447      * the framework.
448      * @param response The <code>ControllerResponse</code> object handed to us
449      * by the framework.
450      * @throws ControllerException upon error
451      * @throws NonHandleableException upon fatal error
452      */

453     protected void runEditUpdateState(ControllerRequest request,
454                                       ControllerResponse response)
455             throws ControllerException, NonHandleableException {
456         ErrorCollection ec = request.getErrorCollection();
457
458         if (ec != null) {
459             response.saveErrors(ec);
460             transition("list", request, response);
461
462             return;
463         }
464
465         JobHandler jh = ConfigManager.getJobHandler(request.getDataContext());
466         Crontab crontab = jh.getCronManager();
467         String JavaDoc cronId = request.getParameter("CronId");
468         long cronNumber = Long.parseLong(cronId);
469         response.setTitle("Cron Execution Time Result");
470
471         int minute = Integer.parseInt(request.getParameter("minute"));
472         int hour = Integer.parseInt(request.getParameter("hour"));
473         int day = Integer.parseInt(request.getParameter("day"));
474         int dayofWeek = Integer.parseInt(request.getParameter("dayofWeek"));
475         int month = Integer.parseInt(request.getParameter("month"));
476         int year = Integer.parseInt(request.getParameter("year"));
477
478         CrontabEntry entry = null;
479
480         synchronized (crontab) {
481             entry = findCronById(crontab, cronNumber);
482
483             if (entry != null) {
484                 response.add(new Output("result",
485                         "Edited Entry Labelled: " + entry.getLabel()));
486
487                 CrontabEntry newEntry;
488
489                 try {
490                     newEntry = new CrontabEntry(minute, hour, day, dayofWeek,
491                             month, year, entry.getLabel(), entry.getListener());
492                     crontab.addCrontabEntry(newEntry);
493                 } catch (CronException ex) {
494                     throw new ControllerException(
495                             "Unable to construct and add new crontab entry. Old entry still exists in crontab.",
496                             ex);
497                 }
498
499                 crontab.removeCrontabEntry(entry);
500
501                 Transition t = new Transition("list", this);
502                 response.add(t);
503             }
504         }
505
506         //We transition down here after synchronize is released so we don't
507
//hold crontab for too long.
508
if (entry == null) {
509             ec = new ErrorCollection();
510             ec.addError("Unable to find cron id of: " + cronId +
511                     ". it may have been removed from the crontab");
512             transition("list", request, response);
513
514             return;
515         }
516     }
517
518     /**
519      * Runs the List state. Displays all currently running crontabs
520      *
521      * @param request The <code>ControllerRequest</code> object handed to us by
522      * the framework.
523      * @param response The <code>ControllerResponse</code> object handed to us
524      * by the framework.
525      * @throws ControllerException upon error
526      * @throws NonHandleableException upon fatal error
527      */

528     protected void runListState(ControllerRequest request,
529                                 ControllerResponse response)
530             throws ControllerException, NonHandleableException {
531         JobHandler jh = ConfigManager.getJobHandler(request.getDataContext());
532         if (jh == null) {
533             throw new ControllerException(
534                     "The job handler could not be retrieved. Either an error occurred, or it is disabled.");
535         }
536         Crontab crontab = jh.getCronManager();
537         Block records = new Block("records");
538         response.setTitle("Running Crontabs");
539         response.add(records);
540
541         synchronized (crontab) {
542             List JavaDoc l = crontab.getAllEntries();
543
544             if (l.size() == 0) {
545                 response.add(new Output("noCrontabs",
546                         "No crontabs are currently running"));
547             }
548
549             for (Iterator JavaDoc i = l.iterator(); i.hasNext();) {
550                 CrontabEntry entry = (CrontabEntry) i.next();
551
552                 long key = entry.getCounter();
553                 String JavaDoc paramString = Long.toString(key);
554                 Block oneEntry = new Block(paramString);
555                 oneEntry.add(new Output("label", entry.getLabel()));
556                 oneEntry.add(new Output("minute",
557                         Integer.toString(entry.getMinute())));
558                 oneEntry.add(new Output("hour",
559                         Integer.toString(entry.getHour())));
560                 oneEntry.add(new Output("dayofweek",
561                         Integer.toString(entry.getDayOfWeek())));
562                 oneEntry.add(new Output("dayofmonth",
563                         Integer.toString(entry.getDayOfMonth())));
564                 oneEntry.add(new Output("month",
565                         Integer.toString(entry.getMonth())));
566                 oneEntry.add(new Output("year",
567                         Integer.toString(entry.getYear())));
568                 oneEntry.add(new Output("alarmTime",
569                         new Date JavaDoc(entry.getAlarmTime()).toString()));
570                 oneEntry.add(new Output("isRepetitive",
571                         "" + entry.isIsRepetitive()));
572
573                 Transition t = new Transition("edit", this);
574                 t.addParam("CronId", paramString);
575                 oneEntry.add(t);
576
577                 t = new Transition("delete", this);
578                 t.addParam("CronId", paramString);
579                 oneEntry.add(t);
580                 records.add(oneEntry);
581             }
582
583             Transition refresh = new Transition("list", this);
584             refresh.setName("refresh");
585             refresh.setLabel("Refresh List");
586             response.add(refresh);
587         }
588     }
589 }
590
Popular Tags