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

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

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

    
435
		ScheduledJobDAO jobDAO = new ScheduledJobDAO();
436
		jobDAO.setId(resultSet.getLong("id"));
437
		jobDAO.setCreateTime(resultSet.getTimestamp("date_created"));
438
		jobDAO.setModTime(resultSet.getTimestamp("date_updated"));
439
		jobDAO.setStatus(resultSet.getString("status"));
440
		jobDAO.setName(resultSet.getString("name"));
441
		jobDAO.setTriggerName(resultSet.getString("trigger_name"));
442
		jobDAO.setGroupName(resultSet.getString("group_name"));
443
		jobDAO.setClassName(resultSet.getString("class_name"));
444
		jobDAO.setStartTime(resultSet.getTimestamp("start_time"));
445
		jobDAO.setIntervalValue(resultSet.getInt("interval_value"));
446
		jobDAO.setIntervalUnit(resultSet.getString("interval_unit"));
447

    
448
		return jobDAO;
449
	}
450
	
451
}
(3-3/7)