01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.scheduling.quartz;
18:
19: import org.quartz.Job;
20: import org.quartz.SchedulerException;
21: import org.quartz.spi.JobFactory;
22: import org.quartz.spi.TriggerFiredBundle;
23:
24: /**
25: * JobFactory implementation that supports {@link java.lang.Runnable}
26: * objects as well as standard Quartz {@link org.quartz.Job} instances.
27: *
28: * @author Juergen Hoeller
29: * @since 2.0
30: * @see DelegatingJob
31: * @see #adaptJob(Object)
32: */
33: public class AdaptableJobFactory implements JobFactory {
34:
35: public Job newJob(TriggerFiredBundle bundle)
36: throws SchedulerException {
37: try {
38: Object jobObject = createJobInstance(bundle);
39: return adaptJob(jobObject);
40: } catch (Exception ex) {
41: throw new SchedulerException("Job instantiation failed", ex);
42: }
43: }
44:
45: /**
46: * Create an instance of the specified job class.
47: * <p>Can be overridden to post-process the job instance.
48: * @param bundle the TriggerFiredBundle from which the JobDetail
49: * and other info relating to the trigger firing can be obtained
50: * @return the job instance
51: * @throws Exception if job instantiation failed
52: */
53: protected Object createJobInstance(TriggerFiredBundle bundle)
54: throws Exception {
55: return bundle.getJobDetail().getJobClass().newInstance();
56: }
57:
58: /**
59: * Adapt the given job object to the Quartz Job interface.
60: * <p>The default implementation supports straight Quartz Jobs
61: * as well as Runnables, which get wrapped in a DelegatingJob.
62: * @param jobObject the original instance of the specified job class
63: * @return the adapted Quartz Job instance
64: * @throws Exception if the given job could not be adapted
65: * @see DelegatingJob
66: */
67: protected Job adaptJob(Object jobObject) throws Exception {
68: if (jobObject instanceof Job) {
69: return (Job) jobObject;
70: } else if (jobObject instanceof Runnable) {
71: return new DelegatingJob((Runnable) jobObject);
72: } else {
73: throw new IllegalArgumentException(
74: "Unable to execute job class ["
75: + jobObject.getClass().getName()
76: + "]: only [org.quartz.Job] and [java.lang.Runnable] supported.");
77: }
78: }
79:
80: }
|