Project

General

Profile

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

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

    
30
import java.sql.PreparedStatement;
31
import java.sql.ResultSet;
32
import java.sql.SQLException;
33
import java.sql.Timestamp;
34
import java.util.Calendar;
35
import java.util.HashMap;
36
import java.util.Vector;
37

    
38
import org.apache.log4j.Logger;
39
import org.quartz.Job;
40

    
41
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
42
import edu.ucsb.nceas.metacat.shared.AccessException;
43
import edu.ucsb.nceas.metacat.shared.BaseAccess;
44
import edu.ucsb.nceas.utilities.StatusUtil;
45

    
46
public class ScheduledJobAccess extends BaseAccess {
47
	
48
	private Logger logMetacat = Logger.getLogger(ScheduledJobAccess.class);
49
	
50
	// Constructor
51
	public ScheduledJobAccess() throws AccessException {
52
		super("ScheduledJobAccess");
53
	}
54
	
55
	/**
56
	 * Get a job based on it's id
57
	 * 
58
	 * @param jobId
59
	 *            the id of the job in the database
60
	 * @return the scheduled job data object that represents the desired job
61
	 */ 
62
	public ScheduledJobDAO getJob(Long jobId) throws AccessException {
63
		ScheduledJobDAO jobDAO = null;
64

    
65
		// first get the job from the db and put it into a DAO
66
		PreparedStatement pstmt = null;
67
		try {
68
			String sql = "SELECT * FROM scheduled_job WHERE id = ? AND status != 'deleted'"; 
69
			pstmt = conn.prepareStatement(sql);
70

    
71
			pstmt.setLong(1, jobId);
72
			
73
			String sqlReport = "ScheduledJobAccess.getJob - SQL: " + sql;
74
			sqlReport += " [" + jobId + "]";
75
			
76
			logMetacat.info(sqlReport);
77
			
78
			pstmt.execute();
79
			
80
			ResultSet resultSet = pstmt.getResultSet();
81
			if (resultSet.next()) {
82
				jobDAO = populateDAO(resultSet);
83
			}
84
			
85
		} catch (SQLException sqle) {
86
			throw new AccessException("ScheduledJobAccess.getJob - SQL error when getting scheduled job: " 
87
					+ jobId  + " : "  + sqle.getMessage());
88
		} finally {
89
			try {
90
				if (pstmt != null) {
91
					pstmt.close();
92
				}
93
			} catch (SQLException sqle) {
94
				logMetacat.error("ScheduledJobAccess.getJob - An error occurred " 
95
						+ "closing prepared statement: " + sqle.getMessage());
96
			} 
97
		}	
98
		
99
		// Now get all the job parameters and put those into a list of job parameter
100
		// DAOs and add that list to the job DAO
101
		ScheduledJobParamAccess jobParamAccess = new ScheduledJobParamAccess();
102
		Vector<ScheduledJobParamDAO> jobParamList = 
103
			jobParamAccess.getJobParamsForJobId(jobDAO.getId());
104
		
105
		for(ScheduledJobParamDAO jobParamDAO : jobParamList) {
106
			jobDAO.addJobParam(jobParamDAO);
107
		}
108
		
109
		return jobDAO;		
110
	}
111
	
112
	/**
113
	 * Get a job by it's name
114
	 * @param jobName the name of the job to get
115
	 * @return the scheduled job data object that represents the desired job
116
	 */
117
	public ScheduledJobDAO getJobByName(String jobName) throws AccessException {
118
		ScheduledJobDAO jobDAO = null;
119

    
120
		// first get the job from the db and put it into a DAO
121
		PreparedStatement pstmt = null;
122
		try {
123
			String sql = "SELECT * FROM scheduled_job WHERE name = ? AND status != 'deleted'"; 
124
			pstmt = conn.prepareStatement(sql);
125

    
126
			pstmt.setString(1, jobName);
127
			
128
			String sqlReport = "ScheduledJobAccess.getJobByName - SQL: " + sql;
129
			sqlReport += " [" + jobName + "]";
130
			
131
			logMetacat.info(sqlReport);
132
			
133
			pstmt.execute();
134
			
135
			ResultSet resultSet = pstmt.getResultSet();
136
			if (resultSet.next()) {
137
				jobDAO = populateDAO(resultSet);
138
			} else {
139
				throw new AccessException("ScheduledJobAccess.getJobByName - could not find scheduled job with name: " 
140
						+ jobName);
141
			}
142
			
143
		} catch (SQLException sqle) {
144
			throw new AccessException("ScheduledJobAccess.getJobByName - SQL error when getting scheduled job by name: " 
145
					+ jobName  + " : "  + sqle.getMessage());
146
		} finally {
147
			try {
148
				if (pstmt != null) {
149
					pstmt.close();
150
				}
151
			} catch (SQLException sqle) {
152
				logMetacat.error("ScheduledJobAccess.getJobByName - An error occurred " 
153
						+ "closing prepared statement: " + sqle.getMessage());
154
			} finally {
155
				DBConnectionPool.returnDBConnection(conn, serialNumber);
156
			}
157
		}	
158
		
159
		// Now get all the job parameters and put those into a list of job parameter
160
		// DAOs and add that list to the job DAO
161
		ScheduledJobParamAccess jobParamAccess = new ScheduledJobParamAccess();
162
		Vector<ScheduledJobParamDAO> jobParamList = 
163
			jobParamAccess.getJobParamsForJobId(jobDAO.getId());
164
		
165
		for(ScheduledJobParamDAO jobParamDAO : jobParamList) {
166
			jobDAO.addJobParam(jobParamDAO);
167
		}
168
		
169
		return jobDAO;		
170
	}
171
	
172
	/**
173
	 * Get all jobs that have a given parameter with a given value
174
	 * 
175
	 * @param groupName
176
	 *            the group to which the job belongs. This keeps us from
177
	 *            returning unrelated jobs that just happen to have a similar
178
	 *            parameter
179
	 * @param paramName
180
	 *            the name of the parameter we are looking for
181
	 * @param paramValue
182
	 *            the value of the parameter we are looking for
183
	 * @return a HashMap of job data objects with all jobs in a given group that
184
	 *         have parameters that match our parameter.
185
	 */
186
	public HashMap<Long, ScheduledJobDAO> getJobsWithParameter(String groupName, String paramName, String paramValue) throws AccessException {
187

    
188
		// first get all jobs
189
		HashMap<Long, ScheduledJobDAO> allJobsMap = getAllJobs(groupName);
190
		HashMap<Long, ScheduledJobDAO> jobsWithParamMap = new HashMap<Long, ScheduledJobDAO>();
191
		
192
		// then iterate through and grab the ones that have the desired parameter
193
		for (Long jobDAOId : allJobsMap.keySet()) {
194
			ScheduledJobDAO jobDAO = allJobsMap.get(jobDAOId); 
195
			if (paramValue != null && paramName != null) {
196
				ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam(paramName);
197
				if(jobParamDAO != null && jobParamDAO.getValue().equals(paramValue)) {
198
					jobsWithParamMap.put(jobDAOId, jobDAO);
199
				}
200
			}
201
		}		
202
		
203
		return jobsWithParamMap;
204
	}
205
	
206
	/**
207
	 * Get all jobs for a given group.  A group is typically a category that coincides with
208
	 * the job type (has it's own job implementation).  
209
	 * @param groupName the name of the group we want to search
210
	 * @return a HashMap of job data objects for the desired group.
211
	 */
212
	public HashMap<Long, ScheduledJobDAO> getAllJobs(String groupName) throws AccessException {
213
		ScheduledJobDAO jobDAO = null;
214
		
215
		HashMap<Long, ScheduledJobDAO> allJobDAOs = new HashMap<Long, ScheduledJobDAO>();
216

    
217
		// Get all jobs where the status is not deleted
218
		PreparedStatement pstmt = null;
219
		try {
220
			String sql = "SELECT * FROM scheduled_job WHERE status != 'deleted'"; 
221
			if (groupName != null) {
222
				sql += " AND group_name = ?" ;
223
			}
224
			pstmt = conn.prepareStatement(sql);
225
			
226
			String sqlReport = "ScheduledJobAccess.getAllJobs - SQL: " + sql;
227
			if (groupName != null) {
228
				pstmt.setString(1, groupName);
229
				
230
				sqlReport += " [" + groupName + "]";
231
			}
232
			
233
			logMetacat.info(sqlReport);
234
						
235
			pstmt.execute();
236
			
237
			ResultSet resultSet = pstmt.getResultSet();
238
			while (resultSet.next()) {
239
				jobDAO = populateDAO(resultSet);
240
				
241
				allJobDAOs.put(jobDAO.getId(), jobDAO);
242
			}
243
			
244
			// Here we grab all job params and put them into the associated jobs.  THis
245
			// takes a little stress off the database by avoiding a join.
246
			ScheduledJobParamAccess jobParamAccess = new ScheduledJobParamAccess();
247
			Vector<ScheduledJobParamDAO> jobParamList = 
248
				jobParamAccess.getAllJobParams();
249
			
250
			for(ScheduledJobParamDAO jobParamDAO : jobParamList) {			
251
				Long jobId = jobParamDAO.getJobId();
252
				if( allJobDAOs.containsKey(jobId)) {
253
					allJobDAOs.get(jobId).addJobParam(jobParamDAO);
254
				}
255
			}
256
			
257
			return allJobDAOs;
258
			
259
		} catch (SQLException sqle) {
260
			throw new AccessException("ScheduledJobAccess.getJobByName - SQL error when getting all jobs : "  
261
					+ sqle.getMessage());
262
		} finally {
263
			try {
264
				if (pstmt != null) {
265
					pstmt.close();
266
				}
267
			} catch (SQLException sqle) {
268
				logMetacat.error("ScheduledJobAccess.getAllJobs - An error occurred " 
269
						+ "closing prepared statement: " + sqle.getMessage());
270
			} finally {
271
				DBConnectionPool.returnDBConnection(conn, serialNumber);
272
			}
273
		}	
274
				
275
	}
276
	
277
	/**
278
	 * Create a job in the database.
279
	 * 
280
	 * @param name
281
	 *            the name of the job. This should be unique
282
	 * @param triggerName
283
	 *            the name of the trigger that is registered in the scheduler
284
	 *            service
285
	 * @param groupName
286
	 *            the group of the job
287
	 * @param jobClass
288
	 *            the class that implements the job functionality. The name of
289
	 *            this class will be extracted and put into the database.
290
	 * @param startTime
291
	 *            the time when the job should first run
292
	 * @param intervalValue
293
	 *            the amount of time between job runs.
294
	 * @param intervalUnit
295
	 *            the unit of time that the intervalValue represents. Valid
296
	 *            values are s,m,h, d and w
297
	 * @param jobParams
298
	 *            a map of parameters that are associated with this job.
299
	 */
300
	public void createJob(String name, String triggerName, String groupName,
301
			Class<Job> jobClass, Calendar startTime, Calendar endTime, int intervalValue,
302
			String intervalUnit, HashMap<String, String> jobParams)
303
			throws AccessException {
304
		
305
		// Create and populate a job data object
306
		ScheduledJobDAO jobDAO = new ScheduledJobDAO();
307
		jobDAO.setStatus(StatusUtil.SCHEDULED);
308
		jobDAO.setName(name);
309
		jobDAO.setTriggerName(name);
310
		jobDAO.setGroupName(groupName);
311
		jobDAO.setClassName(jobClass.getName());
312
		jobDAO.setStartTime(new Timestamp(startTime.getTimeInMillis()));
313
		jobDAO.setEndTime(new Timestamp(endTime.getTimeInMillis()));
314
		jobDAO.setIntervalValue(intervalValue);
315
		jobDAO.setIntervalUnit(intervalUnit);
316

    
317
		createJob(jobDAO, jobParams);
318
	}
319
	
320
	/**
321
	 * Create a job in the database
322
	 * @param jobDAO the job data object that holds necessary information
323
	 * @param jobParams a map of parameters that are associated with this job.
324
	 */
325
	public void createJob(ScheduledJobDAO jobDAO, HashMap<String, String> jobParams) throws AccessException {			
326
		PreparedStatement pstmt = null;
327
		
328
		// First insert the job
329
		try {
330
			String sql = 
331
				"INSERT INTO scheduled_job (date_created, date_updated, status, name, trigger_name, group_name, class_name, start_time, end_time, interval_value, interval_unit) " 
332
				+ "VALUES(now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?)";		
333
			pstmt = conn.prepareStatement(sql);
334
		
335
			pstmt.setString(1, jobDAO.getStatus());
336
			pstmt.setString(2, jobDAO.getName());
337
			pstmt.setString(3, jobDAO.getTriggerName());
338
			pstmt.setString(4, jobDAO.getGroupName());
339
			pstmt.setString(5, jobDAO.getClassName());
340
			pstmt.setTimestamp(6, jobDAO.getStartTime());
341
			pstmt.setTimestamp(7, jobDAO.getEndTime());
342
			pstmt.setInt(8, jobDAO.getIntervalValue());
343
			pstmt.setString(9, jobDAO.getIntervalUnit());
344
			
345
			String sqlReport = "ScheduledJobAccess.createJob - SQL: " + sql 
346
				+ " [" + jobDAO.getStatus() + ","
347
				+ jobDAO.getName() + ","
348
				+ jobDAO.getTriggerName() + ","
349
				+ jobDAO.getGroupName() + ","
350
				+ jobDAO.getClassName() + ",(Timestamp)"
351
				+ jobDAO.getStartTime().toString() + ",";
352
			if(jobDAO.getEndTime() == null) {
353
				sqlReport += "null,";
354
			} else {
355
				sqlReport += jobDAO.getEndTime().toString() + ",";
356
			}
357
			sqlReport += jobDAO.getIntervalValue() + ","
358
				+ jobDAO.getIntervalUnit() + "]";
359
			logMetacat.info(sqlReport);
360
			
361
			pstmt.execute();
362
			
363
		} catch (SQLException sqle) {
364
			throw new AccessException("ScheduledJobAccess.createJob - SQL error when creating scheduled job " 
365
					+ jobDAO.getName()  + " : "  + sqle.getMessage());
366
		} finally {
367
			try {
368
				if (pstmt != null) {
369
					pstmt.close();
370
				}
371
			} catch (SQLException sqle) {
372
				logMetacat.error("ScheduledJobAccess.createJob - An error occurred " 
373
						+ "closing prepared statement: " + sqle.getMessage());
374
			} finally {
375
				DBConnectionPool.returnDBConnection(conn, serialNumber);
376
			}
377
		}	
378
		
379
		// Then iterate through the job params and insert them into the db
380
		if (jobParams.size() > 0) {
381
			ScheduledJobParamAccess scheduledJobParamsAccess = null;
382
			ScheduledJobDAO updatedJobDAO = null;
383
			try {
384
				updatedJobDAO = getJobByName(jobDAO.getName());
385
				scheduledJobParamsAccess = new ScheduledJobParamAccess();
386
				scheduledJobParamsAccess.createJobParams(updatedJobDAO.getId(), jobParams);
387
			} catch (AccessException ae) {
388
				if (updatedJobDAO != null) {
389
					updatedJobDAO.setStatus(StatusUtil.DELETED);
390
					updateJobStatus(updatedJobDAO);
391
					scheduledJobParamsAccess.deleteJobParams(updatedJobDAO.getId());
392
				} else {
393
					logMetacat.warn("ScheduledJobAccess.createJob - Tried to delete non-existant scheduled job: " 
394
							+ jobDAO.getName());
395
				}
396
			}
397
		}
398
	}
399
	
400
	/**
401
	 * Update the status of a job in the database
402
	 * 
403
	 * @param jobDAO
404
	 *            the job data object that we want to change. The status should
405
	 *            already have been updated in this object
406
	 */
407
	public void updateJobStatus(ScheduledJobDAO jobDAO) throws AccessException {	
408
		
409
		if (jobDAO == null) {
410
			throw new AccessException("ScheduledJobAccess.updateJobStatus - job DAO cannot be null.");
411
		}
412
		
413
		PreparedStatement pstmt = null;
414
		
415
		try {
416
			String sql = "UPDATE scheduled_job SET status = ? WHERE id = ?";	
417
			
418
			pstmt = conn.prepareStatement(sql);
419
			pstmt.setString(1, jobDAO.getStatus());
420
			pstmt.setLong(2, jobDAO.getId());
421
			
422
			String sqlReport = "ScheduledJobAccess.deleteJob - SQL: " + sql
423
				+  " [" + jobDAO.getStatus() + "," + jobDAO.getId() + "]";
424
			logMetacat.info(sqlReport);
425

    
426
			pstmt.execute();
427
		} catch (SQLException sqle) {
428
			throw new AccessException("ScheduledJobAccess.deleteJob - SQL error when " 
429
					+ "deleting scheduled job " + jobDAO.getName()  + " : "  + sqle.getMessage());
430
		} finally {
431
			try {
432
				if (pstmt != null) {
433
					pstmt.close();
434
				}
435
			} catch (SQLException sqle) {
436
				logMetacat.error("ScheduledJobAccess.updateJobStatus - An error occurred " 
437
						+ "closing prepared statement: " + sqle.getMessage());
438
			} finally {
439
				DBConnectionPool.returnDBConnection(conn, serialNumber);
440
			}
441
		}		
442
		
443
	}
444
	
445
	/**
446
	 * Populate a job data object with the current row in a resultset
447
	 * 
448
	 * @param resultSet
449
	 *            the result set which is already pointing to the desired row.
450
	 * @return a scheduled job data object
451
	 */
452
	protected ScheduledJobDAO populateDAO(ResultSet resultSet) throws SQLException {
453

    
454
		ScheduledJobDAO jobDAO = new ScheduledJobDAO();
455
		jobDAO.setId(resultSet.getLong("id"));
456
		jobDAO.setCreateTime(resultSet.getTimestamp("date_created"));
457
		jobDAO.setModTime(resultSet.getTimestamp("date_updated"));
458
		jobDAO.setStatus(resultSet.getString("status"));
459
		jobDAO.setName(resultSet.getString("name"));
460
		jobDAO.setTriggerName(resultSet.getString("trigger_name"));
461
		jobDAO.setGroupName(resultSet.getString("group_name"));
462
		jobDAO.setClassName(resultSet.getString("class_name"));
463
		jobDAO.setStartTime(resultSet.getTimestamp("start_time"));
464
		jobDAO.setEndTime(resultSet.getTimestamp("end_time"));
465
		jobDAO.setIntervalValue(resultSet.getInt("interval_value"));
466
		jobDAO.setIntervalUnit(resultSet.getString("interval_unit"));
467

    
468
		return jobDAO;
469
	}
470
	
471
}
(3-3/7)