Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that handles scheduling tasks 
4
 *  Copyright: 2009 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 * 
8
 *   '$Author: daigle $'
9
 *     '$Date: 2009-03-25 13:41:15 -0800 (Wed, 25 Mar 2009) $'
10
 * '$Revision: 4861 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat.scheduler;
28

    
29
import java.io.PrintWriter;
30
import java.util.Calendar;
31
import java.util.HashMap;
32
import java.util.Vector;
33

    
34
import org.apache.log4j.Logger;
35

    
36
import org.quartz.Job;
37
import org.quartz.JobDataMap;
38
import org.quartz.JobDetail;
39
import org.quartz.Scheduler;
40
import org.quartz.SchedulerException;
41
import org.quartz.SchedulerFactory;
42
import org.quartz.SimpleTrigger;
43
import org.quartz.Trigger;
44
import org.quartz.TriggerUtils;
45

    
46
import edu.ucsb.nceas.metacat.shared.AccessException;
47
import edu.ucsb.nceas.metacat.shared.BaseService;
48
import edu.ucsb.nceas.metacat.shared.ServiceException;
49
import edu.ucsb.nceas.utilities.DateUtil;
50
import edu.ucsb.nceas.utilities.StatusUtil;
51
import edu.ucsb.nceas.utilities.UtilException;
52

    
53
public class SchedulerService extends BaseService {
54
	
55
	private static SchedulerService schedulerService = null;
56
	
57
	private static Logger logMetacat = Logger.getLogger(SchedulerService.class);
58
	
59
	private static Scheduler sched = null;
60

    
61
	/**
62
	 * private constructor since this is a singleton
63
	 */
64
	private SchedulerService() throws ServiceException {
65
		start();
66
	}
67
	
68
	/**
69
	 * Get the single instance of SchedulerService.
70
	 * 
71
	 * @return the single instance of SchedulerService
72
	 */
73
	public static SchedulerService getInstance() throws ServiceException {
74
		if (schedulerService == null) {
75
			schedulerService = new SchedulerService();
76
		}
77
		return schedulerService;
78
	}
79
	
80
	// this is a refreshable class
81
	public boolean refreshable() {
82
		return true;
83
	}
84

    
85
	// do the refresh
86
	public void doRefresh() throws ServiceException {
87
		stop();
88
		start();
89
	}
90

    
91
	// initialize the service
92
	public void start() throws ServiceException {
93
		try {
94
			// get the Quartz scheduler factory
95
			SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
96
			
97
			// get the scheduler
98
			sched = schedFact.getScheduler();
99
			sched.start();
100
			
101
			// get all existing jobs from the database
102
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
103
			HashMap<Long, ScheduledJobDAO> allJobsMap = jobAccess.getAllJobs(null);
104
			
105
			// reschedule each job that is in a SCHEDULED state.  
106
			for (Long jobId : allJobsMap.keySet()) {
107
				ScheduledJobDAO jobDAO = allJobsMap.get(jobId);
108
				String[] groups = {"scheduler_group"};
109
				if (jobDAO.getStatus().equals(StatusUtil.SCHEDULED)) {
110
					// send false as the last param so the reschedule method will not 
111
					// complain that the job is already in a SCHEDULED state.
112
					rescheduleJob(jobDAO, "scheduler_user", groups, false);
113
				}
114
			}			
115
			
116
		} catch (AccessException ae) {
117
			throw new ServiceException("SchedulerService.start - DB Access issue when starting scheduler: ", ae);
118
		} catch (SchedulerException se) {
119
			throw new ServiceException("SchedulerService.start - Scheduler engine issue when starting scheduler: " + se.getMessage());
120
		}		
121
	}
122
	
123
	// Stop the scheduler
124
	public void stop() throws ServiceException {
125
		try {
126
			sched.shutdown();
127
			sched = null;
128
		} catch (SchedulerException se) {
129
			throw new ServiceException("SchedulerService.stop - Could not shut down scheduler: " + se.getMessage());
130
		}		
131
	}
132
	
133
	// this will eventually return the scheduler status
134
	protected Vector<String> getStatus() throws ServiceException {
135
		return new Vector<String>();
136
	}
137
	
138
	/**
139
	 * Schedule a job
140
	 * 
141
	 * @param jobDAO
142
	 *            the job data object to schedule
143
	 * @param username
144
	 *            the user that we will use to schedule
145
	 * @param groups
146
	 *            the user group that we will use to schedule
147
	 * @return a message saying that the job was scheduled
148
	 */
149
	public String scheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups) throws ServiceException {
150
        
151
		// convert the start time to a calendar object
152
		Calendar startTimeCal = Calendar.getInstance();
153
        startTimeCal.setTime(jobDAO.getStartTime());
154
        
155
		// convert the start time to a calendar object
156
		Calendar endTimeCal = Calendar.getInstance();
157
        endTimeCal.setTime(jobDAO.getEndTime());
158
        
159
        // extract the job parameters from their data objects and put into a string map
160
        HashMap<String, String> jobParams = new HashMap<String, String>();
161
        HashMap<String, ScheduledJobParamDAO> jobParamDAOs = jobDAO.getAllJobParams();
162
        for (String paramName : jobParamDAOs.keySet()) {
163
        	jobParams.put(paramName, jobParamDAOs.get(paramName).getValue());   	
164
        }
165
        
166
        // schedule the job
167
		return scheduleJob(jobDAO.getName(), startTimeCal, endTimeCal, jobDAO.getIntervalValue(), 
168
				jobDAO.getIntervalUnit(), jobDAO.getClassName(), jobDAO.getGroupName(), 
169
				jobParams);
170
	}
171
	
172
	/**
173
	 * schedule a job
174
	 * 
175
	 * @param jobName
176
	 *            the name of the job
177
	 * @param startCal
178
	 *            a calendar holding the start date of the job
179
	 * @param endCal
180
	 *            a calendar holding the end date of the job
181
	 * @param intervalValue
182
	 *            the run interval for the job
183
	 * @param intervalUnit
184
	 *            the unit of the run interval for the job
185
	 * @param jobClassName
186
	 *            the job class name
187
	 * @param jobGroup
188
	 *            the job group name
189
	 * @param jobParams
190
	 *            a map of additional job parameters
191
	 * @param username
192
	 *            the user name
193
	 * @param groups
194
	 *            the user's group name
195
	 * @return a message saying that the job was scheduled
196
	 */
197
	public String scheduleJob(String jobName, Calendar startCal, Calendar endCal, int intervalValue, 
198
			String intervalUnit, String jobClassName, String jobGroup, HashMap<String, String> jobParams) 
199
	throws ServiceException {
200
        
201
        Class<Job> jobClass = null;
202
        try {
203
			jobClass = (Class<Job>) Class.forName(jobClassName);
204

    
205
			String startTimeStr = DateUtil.getHumanReadable(startCal);
206
			logMetacat.info("SchedulerService.scheduleJob - Scheduling job -- name: "
207
					+ jobName + ", class: " + jobClassName + ", start time: "
208
					+ startTimeStr + ", interval value: " + intervalValue
209
					+ ", interval unit: " + intervalUnit);
210

    
211
			// start the job in the job scheduler
212
			startJob(jobName, startCal, endCal, intervalValue, intervalUnit, jobClass, jobGroup,
213
					jobParams);
214

    
215
			// get a database access object and create the job in the database
216

    
217
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
218
			jobAccess.createJob(jobName, jobName, jobGroup, jobClass, startCal, endCal,
219
					intervalValue, intervalUnit, jobParams);
220
		} catch (AccessException ae) {
221
			try {
222
				deleteJob(jobName);
223
			} catch (Exception e) {
224
				// Not much we can do here but log this
225
				logMetacat.error("SchedulerService.scheduleJob - An access exception was thrown when writing job: "
226
						+ jobName + "to the db, and another exception was thrown when trying to remove the "
227
						+ "job from the scheduler.  The db and scheduler may be out of sync: " + e.getMessage());
228
			}
229
			throw new ServiceException("SchedulerService.scheduleJob - Error accessing db: ", ae);
230
		} catch (ClassNotFoundException cnfe) {
231
			throw new ServiceException("SchedulerService.scheduleJob - Could not find class with name: "
232
							+ jobClassName + " : " + cnfe.getMessage());
233
		} catch (UtilException ue) {
234
			throw new ServiceException("SchedulerService.scheduleJob - Could not schedule "
235
							+ "job due to a utility issue: " + ue.getMessage());
236
		}
237
		
238
		return "Scheduled: " + jobName;
239
	}
240
	
241
	/**
242
	 * schedule a job one time with a given delay. The job is registered in the
243
	 * scheduler, but not persisted to the database. The delay is calculated
244
	 * from the time that this method is called.
245
	 * 
246
	 * @param jobName
247
	 *            the name of the job
248
	 * @param delay
249
	 *            the delay in seconds, minutes, hours or days from the time
250
	 *            this method is called (i.e. 30s, 5m, 2h, 1d)
251
	 * @param jobClassName
252
	 *            the job class name
253
	 * @param jobGroup
254
	 *            the job group name
255
	 * @param jobParams
256
	 *            a map of additional job parameters
257
	 * @param username
258
	 *            the user name
259
	 * @param groups
260
	 *            the user's group name
261
	 * @return a message saying that the job was scheduled
262
	 */
263
	public String scheduleDelayedJob(String jobName, String delay, String jobClassName, 
264
			String jobGroup, HashMap<String, String> jobParams, 
265
			String username, String[] groups) throws ServiceException {
266
        
267
        Class<Job> jobClass = null;
268
        try {
269
			jobClass = (Class<Job>) Class.forName(jobClassName);
270
			
271
			Calendar startCal = getStartDateFromDelay(delay);
272

    
273
			logMetacat.info("SchedulerService.scheduleDelayedJob - Scheduling job -- name: "
274
					+ jobName + ", delay: " + delay + ", job class name: " + jobClassName);
275

    
276
			// start the job in the job scheduler
277
			startOneTimeJob(jobName, startCal, jobClass, jobGroup,
278
					jobParams);
279

    
280
		} catch (ClassNotFoundException cnfe) {
281
			throw new ServiceException("SchedulerService.scheduleJob - Could not find class with name: "
282
							+ jobClassName + " : " + cnfe.getMessage());
283
		} 
284
		
285
		return "Scheduled: " + jobName;
286
	}
287
	
288
	/**
289
	 * Unschedule a job. This removed it from the scheduler in memory and
290
	 * changed it's status to unscheduled in the database.
291
	 * 
292
	 * @param jobName
293
	 *            the name of the job to unschedule
294
	 * @param username
295
	 *            the user name
296
	 * @param groups
297
	 *            the user's group name
298
	 * @return a message saying the job was unscheduled
299
	 */
300
	public String unscheduleJob(String jobName, String username,
301
			String[] groups) throws ServiceException {
302
		
303
		ScheduledJobDAO jobDAO = null;
304
		try {
305
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
306
			jobDAO = jobAccess.getJobByName(jobName);
307
			if (jobDAO == null) {
308
				throw new ServiceException("SchedulerService.unscheduleJob - Could " 
309
						+ "not find job with name: " + jobName);
310
			}
311

    
312
			// remove the job from the scheduler
313
			sched.deleteJob(jobDAO.getName(), jobDAO.getGroupName());
314

    
315
			// change the status of the job to unscheduled in the database.
316
			jobDAO.setStatus(StatusUtil.UNSCHEDULED);
317
			jobAccess.updateJobStatus(jobDAO);
318
		} catch (SchedulerException se) {
319
			throw new ServiceException("SchedulerService.unscheduleJob - Could not create "
320
							+ "scheduled job because of service issue: " + se.getMessage());
321
		} catch (AccessException ae) {
322
			throw new ServiceException("SchedulerService.unscheduleJob - Could not create "
323
							+ "scheduled job : " + jobDAO.getName() + " because of db access issue: ", ae);
324
		}
325
		
326
		return "Unscheduled: " + jobName;
327
	}
328
	
329
	/**
330
	 * Reschedule a job. This call will always check to make sure the status is not SCHEDULED
331
	 * @param jobDAO the job data object holding the information about the job to reschedule
332
	 * @param username
333
	 *            the user name
334
	 * @param groups
335
	 *            the user's group name
336
	 * @return a message saying that the job was rescheduled
337
	 */
338
	public String rescheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups) throws ServiceException {
339
		return rescheduleJob(jobDAO, username, groups, true);
340
	}
341
	
342
	/**
343
	 * Reschedule a job.
344
	 * 
345
	 * @param jobDAO
346
	 *            the job data object holding the information about the job to
347
	 *            reschedule
348
	 * @param username
349
	 *            the user name
350
	 * @param groups
351
	 *            the user's group name
352
	 * @param checkStatus
353
	 *            if set to true, the method will check to make sure the status
354
	 *            is UNSCHEDULED before restarting. Otherwise, the method will
355
	 *            not check. This is so that we can restart a service at startup
356
	 *            that was running when metacat was shut down.
357
	 * @return a message saying that the job was rescheduled
358
	 */
359
	public String rescheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups, boolean checkStatus) throws ServiceException {
360
		
361
		try {
362
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
363
        
364
			if (jobDAO == null) {
365
				throw new ServiceException("SchedulerService.reScheduleJob - Cannot reschedule nonexistant job.");
366
			}
367
        
368
			// if we are checking status, make sure the job is in an UNSCHEDULED state in the db
369
			if (checkStatus && !jobDAO.getStatus().equals(StatusUtil.UNSCHEDULED)) {
370
				throw new ServiceException("SchedulerService.reScheduleJob - Cannot reschedule a job with status: " 
371
						+ jobDAO.getStatus() + ". Status must be 'unscheduled'.");
372
			}
373
        
374
			Calendar startCal = Calendar.getInstance();
375
	        startCal.setTime(jobDAO.getStartTime());
376
	        
377
			Calendar endCal = Calendar.getInstance();
378
	        endCal.setTime(jobDAO.getEndTime());
379
	        
380
	        HashMap<String, String> jobParams = new HashMap<String, String>();
381
	        HashMap<String, ScheduledJobParamDAO> jobParamDAOs = jobDAO.getAllJobParams();
382
	        for (String paramName : jobParamDAOs.keySet()) {
383
	        	jobParams.put(paramName, jobParamDAOs.get(paramName).getValue());   	
384
	        }
385
	        
386
	        Class<Job> jobClass = null;
387
	        String jobClassName = jobDAO.getClassName();
388
	        try {        	
389
	        	jobClass = (Class<Job>)Class.forName(jobClassName);     	
390
	        } catch (ClassNotFoundException cnfe) {
391
	        	throw new ServiceException("SchedulerService.scheduleJob - Could not find class with name: " 
392
	        			+ jobDAO.getClassName() + " : " + cnfe.getMessage());
393
	        } 
394
	        
395
	        String startTimeStr = DateUtil.getHumanReadable(startCal);
396
	        logMetacat.info("SchedulerService.rescheduleJob - name: " + jobDAO.getName() + ", class: " + jobClassName 
397
	        		+ ", start time: " + startTimeStr + ", interval value: " + jobDAO.getIntervalValue() 
398
	        		+ ", interval unit: " + jobDAO.getIntervalUnit());  
399
			
400
	        // start the job in the scheduler
401
			startJob(jobDAO.getName(), startCal, endCal, jobDAO.getIntervalValue(), jobDAO.getIntervalUnit(), jobClass, jobDAO.getGroupName(), jobParams);
402
	        
403
			// update the status in the database
404
			jobDAO.setStatus(StatusUtil.SCHEDULED);
405
			jobAccess.updateJobStatus(jobDAO);
406
			
407
		} catch (AccessException ae) {
408
			throw new ServiceException("SchedulerService.reScheduleJob - Could not reschedule "
409
					+ "job : " + jobDAO.getName() + " because of db access issue: ", ae);
410
		} catch (UtilException ue) {
411
			throw new ServiceException("SchedulerService.reScheduleJob - Could not reschedule "
412
					+ "job : " + jobDAO.getName() + " due to a utility issue: " + ue.getMessage());
413
		}
414
        		
415
		return "Rescheduled: " + jobDAO.getName();
416
	}
417

    
418
	/**
419
	 * Remove the job from the scheduler and set the job status to deleted in the database
420
	 * @param jobName
421
	 *            the string holding the name of the job to delete
422
	 * @param username
423
	 *            the user name
424
	 * @param groups
425
	 *            the user's group name
426
	 * @return a message saying that the job was deleted
427
	 */
428
	public String deleteJob(String jobName) throws ServiceException {
429
		
430
		ScheduledJobDAO jobDAO = null;
431
		try {	
432
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
433
			jobDAO = jobAccess.getJobByName(jobName);
434
		} catch (AccessException ae) {
435
			throw new ServiceException("SchedulerService.deleteJob - Could not delete "
436
					+ "scheduled job : " + jobDAO.getName() + " because of db access issue: ", ae);
437
		}
438
		
439
		return deleteJob(jobDAO);
440
	}
441
	
442
	/**
443
	 * Remove the job from the scheduler and set the job status to deleted in the database
444
	 * @param jobDAO
445
	 *            the job data object holding the information about the job to delete
446
	 * @param username
447
	 *            the user name
448
	 * @param groups
449
	 *            the user's group name
450
	 * @return a message saying that the job was deleted
451
	 */
452
	public String deleteJob(ScheduledJobDAO jobDAO) throws ServiceException {
453

    
454
		String groupName = "";
455
		try {
456

    
457
			sched.deleteJob(jobDAO.getName(), groupName);
458
			
459
			jobDAO.setStatus(StatusUtil.DELETED);
460
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
461
			jobAccess.updateJobStatus(jobDAO);
462
		} catch (SchedulerException se) {
463
			throw new ServiceException("SchedulerService.deleteJob - Could not delete job: " + jobDAO.getName()
464
							+ " for group: " + groupName + " : " + se.getMessage());
465
		} catch (AccessException ae) {
466
			throw new ServiceException("SchedulerService.deleteJob - Could not delete "
467
					+ "scheduled job: " + jobDAO.getName() + " because of db access issue: ", ae);
468
		}
469
		
470
		return "Deleted: " + jobDAO.getName();
471
	}
472
	
473
	/**
474
	 * Get information about the job in XML format
475
	 * 
476
	 * @param jobId
477
	 *            the job for which we want the information
478
	 * @return an XML representation of the job
479
	 */
480
	public String getJobInfoXML(Long jobId) throws ServiceException {
481
		String jobInfoXML = "";
482
		
483
		try {
484
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
485
			ScheduledJobDAO scheduledJobDAO = jobAccess.getJob(jobId);
486
			
487
			jobInfoXML += 
488
				"<scheduledJobs>" + jobToXML(scheduledJobDAO) + "</scheduledJobs>";
489
			
490
		} catch (AccessException ae) {
491
			throw new ServiceException("SchedulerService.getJobInfoXML - Could not get job info for job: " 
492
					+ jobId, ae);
493
		}
494
		
495
		return jobInfoXML;
496
	}
497
	
498
	/**
499
	 * Get the information for jobs in a group in an xml format. A parameter
500
	 * key/value pair can be provided as well to limit the jobs returned.
501
	 * 
502
	 * @param groupName
503
	 *            the job group that we are searching for
504
	 * @param paramName
505
	 *            the parameter name that we are looking for. this is ignored if
506
	 *            null
507
	 * @param paramValue
508
	 *            the parameter value that we are looking for. this is ignored
509
	 *            if null
510
	 * @return an XML representation of the jobs.
511
	 */
512
	public String getJobsInfoXML(String groupName, String paramName, String paramValue) throws ServiceException {
513
		String jobInfoXML = "";
514
		
515
		try {
516
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
517
			HashMap<Long, ScheduledJobDAO> JobDAOMap = jobAccess.getJobsWithParameter(groupName, paramName, paramValue);
518
			
519
			jobInfoXML += "<scheduledWorkflowResultset>";
520
			for (Long jobDAOId : JobDAOMap.keySet()) {
521
				ScheduledJobDAO jobDAO = JobDAOMap.get(jobDAOId); 
522
				if (paramValue != null && paramName != null) {
523
					ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam(paramName);
524
					if(jobParamDAO != null && jobParamDAO.getValue().equals(paramValue)) {
525
						jobInfoXML +=  jobToXML(JobDAOMap.get(jobDAOId)); 
526
					}
527
				}
528
			}				
529
			jobInfoXML += "</scheduledWorkflowResultset>";
530
			
531
		} catch (AccessException ae) {
532
			throw new ServiceException("SchedulerService.getJobInfoXML - Could not get jobs info for group: " 
533
					+ groupName, ae);
534
		}
535
		
536
		return jobInfoXML;
537
	}
538
	
539
	/**
540
	 * Get the information for jobs in a group in an xml format. A parameter
541
	 * key/value pair can be provided as well to limit the jobs returned.
542
	 * 
543
	 * @param groupName
544
	 *            the job group that we are searching for
545
	 * @param paramName
546
	 *            the parameter name that we are looking for. this is ignored if
547
	 *            null
548
	 * @param paramValue
549
	 *            the parameter value that we are looking for. this is ignored
550
	 *            if null
551
	 * @return an XML representation of the jobs.
552
	 */
553
	public void getJobsInfoXML(String groupName, String paramName, String paramValue, PrintWriter pw) throws ServiceException {
554
		
555
		try {
556
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
557
			HashMap<Long, ScheduledJobDAO> JobDAOMap = jobAccess.getJobsWithParameter(groupName, paramName, paramValue);
558
			
559
			pw.print("<scheduledWorkflowResultset>");
560
			for (Long jobDAOId : JobDAOMap.keySet()) {
561
				ScheduledJobDAO jobDAO = JobDAOMap.get(jobDAOId); 
562
				if (paramValue != null && paramName != null) {
563
					ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam(paramName);
564
					if(jobParamDAO != null && jobParamDAO.getValue().equals(paramValue)) {
565
						pw.print(jobToXML(JobDAOMap.get(jobDAOId))); 
566
					}
567
				}
568
			}				
569
			pw.print("</scheduledWorkflowResultset>");
570
			
571
		} catch (AccessException ae) {
572
			throw new ServiceException("SchedulerService.getJobInfoXML - Could not get jobs info for group: " 
573
					+ groupName, ae);
574
		}
575
	}
576
	
577
	/**
578
	 * Convert a single job to XML
579
	 * @param scheduledJobDAO the job we want to convert
580
	 * @return an XML representation of the job
581
	 */
582
	public String jobToXML(ScheduledJobDAO scheduledJobDAO) throws ServiceException {
583
		String jobXML = "";
584

    
585
		if (scheduledJobDAO != null) {
586
			jobXML += "<scheduledJob>";
587
			jobXML += "<id>" + scheduledJobDAO.getId() + "</id>";
588
			jobXML += "<createTime>" + scheduledJobDAO.getCreateTime() + "</createTime>";
589
			jobXML += "<modTime>" + scheduledJobDAO.getModTime() + "</modTime>";
590
			jobXML += "<status>" + scheduledJobDAO.getStatus() + "</status>";
591
			jobXML += "<name>" + scheduledJobDAO.getName() + "</name>";
592
			jobXML += "<triggerName>" + scheduledJobDAO.getName() + "</triggerName>";
593
			jobXML += "<groupName>" + scheduledJobDAO.getGroupName() + "</groupName>";
594
			jobXML += "<className>" + scheduledJobDAO.getClassName() + "</className>";
595
			String startTimeString = null;
596
			try {
597
				startTimeString = 
598
					DateUtil.getHumanReadable(scheduledJobDAO.getStartTime());
599
			} catch (UtilException ue) {
600
				throw new ServiceException("SchedulerService.jobToXML - error getting human readable date for job: " 
601
						+ scheduledJobDAO.getId() + " ; " + ue.getMessage());
602
			}
603
			jobXML += "<startTime>" + startTimeString + "</startTime>";
604
			
605
			String endTimeString = null;
606
			try {
607
				if (scheduledJobDAO.getEndTime() != null) {
608
					endTimeString = DateUtil.getHumanReadable(scheduledJobDAO.getEndTime());
609
				}
610
			} catch (UtilException ue) {
611
				throw new ServiceException("SchedulerService.jobToXML - error getting human readable date for job: " 
612
						+ scheduledJobDAO.getId() + " ; " + ue.getMessage());
613
			}
614
			jobXML += "<endTime>" + endTimeString + "</endTime>";
615
			jobXML += "<intervalValue>" + scheduledJobDAO.getIntervalValue() + "</intervalValue>";
616
			jobXML += "<intervalUnit>" + scheduledJobDAO.getIntervalUnit() + "</intervalUnit>";
617

    
618
			HashMap<String, ScheduledJobParamDAO> jobParams = scheduledJobDAO
619
					.getAllJobParams();
620
			for (String jobParamKey : jobParams.keySet()) {
621
				jobXML += "<jobParam name='" + jobParams.get(jobParamKey).getKey() + "'>";
622
				jobXML += "<id>" + jobParams.get(jobParamKey).getId() + "</id>";
623
				jobXML += "<createTime>" + jobParams.get(jobParamKey).getCreateTime()
624
						+ "</createTime>";
625
				jobXML += "<modTime>" + jobParams.get(jobParamKey).getModTime()
626
						+ "</modTime>";
627
				jobXML += "<status>" + jobParams.get(jobParamKey).getStatus()
628
						+ "</status>";
629
				jobXML += "<jobId>" + jobParams.get(jobParamKey).getJobId() + "</jobId>";
630
				jobXML += "<key>" + jobParams.get(jobParamKey).getKey() + "</key>";
631
				jobXML += "<value>" + jobParams.get(jobParamKey).getValue() + "</value>";
632
				jobXML += "</jobParam>";
633
			}
634
			jobXML += "</scheduledJob>";
635
		}
636

    
637
		return jobXML;
638
	}
639
	
640
	/**
641
	 * Start a job in the scheduler
642
	 * 
643
	 * @param jobName
644
	 *            the name of the job
645
	 * @param startCal
646
	 *            a calendar holding the start date of the job
647
	 * @param intervalValue
648
	 *            the run interval for the job
649
	 * @param intervalUnit
650
	 *            the unit of the run interval for the job
651
	 * @param jobClassName
652
	 *            the job class name
653
	 * @param jobGroup
654
	 *            the job group name
655
	 * @param jobParams
656
	 *            a map of additional job parameters
657
	 * @param username
658
	 *            the user name
659
	 * @param groups
660
	 *            the user's group name
661
	 */
662
	private void startJob(String jobName, Calendar startCal, Calendar endCal, int intervalValue, String intervalUnit,
663
			Class<Job> jobClass, String jobGroup, HashMap<String, String> jobParams) throws ServiceException { 
664
		
665
		JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass);
666
		jobDetail.setJobDataMap(new JobDataMap(jobParams));
667
		
668
		char intervalChar = intervalUnit.charAt(0);
669
		
670
		// call the appropriate scheduling method depending on the schedule interval unit
671
		switch (intervalChar) {
672
		case 's':
673
		case 'S':
674
			scheduleSecondlyJob(jobName, jobClass, startCal, endCal, intervalValue, jobGroup, jobDetail);
675
			break;
676
		case 'm':
677
		case 'M':
678
			scheduleMinutelyJob(jobName, jobClass, startCal, endCal, intervalValue, jobGroup, jobDetail);
679
			break;
680
		case 'h':
681
		case 'H':
682
			scheduleHourlyJob(jobName, jobClass, startCal, endCal, intervalValue, jobGroup, jobDetail);
683
			break;
684
		case 'd':
685
		case 'D':
686
			scheduleDailyJob(jobName, jobClass, startCal, endCal, intervalValue, jobGroup, jobDetail);
687
			break;
688
		default:
689
			throw new ServiceException("SchedulerService.scheduleJob - Could not interpret interval unit: " 
690
					+ intervalUnit + ". Unit must be s, m, h or d");	
691
		}	
692
	}
693
	
694
	/**
695
	 * Schedule a job in the scheduler that has an interval based in seconds
696
	 * 
697
	 * @param jobName
698
	 *            the name of the job
699
	 * @param jobClass
700
	 *            the job class object
701
	 * @param startTime
702
	 *            the time of the first run
703
	 * @param jobGroup
704
	 *            the group of this job
705
	 * @param jobDetail
706
	 *            the job detail object
707
	 */
708
	private void startOneTimeJob(String jobName, Calendar startTime, Class<Job> jobClass, String jobGroup, HashMap<String, String> jobParams) throws ServiceException {
709

    
710
		JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass);
711
		jobDetail.setJobDataMap(new JobDataMap(jobParams));
712
		
713
		SimpleTrigger trigger = new SimpleTrigger();
714
		trigger.setName(jobName);
715
		trigger.setStartTime(startTime.getTime());
716
		trigger.setRepeatCount(1);
717

    
718
		try {
719
			sched.scheduleJob(jobDetail, trigger);
720
		} catch (SchedulerException se) {
721
			throw new ServiceException("SchedulerService.scheduleSecondlyJob - Could not create " 
722
					+ "scheduler: " + se.getMessage());
723
		}
724
	}
725
	
726
	/**
727
	 * Schedule a job in the scheduler that has an interval based in seconds
728
	 * 
729
	 * @param jobName
730
	 *            the name of the job
731
	 * @param jobClass
732
	 *            the job class object
733
	 * @param startTime
734
	 *            the time of the first run
735
	 * @param interval
736
	 *            the interval in seconds between runs
737
	 * @param jobGroup
738
	 *            the group of this job
739
	 * @param jobDetail
740
	 *            the job detail object
741
	 */
742
	private void scheduleSecondlyJob(String jobName, Class<Job> jobClass, Calendar startTime, Calendar endTime, int interval, String jobGroup, JobDetail jobDetail) throws ServiceException {
743

    
744
		Trigger trigger = TriggerUtils.makeSecondlyTrigger(interval);
745
		trigger.setName(jobName);
746
		trigger.setStartTime(startTime.getTime());
747
		if (endTime != null) {
748
			trigger.setEndTime(endTime.getTime());
749
		}
750

    
751
		try {
752
			sched.scheduleJob(jobDetail, trigger);
753
		} catch (SchedulerException se) {
754
			throw new ServiceException("SchedulerService.scheduleSecondlyJob - Could not create " 
755
					+ "scheduler: " + se.getMessage());
756
		}
757
	}
758
	
759
	/**
760
	 * Schedule a job in the scheduler that has an interval based in minutes
761
	 * 
762
	 * @param jobName
763
	 *            the name of the job
764
	 * @param jobClass
765
	 *            the job class object
766
	 * @param startTime
767
	 *            the time of the first run
768
	 * @param interval
769
	 *            the interval in minutes between runs
770
	 * @param jobGroup
771
	 *            the group of this job
772
	 * @param jobDetail
773
	 *            the job detail object
774
	 */
775
	private void scheduleMinutelyJob(String jobName, Class<Job> jobClass, Calendar startTime, Calendar endTime, int interval, String jobGroup, JobDetail jobDetail) throws ServiceException {
776

    
777
		Trigger trigger = TriggerUtils.makeMinutelyTrigger(interval);
778
		trigger.setName(jobName);
779
		trigger.setStartTime(startTime.getTime());
780
		if (endTime != null) {
781
			trigger.setEndTime(endTime.getTime());
782
		}
783

    
784
		try {
785
			sched.scheduleJob(jobDetail, trigger);
786
		} catch (SchedulerException se) {
787
			throw new ServiceException("SchedulerService.scheduleMinutelyJob - Could not create " 
788
					+ "scheduler: " + se.getMessage());
789
		}
790
	}
791
	
792
	/**
793
	 * Schedule a job in the scheduler that has an interval based in hours
794
	 * 
795
	 * @param jobName
796
	 *            the name of the job
797
	 * @param jobClass
798
	 *            the job class object
799
	 * @param startTime
800
	 *            the time of the first run
801
	 * @param interval
802
	 *            the interval in hours between runs
803
	 * @param jobGroup
804
	 *            the group of this job
805
	 * @param jobDetail
806
	 *            the job detail object
807
	 */
808
	private void scheduleHourlyJob(String jobName, Class<Job> jobClass, Calendar startTime, Calendar endTime, int interval, String jobGroup, JobDetail jobDetail) throws ServiceException {
809

    
810
		Trigger trigger = TriggerUtils.makeHourlyTrigger(interval);
811
		trigger.setName(jobName);
812
		trigger.setStartTime(startTime.getTime());
813
		if (endTime != null) {
814
			trigger.setEndTime(endTime.getTime());
815
		}
816

    
817
		try {
818
			sched.scheduleJob(jobDetail, trigger);
819
		} catch (SchedulerException se) {
820
			throw new ServiceException("SchedulerService.scheduleHourlyJob - Could not create " 
821
					+  "scheduler: " + se.getMessage());
822
		}
823
	}
824
	
825
	/**
826
	 * Schedule a job in the scheduler that has an interval based in days
827
	 * 
828
	 * @param jobName
829
	 *            the name of the job
830
	 * @param jobClass
831
	 *            the job class object
832
	 * @param startTime
833
	 *            the time of the first run
834
	 * @param interval
835
	 *            the interval in days between runs
836
	 * @param jobGroup
837
	 *            the group of this job
838
	 * @param jobDetail
839
	 *            the job detail object
840
	 */
841
	private void scheduleDailyJob(String jobName, Class<Job> jobClass, Calendar startTime, Calendar endTime, int interval, String jobGroup, JobDetail jobDetail) throws ServiceException {
842

    
843
		Trigger trigger = TriggerUtils.makeHourlyTrigger(interval * 24);
844
		trigger.setName(jobName);
845
		trigger.setStartTime(startTime.getTime());
846
		if (endTime != null) {
847
			trigger.setEndTime(endTime.getTime());
848
		}
849

    
850
		try {
851
			sched.scheduleJob(jobDetail, trigger);
852
		} catch (SchedulerException se) {
853
			throw new ServiceException("SchedulerService.scheduleHourlyJob - Could not create " 
854
					+ "scheduler: " + se.getMessage());
855
		}
856
	}
857
	
858
	/**
859
	 * Extract the start date from the delay value
860
	 * 
861
	 * @param delay
862
	 *            a string representing the start delay in <value><unit>
863
	 *            notation where value is an integer and unit is one of s,m,h or
864
	 *            d
865
	 * @return the calendar object holding the start date
866
	 */
867
	public Calendar getStartDateFromDelay(String delay) throws ServiceException {
868
		Calendar cal = Calendar.getInstance();
869
	
870
		char delayUnit = delay.trim().charAt(delay.length() - 1);
871
		String delayStrValue = delay.trim().substring(0, delay.length() - 1);
872
		int delayValue;
873
		try {
874
			delayValue = Integer.parseInt(delayStrValue);
875
		} catch (NumberFormatException nfe) {
876
			throw new ServiceException("SchedulerService.getStartDateFromDelay - Could not " 
877
					+ "parse delay value into an integer: " + delayStrValue + " : " + nfe.getMessage());
878
		}
879
		
880
		switch (delayUnit) {
881
		case 's':
882
		case 'S':
883
			cal.add(Calendar.SECOND, delayValue);
884
			break;
885
		case 'm':
886
		case 'M':
887
			cal.add(Calendar.MINUTE, delayValue);
888
			break;
889
		case 'h':
890
		case 'H':
891
			cal.add(Calendar.HOUR, delayValue);
892
			break;
893
		case 'd':
894
		case 'D':
895
			cal.add(Calendar.DAY_OF_YEAR, delayValue);
896
			break;
897
		default:
898
			throw new ServiceException("SchedulerService.getStartDateFromDelay - Could not " 
899
					+ "interpret delay unit: " + delayUnit + ". Unit must be s, m, h or d");	
900
		}
901
		
902
		return cal;
903
	}	
904
}
(7-7/7)