1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.batch.admin.integration;
17
18 import org.springframework.batch.admin.web.LaunchRequest;
19 import org.springframework.batch.core.BatchStatus;
20 import org.springframework.batch.core.Job;
21 import org.springframework.batch.core.JobExecution;
22 import org.springframework.batch.core.JobInstance;
23 import org.springframework.batch.core.JobParameters;
24 import org.springframework.batch.core.configuration.JobLocator;
25 import org.springframework.batch.core.explore.JobExplorer;
26 import org.springframework.batch.core.launch.JobParametersNotFoundException;
27 import org.springframework.batch.core.launch.NoSuchJobException;
28 import org.springframework.batch.integration.launch.JobLaunchRequest;
29 import org.springframework.integration.annotation.MessageEndpoint;
30 import org.springframework.integration.annotation.ServiceActivator;
31
32 import java.util.List;
33
34
35
36
37
38
39
40
41
42
43 @MessageEndpoint
44 public class JobNameToJobRestartRequestAdapter {
45
46 private JobLocator jobLocator;
47
48 private JobExplorer jobExplorer;
49
50 public void setJobLocator(JobLocator jobLocator) {
51 this.jobLocator = jobLocator;
52 }
53
54 public void setJobExplorer(JobExplorer jobExplorer) {
55 this.jobExplorer = jobExplorer;
56 }
57
58 @ServiceActivator
59 public JobLaunchRequest adapt(String jobName) throws NoSuchJobException,
60 JobParametersNotFoundException {
61 jobName = jobName.trim();
62 Job job = jobLocator.getJob(jobName);
63 JobParameters jobParameters = getLastFailedJobParameters(jobName);
64 return new JobLaunchRequest(job, jobParameters);
65 }
66
67
68
69
70
71
72 private JobParameters getLastFailedJobParameters(String jobName)
73 throws JobParametersNotFoundException {
74
75 int start = 0;
76 int count = 100;
77 List<JobInstance> lastInstances = jobExplorer.getJobInstances(jobName,
78 start, count);
79
80 JobParameters jobParameters = null;
81
82 if (lastInstances.isEmpty()) {
83 throw new JobParametersNotFoundException(
84 "No job instance found for job=" + jobName);
85 }
86
87 while (!lastInstances.isEmpty()) {
88
89 for (JobInstance jobInstance : lastInstances) {
90 List<JobExecution> jobExecutions = jobExplorer
91 .getJobExecutions(jobInstance);
92 if (jobExecutions == null || jobExecutions.isEmpty()) {
93 continue;
94 }
95 JobExecution jobExecution = jobExecutions.get(jobExecutions
96 .size() - 1);
97 if (jobExecution.getStatus()
98 .isGreaterThan(BatchStatus.STOPPING)) {
99 jobParameters = jobExecution.getJobParameters();
100 break;
101 }
102 }
103
104 if (jobParameters != null) {
105 break;
106 }
107
108 start += count;
109 lastInstances = jobExplorer.getJobInstances(jobName, start, count);
110
111 }
112
113 if (jobParameters == null) {
114 throw new JobParametersNotFoundException(
115 "No failed or stopped execution found for job=" + jobName);
116 }
117 return jobParameters;
118
119 }
120
121 }