PageRenderTime 112ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/wct-1.5.2/WCTCore/src-app/org/webcurator/ui/common/validation/ValidatorUtil.java

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