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

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

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

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

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

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

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

    
445
		ScheduledJobDAO jobDAO = new ScheduledJobDAO();
446
		jobDAO.setId(resultSet.getLong("id"));
447
		jobDAO.setCreateTime(resultSet.getTimestamp("date_created"));
448
		jobDAO.setModTime(resultSet.getTimestamp("date_updated"));
449
		jobDAO.setStatus(resultSet.getString("status"));
450
		jobDAO.setName(resultSet.getString("name"));
451
		jobDAO.setTriggerName(resultSet.getString("trigger_name"));
452
		jobDAO.setGroupName(resultSet.getString("group_name"));
453
		jobDAO.setClassName(resultSet.getString("class_name"));
454
		jobDAO.setStartTime(resultSet.getTimestamp("start_time"));
455
		jobDAO.setEndTime(resultSet.getTimestamp("end_time"));
456
		jobDAO.setIntervalValue(resultSet.getInt("interval_value"));
457
		jobDAO.setIntervalUnit(resultSet.getString("interval_unit"));
458

    
459
		return jobDAO;
460
	}
461
	
462
}
(3-3/7)