1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.batch.sample.quartz;
17
18 import java.util.Date;
19 import java.util.Map;
20 import java.util.Map.Entry;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.quartz.JobExecutionContext;
25 import org.springframework.batch.core.JobExecutionException;
26 import org.springframework.batch.core.JobParameters;
27 import org.springframework.batch.core.JobParametersBuilder;
28 import org.springframework.batch.core.configuration.JobLocator;
29 import org.springframework.batch.core.launch.JobLauncher;
30 import org.springframework.scheduling.quartz.QuartzJobBean;
31
32
33
34
35
36 public class JobLauncherDetails extends QuartzJobBean {
37
38
39
40
41 static final String JOB_NAME = "jobName";
42
43 private static Log log = LogFactory.getLog(JobLauncherDetails.class);
44
45 private JobLocator jobLocator;
46
47 private JobLauncher jobLauncher;
48
49
50
51
52
53 public void setJobLocator(JobLocator jobLocator) {
54 this.jobLocator = jobLocator;
55 }
56
57
58
59
60
61 public void setJobLauncher(JobLauncher jobLauncher) {
62 this.jobLauncher = jobLauncher;
63 }
64
65 @SuppressWarnings("unchecked")
66 protected void executeInternal(JobExecutionContext context) {
67 Map<String, Object> jobDataMap = context.getMergedJobDataMap();
68 String jobName = (String) jobDataMap.get(JOB_NAME);
69 log.info("Quartz trigger firing with Spring Batch jobName="+jobName);
70 JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);
71 try {
72 jobLauncher.run(jobLocator.getJob(jobName), jobParameters);
73 }
74 catch (JobExecutionException e) {
75 log.error("Could not execute job.", e);
76 }
77 }
78
79
80
81
82
83
84
85 private JobParameters getJobParametersFromJobMap(Map<String, Object> jobDataMap) {
86
87 JobParametersBuilder builder = new JobParametersBuilder();
88
89 for (Entry<String, Object> entry : jobDataMap.entrySet()) {
90 String key = entry.getKey();
91 Object value = entry.getValue();
92 if (value instanceof String && !key.equals(JOB_NAME)) {
93 builder.addString(key, (String) value);
94 }
95 else if (value instanceof Float || value instanceof Double) {
96 builder.addDouble(key, ((Number) value).doubleValue());
97 }
98 else if (value instanceof Integer || value instanceof Long) {
99 builder.addLong(key, ((Number)value).longValue());
100 }
101 else if (value instanceof Date) {
102 builder.addDate(key, (Date) value);
103 }
104 else {
105 log.debug("JobDataMap contains values which are not job parameters (ignoring).");
106 }
107 }
108
109 return builder.toJobParameters();
110
111 }
112
113 }