View Javadoc

1   /**
2    * 
3    */
4   package org.mod4j.runtime.validation;
5   
6   import java.net.BindException;
7   import java.util.LinkedList;
8   import java.util.List;
9   
10  import org.mod4j.runtime.exception.BusinessRuleException;
11  import org.springframework.validation.Validator;
12  
13  /**
14   * @author Eric Jan Malotaux
15   */
16  public class BusinessRuleValidationSupport {
17      
18      private boolean active = true;
19      
20      public boolean isActive() {
21          return this.active;
22      }
23  
24      public void setActive(boolean active) {
25          this.active = active;
26      }
27  
28      /**
29       * 
30       */
31      public BusinessRuleValidationSupport(Object object) {
32          this.validationTemplate = new BusinessRuleValidationTemplate(object);
33      }
34  
35      protected List<Validator> validators = new LinkedList<Validator>();
36  
37      protected final BusinessRuleValidationTemplate validationTemplate;
38  
39      /**
40       * Add the given <code>validator</code> to the collection of validators that will be executed on this object when
41       * the {@link #validate()} method is called. The validators will be invoked in the order they were added.
42       * 
43       * @param validator -
44       *            the validator being added.
45       */
46      public void addValidator(Validator validator) {
47          if (!validators.contains(validator)) {
48              validators.add(validator);
49          }
50      }
51  
52      /**
53       * Validate this object.
54       * 
55       * If active, validation is performed by calling every {@link Validator} added by the {@link #addValidator(Validator)} method,
56       * in the order they were added.
57       * 
58       * @throws BusinessRuleException -
59       *             thrown when one or more errors are found. The exception thrown has as its cause a
60       *             {@link BindException} containing information on all errors found.
61       */
62      public void validate() throws BusinessRuleException {
63          
64          if (isActive()) {
65              validationTemplate.invokeValidators(validators);    
66          }
67      }
68  }