1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.batch.core.job;
17
18 import java.util.Arrays;
19 import java.util.Collection;
20 import java.util.HashSet;
21 import java.util.Set;
22
23 import org.springframework.batch.core.JobParameters;
24 import org.springframework.batch.core.JobParametersInvalidException;
25 import org.springframework.batch.core.JobParametersValidator;
26 import org.springframework.beans.factory.InitializingBean;
27 import org.springframework.util.Assert;
28
29
30
31
32
33
34
35 public class DefaultJobParametersValidator implements JobParametersValidator, InitializingBean {
36
37 private Collection<String> requiredKeys;
38
39 private Collection<String> optionalKeys;
40
41
42
43
44 public DefaultJobParametersValidator() {
45 this(new String[0], new String[0]);
46 }
47
48
49
50
51
52
53
54
55
56
57
58 public DefaultJobParametersValidator(String[] requiredKeys, String[] optionalKeys) {
59 super();
60 setRequiredKeys(requiredKeys);
61 setOptionalKeys(optionalKeys);
62 }
63
64
65
66
67
68 @Override
69 public void afterPropertiesSet() throws IllegalStateException {
70 for (String key : requiredKeys) {
71 Assert.state(!optionalKeys.contains(key), "Optional keys canot be required: " + key);
72 }
73 }
74
75
76
77
78
79
80
81
82
83
84
85 @Override
86 public void validate(JobParameters parameters) throws JobParametersInvalidException {
87
88 if (parameters == null) {
89 throw new JobParametersInvalidException("The JobParameters can not be null");
90 }
91
92 Set<String> keys = parameters.getParameters().keySet();
93
94
95
96 if (!optionalKeys.isEmpty()) {
97
98 Collection<String> missingKeys = new HashSet<String>();
99 for (String key : keys) {
100 if (!optionalKeys.contains(key) && !requiredKeys.contains(key)) {
101 missingKeys.add(key);
102 }
103 }
104 if (!missingKeys.isEmpty()) {
105 throw new JobParametersInvalidException(
106 "The JobParameters contains keys that are not explicitly optional or required: " + missingKeys);
107 }
108
109 }
110
111 Collection<String> missingKeys = new HashSet<String>();
112 for (String key : requiredKeys) {
113 if (!keys.contains(key)) {
114 missingKeys.add(key);
115 }
116 }
117 if (!missingKeys.isEmpty()) {
118 throw new JobParametersInvalidException("The JobParameters do not contain required keys: " + missingKeys);
119 }
120
121 }
122
123
124
125
126
127
128
129
130
131
132 public final void setRequiredKeys(String[] requiredKeys) {
133 this.requiredKeys = new HashSet<String>(Arrays.asList(requiredKeys));
134 }
135
136
137
138
139
140
141
142
143
144
145
146 public final void setOptionalKeys(String[] optionalKeys) {
147 this.optionalKeys = new HashSet<String>(Arrays.asList(optionalKeys));
148 }
149
150 }