/projects/wct-1.5.2/WCTCore/src-app/org/webcurator/ui/common/validation/ValidatorUtil.java
Java | 418 lines | 221 code | 42 blank | 155 comment | 83 complexity | 36bff481e173c2157a9b7bd50f3bc2ef MD5 | raw file
1/*
2 * Copyright 2006 The National Library of New Zealand
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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 */
16package org.webcurator.ui.common.validation;
17
18import java.text.DateFormat;
19import java.text.ParseException;
20import java.text.SimpleDateFormat;
21import java.util.Date;
22import java.util.HashMap;
23import java.util.Iterator;
24import java.util.List;
25
26import org.webcurator.core.permissionmapping.UrlUtils;
27import org.apache.commons.logging.LogFactory;
28import org.apache.oro.text.regex.MalformedPatternException;
29import org.apache.oro.text.regex.Perl5Compiler;
30import org.apache.oro.text.regex.Perl5Matcher;
31import org.apache.oro.text.regex.Perl5Pattern;
32import org.springframework.context.ApplicationContext;
33import org.springframework.validation.Errors;
34import org.webcurator.core.common.Constants;
35import org.webcurator.core.harvester.coordinator.HarvestCoordinator;
36import org.webcurator.core.scheduler.TargetInstanceManager;
37import org.webcurator.core.targets.TargetManager;
38import org.webcurator.core.util.ApplicationContextFactory;
39import org.webcurator.domain.HarvestCoordinatorDAO;
40import org.webcurator.domain.model.core.BandwidthRestriction;
41import org.webcurator.domain.model.core.TargetInstance;
42import org.webcurator.ui.agent.command.BandwidthRestrictionsCommand;
43
44/**
45 * Utility class providing useful validation methods.
46 * @author nwaight
47 */
48public final class ValidatorUtil {
49
50 public final static String EMAIL_VALIDATION_REGEX =
51 "^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,4})$";
52
53
54 /**
55 * Helper function to validate that a number is greater than the
56 * low limit value.
57 * @param aErrors the errors object to populate
58 * @param aNumber the number to check
59 * @param aLowLimit the low limit
60 * @param aErrorCode the error code to use
61 * @param aValues the values to set in the error message
62 * @param aFailureMessage the default error message
63 */
64 public static void validateMinNumber(Errors aErrors, Number aNumber, Number aLowLimit, String aErrorCode, Object[] aValues, String aFailureMessage) {
65 if (aNumber != null) {
66 if (aNumber.doubleValue() <= aLowLimit.doubleValue()) {
67 aErrors.reject(aErrorCode, aValues, aFailureMessage);
68 }
69 }
70 }
71
72 /**
73 * Helper function to validate the length of a string input field.
74 * @param aErrors the errors object to populate
75 * @param aField the field to check the length of
76 * @param aMaxLength the length to check against
77 * @param aErrorCode the code for the message resource value
78 * @param aValues the list of values to replace in the i8n messages
79 * @param aFailureMessage the default failure message
80 */
81 public static void validateStringMaxLength(Errors aErrors, String aField, int aMaxLength, String aErrorCode, Object[] aValues, String aFailureMessage) {
82 if (aField != null && !aField.trim().equals("")) {
83 if (aField.length() > aMaxLength) {
84 aErrors.reject(aErrorCode, aValues, aFailureMessage);
85 }
86 }
87 }
88
89 /**
90 * Helper function to validate the length of a string input field.
91 * @param aErrors the errors object to populate
92 * @param aField the field to check the length of
93 * @param aMinLength the length to check against
94 * @param aErrorCode the code for the message resource value
95 * @param aValues the list of values to replace in the i8n messages
96 * @param aFailureMessage the default failure message
97 */
98 public static void validateStringMinLength(Errors aErrors, String aField, int aMinLength, String aErrorCode, Object[] aValues, String aFailureMessage) {
99 if (aField != null && !aField.trim().equals("")) {
100 if (aField.length() < aMinLength) {
101 aErrors.reject(aErrorCode, aValues, aFailureMessage);
102 }
103 }
104 }
105
106 /**
107 * Helper method used to check two string values match.
108 * @param aErrors the errors object to populate
109 * @param val1 String value 1
110 * @param val2 String value 2
111 * @param aErrorCode the error code
112 * @param aValues the values
113 * @param aFailureMessage the default message
114 */
115 public static void validateValueMatch(Errors aErrors, String val1, String val2, String aErrorCode, Object[] aValues, String aFailureMessage) {
116 if (val1 != null && val2 != null) {
117 if (val1.equals(val2) == true) {
118 return;
119 }
120 }
121
122 aErrors.reject(aErrorCode, aValues, aFailureMessage);
123 }
124
125 /**
126 * Helper method used to check two string values are different.
127 * @param aErrors the errors object to populate
128 * @param val1 String value 1
129 * @param val2 String value 2
130 * @param aErrorCode the error code
131 * @param aValues the values
132 * @param aFailureMessage the default message
133 */
134 public static void validateValuesDifferent(Errors aErrors, String val1, String val2, String aErrorCode, Object[] aValues, String aFailureMessage) {
135 if (val1 != null && val2 != null) {
136 if (val1.equals(val2) == false) {
137 return;
138 }
139 }
140
141 aErrors.reject(aErrorCode, aValues, aFailureMessage);
142 }
143
144 /**
145 * Helper method to validated that a start time is before and
146 * not the same as an end time.
147 * @param aErrors the errors object to populate
148 * @param aStart the start time
149 * @param aEnd the end time
150 * @param aErrorCode the error code
151 * @param aValues the values to set in the error message
152 * @param aFailureMessage the default failure message
153 */
154 public static void validateStartBeforeEndTime(Errors aErrors, Date aStart, Date aEnd, String aErrorCode, Object[] aValues, String aFailureMessage) {
155 if (aStart != null && aEnd != null) {
156 if (aStart.after(aEnd)) {
157 aErrors.reject(aErrorCode, aValues, aFailureMessage);
158 }
159
160 if (aStart.equals(aEnd)) {
161 aErrors.reject(aErrorCode, aValues, aFailureMessage);
162 }
163 }
164 }
165
166 /**
167 * Helper method to validated that a start time is before or equal to the
168 * end time.
169 * @param aErrors the errors object to populate
170 * @param aStart the start time
171 * @param aEnd the end time
172 * @param aErrorCode the error code
173 * @param aValues the values to set in the error message
174 * @param aFailureMessage the default failure message
175 */
176 public static void validateStartBeforeOrEqualEndTime(Errors aErrors, Date aStart, Date aEnd, String aErrorCode, Object[] aValues, String aFailureMessage) {
177 if (aStart != null && aEnd != null) {
178 if (aStart.after(aEnd)) {
179 aErrors.reject(aErrorCode, aValues, aFailureMessage);
180 }
181 }
182 }
183
184 /**
185 * Helper method to validated that a start time is before and
186 * not the same as an end time for a specified bandwidth restriction.
187 * @param aErrors the errors object to populate
188 * @param aCmd the bandwidth restriction command
189 * @param aErrorCode the error code
190 * @param aValues the values to set in the error message
191 * @param aFailureMessage the default failure message
192 */
193 public static void validateNoBandwidthPeriodOverlaps(Errors aErrors, BandwidthRestrictionsCommand aCmd, String aErrorCode, Object[] aValues, String aFailureMessage) {
194 if (aCmd != null && aCmd.getStart() != null && aCmd.getEnd() != null && aCmd.getDay() != null) {
195 ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
196 HarvestCoordinatorDAO hcDao = (HarvestCoordinatorDAO) context.getBean(Constants.BEAN_HARVEST_COORDINATOR_DAO);
197 HashMap<String, List<BandwidthRestriction>> allRestrictions = hcDao.getBandwidthRestrictions();
198 List restrictions = allRestrictions.get(aCmd.getDay());
199 if (restrictions != null && !restrictions.isEmpty()) {
200 BandwidthRestriction newBr = new BandwidthRestriction();
201 newBr.setStartTime(aCmd.getStart());
202 newBr.setEndTime(aCmd.getEnd());
203
204 BandwidthRestriction element = null;
205 Iterator it = restrictions.iterator();
206 while (it.hasNext()) {
207 element = (BandwidthRestriction) it.next();
208 if (aCmd.getOid() == null || !aCmd.getOid().equals(element.getOid())) {
209 if (newBr.getStartTime().after(element.getStartTime()) && newBr.getStartTime().before(element.getEndTime())) {
210 aErrors.reject(aErrorCode, aValues, aFailureMessage);
211 return;
212 }
213
214 if (newBr.getEndTime().after(element.getStartTime()) && newBr.getEndTime().before(element.getEndTime())) {
215 aErrors.reject(aErrorCode, aValues, aFailureMessage);
216 return;
217 }
218
219 if (newBr.getStartTime().equals(element.getStartTime()) || newBr.getStartTime().equals(element.getEndTime())) {
220 aErrors.reject(aErrorCode, aValues, aFailureMessage);
221 return;
222 }
223
224 if (newBr.getEndTime().equals(element.getStartTime()) && newBr.getEndTime().equals(element.getEndTime())) {
225 aErrors.reject(aErrorCode, aValues, aFailureMessage);
226 return;
227 }
228 }
229 }
230 }
231 }
232 }
233
234 public static void validateIsDate(Errors errors, String aDate, String aDateFormat, String aErrorCode, Object[] aValues, String aDefaultMessage) {
235 DateFormat simpleDateFormat = new SimpleDateFormat(aDateFormat);
236 try {
237 simpleDateFormat.parse(aDate);
238 }
239 catch (ParseException e) {
240 errors.reject(aErrorCode, aValues, aDefaultMessage);
241 }
242 }
243
244 /**
245 * Helper method to check to see if adding the new target instance will mean that
246 * this or any other running harvest has a bandwidth setting below the minimum
247 * @param aErrors the errors object to populate
248 * @param aTargetInstanceOid the target instance id to check
249 * @param aErrorCode the error code for a vaildation failure
250 * @param aValues the values to set for a failure
251 * @param aFailureMessage the default failure message
252 */
253 public static void validateMinimumBandwidthAvailable(Errors aErrors, Long aTargetInstanceOid, String aErrorCode, Object[] aValues, String aFailureMessage) {
254 if (aTargetInstanceOid != null) {
255 ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
256 TargetInstanceManager targetInstanceManager = (TargetInstanceManager) context.getBean(Constants.BEAN_TARGET_INSTANCE_MNGR);
257 HarvestCoordinator harvestCoordinator = (HarvestCoordinator) context.getBean(Constants.BEAN_HARVEST_COORDINATOR);
258
259 TargetInstance ti = targetInstanceManager.getTargetInstance(aTargetInstanceOid);
260 if (!harvestCoordinator.isMiniumBandwidthAvailable(ti)) {
261 // failure bandwidth setting is too low.
262 aErrors.reject(aErrorCode, aValues, aFailureMessage);
263 }
264 }
265 }
266
267 /**
268 * Helper method to check to see if the bandwidth percentage setting is
269 * less than or equal to the maximum
270 * @param aErrors the errors object to populate
271 * @param aErrorCode the error code for a vaildation failure
272 * @param aPercentage the percentage to check.
273 */
274 public static void validateMaxBandwidthPercentage(Errors aErrors, int aPercentage, String aErrorCode) {
275 ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
276 HarvestCoordinator harvestCoordinator = (HarvestCoordinator) context.getBean(Constants.BEAN_HARVEST_COORDINATOR);
277
278 if (aPercentage > harvestCoordinator.getMaxBandwidthPercent()) {
279 // failure bandwidth percentage setting is too high.
280 Object[] vals = new Object[1];
281 vals[0] = harvestCoordinator.getMaxBandwidthPercent();
282 aErrors.reject(aErrorCode, vals, "max bandwidth percentage exeeded");
283 }
284 }
285
286 /**
287 * Helper method to check to see if the Target of a target instance is approved for harvest.
288 * @param aErrors the errors object to populate
289 * @param aTargetInstanceOid the target instance to check
290 * @param aErrorCode the error code for a vaildation failure
291 */
292 public static void validateTargetApproved(Errors aErrors, Long aTargetInstanceOid, String aErrorCode) {
293 ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
294 TargetInstanceManager tiManager = (TargetInstanceManager) context.getBean(Constants.BEAN_TARGET_INSTANCE_MNGR);
295 TargetManager targetManager = (TargetManager) context.getBean(Constants.BEAN_TARGET_MNGR);
296
297 TargetInstance ti = tiManager.getTargetInstance(aTargetInstanceOid);
298 if (!targetManager.isTargetHarvestable(ti)) {
299 // failure target is not approved to be harvested.
300 Object[] vals = new Object[1];
301 vals[0] = ti.getTarget().getOid().toString();
302 aErrors.reject(aErrorCode, vals, "target instance is not approved for harvest");
303 }
304 }
305
306 /**
307 * Helper method to validate the specified string does not contain anything other than
308 * that specified by the regular expression
309 * @param aErrors The errors object to populate
310 * @param aValue the string to check
311 * @param aRegEx the Perl based regular expression to check the value against
312 * @param aErrorCode the error code for getting the i8n failure message
313 * @param aValues the list of values to replace in the i8n messages
314 * @param aFailureMessage the default error message
315 */
316 public static void validateRegEx(Errors aErrors, String aValue, String aRegEx, String aErrorCode, Object[] aValues, String aFailureMessage) {
317 if (aValue != null && aRegEx != null && !aRegEx.equals("") && !aValue.trim().equals("")) {
318 Perl5Compiler ptrnCompiler = new Perl5Compiler();
319 Perl5Matcher matcher = new Perl5Matcher();
320 try {
321 Perl5Pattern aCharPattern = (Perl5Pattern) ptrnCompiler.compile(aRegEx);
322
323 if (!matcher.contains(aValue, aCharPattern)) {
324 aErrors.reject(aErrorCode, aValues, aFailureMessage);
325 return;
326 }
327 }
328 catch (MalformedPatternException e) {
329 LogFactory.getLog(ValidatorUtil.class).fatal("Perl pattern malformed: pattern used was "+aRegEx +" : "+ e.getMessage(), e);
330 }
331 }
332 }
333
334 /**
335 * Helper method to validate a supplied URL is correctly formatted
336 * @param aErrors The errors object to populate
337 * @param aURL The URL to check
338 * @param aErrorCode the error code for getting the i8n failure message
339 * @param aValues the list of values to replace in the i8n messages
340 * @param aFailureMessage the default error message
341 */
342 public static void validateURL(Errors aErrors, String aURL, String aErrorCode, Object[] aValues, String aFailureMessage) {
343 if(!UrlUtils.isUrl(aURL)) {
344 aErrors.reject(aErrorCode, aValues, aFailureMessage);
345 }
346 }
347
348 /**
349 * Helper method to validate a new password for a user id.
350 * @param aErrors The errors object to populate
351 * @param aNewPwd the new password for the user id
352 * @param aErrorCode the error code
353 * @param aValues the values
354 * @param aFailureMessage the default message
355 */
356 public static void validateNewPassword(Errors aErrors, String aNewPwd, String aErrorCode, Object[] aValues, String aFailureMessage) {
357 if (aNewPwd != null && !aNewPwd.trim().equals("")) {
358 Perl5Compiler ptrnCompiler = new Perl5Compiler();
359 Perl5Matcher matcher = new Perl5Matcher();
360 try {
361 Perl5Pattern lcCharPattern = (Perl5Pattern) ptrnCompiler.compile("[a-z]");
362 Perl5Pattern ucCharPattern = (Perl5Pattern) ptrnCompiler.compile("[A-Z]");
363 Perl5Pattern numericPattern = (Perl5Pattern) ptrnCompiler.compile("[0-9]");
364
365 if (aNewPwd.length() < 6) {
366 aErrors.reject(aErrorCode, aValues, aFailureMessage);
367 return;
368 }
369
370 if (!matcher.contains(aNewPwd, lcCharPattern)) {
371 aErrors.reject(aErrorCode, aValues, aFailureMessage);
372 return;
373 }
374
375 if (!matcher.contains(aNewPwd, ucCharPattern)) {
376 aErrors.reject(aErrorCode, aValues, aFailureMessage);
377 return;
378 }
379
380 if (!matcher.contains(aNewPwd, numericPattern)) {
381 aErrors.reject(aErrorCode, aValues, aFailureMessage);
382 return;
383 }
384
385 }
386 catch (MalformedPatternException e) {
387 LogFactory.getLog(ValidatorUtil.class).fatal("Perl patterns malformed: " + e.getMessage(), e);
388 }
389 }
390 }
391
392 /**
393 * Helper method used to check string value 1 does not contain value 2.
394 * @param aErrors the errors object to populate
395 * @param val1 String value 1
396 * @param val2 String value 2
397 * @param aErrorCode the error code
398 * @param aValues the values
399 * @param aFailureMessage the default message
400 */
401 public static void validateValueNotContained(Errors aErrors, String val1, String val2, String aErrorCode, Object[] aValues, String aFailureMessage) {
402 if (val1 != null && val2 != null) {
403 if (val1.contains(val2) == false) {
404 return;
405 }
406 }
407
408 aErrors.reject(aErrorCode, aValues, aFailureMessage);
409 }
410
411 /** private constructor. */
412 private ValidatorUtil() {
413 super();
414 }
415
416
417
418}