commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tur...@apache.org
Subject cvs commit: jakarta-commons/validator/src/test/org/apache/commons/validator MultipleTests.java validator-multipletest.xml ValidatorTestSuite.java
Date Tue, 24 Sep 2002 20:23:37 GMT
turner      2002/09/24 13:23:35

  Modified:    validator/src/share/org/apache/commons/validator
                        Validator.java
               validator/src/test/org/apache/commons/validator
                        ValidatorTestSuite.java
  Added:       validator/src/test/org/apache/commons/validator
                        MultipleTests.java validator-multipletest.xml
  Log:
  Refactors Validator.java to split one big method (validate) into a number of methods, have it iterate over fields rather than iterate over actions, stop on the first error for each field rather than skip processing a field if a depended action fails for any field.  Also added unit tests for multiple action fields.
  
  Revision  Changes    Path
  1.9       +295 -375  jakarta-commons/validator/src/share/org/apache/commons/validator/Validator.java
  
  Index: Validator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/share/org/apache/commons/validator/Validator.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- Validator.java	19 Sep 2002 17:11:46 -0000	1.8
  +++ Validator.java	24 Sep 2002 20:23:35 -0000	1.9
  @@ -81,9 +81,9 @@
   
   
   /**
  - * <p>Validations are processed by the validate method.  
  - * An instance of <code>ValidatorResources</code> is 
  - * used to define the validators (validation methods) 
  + * <p>Validations are processed by the validate method.
  + * An instance of <code>ValidatorResources</code> is
  + * used to define the validators (validation methods)
    * and the validation rules for a JavaBean.</p>
    *
    * @author David Winterfeldt
  @@ -103,40 +103,40 @@
      public static String BEAN_KEY = "java.lang.Object";
   
      /**
  -    * Resources key the <code>ValidatorAction</code> is stored under.  
  -    * This will be automatically passed into a validation method 
  -    * with the current <code>ValidatorAction</code> if it is 
  +    * Resources key the <code>ValidatorAction</code> is stored under.
  +    * This will be automatically passed into a validation method
  +    * with the current <code>ValidatorAction</code> if it is
       * specified in the method signature.
      */
      public static String VALIDATOR_ACTION_KEY = "org.apache.commons.validator.ValidatorAction";
   
      /**
  -    * Resources key the <code>Field</code> is stored under.  
  -    * This will be automatically passed into a validation method 
  -    * with the current <code>Field</code> if it is 
  +    * Resources key the <code>Field</code> is stored under.
  +    * This will be automatically passed into a validation method
  +    * with the current <code>Field</code> if it is
       * specified in the method signature.
      */
      public static String FIELD_KEY = "org.apache.commons.validator.Field";
   
      /**
  -    * Resources key the <code>Validator</code> is stored under.  
  -    * This will be automatically passed into a validation method 
  -    * with the current <code>Validator</code> if it is 
  +    * Resources key the <code>Validator</code> is stored under.
  +    * This will be automatically passed into a validation method
  +    * with the current <code>Validator</code> if it is
       * specified in the method signature.
      */
      public static String VALIDATOR_KEY = "org.apache.commons.validator.Validator";
      /**
       * Resources key the <code>Locale</code> is stored.
  -    * This will be used to retrieve the appropriate 
  -    * <code>FormSet</code> and <code>Form</code> to be 
  +    * This will be used to retrieve the appropriate
  +    * <code>FormSet</code> and <code>Form</code> to be
       * processed.
      */
      public static String LOCALE_KEY = "java.util.Locale";
  -   
  +
      protected ValidatorResources resources = null;
      protected String formName = null;
      protected HashMap hResources = new HashMap();
  -   protected int page = 0;   
  +   protected int page = 0;
   
      /**
       * The class loader to use for instantiating application objects.
  @@ -153,12 +153,12 @@
      protected boolean useContextClassLoader = false;
   
      /**
  -    * Construct a <code>Validator</code> that will 
  -    * use the <code>ValidatorResources</code> 
  -    * passed in to retrieve pluggable validators 
  +    * Construct a <code>Validator</code> that will
  +    * use the <code>ValidatorResources</code>
  +    * passed in to retrieve pluggable validators
       * the different sets of validation rules.
       *
  -    * @param	resources	<code>ValidatorResources</code> 
  +    * @param	resources	<code>ValidatorResources</code>
       *				to use during validation.
      */
      public Validator(ValidatorResources resources) {
  @@ -166,30 +166,30 @@
      }
   
      /**
  -    * Construct a <code>Validator</code> that will 
  -    * use the <code>ValidatorResources</code> 
  -    * passed in to retrieve pluggable validators 
  +    * Construct a <code>Validator</code> that will
  +    * use the <code>ValidatorResources</code>
  +    * passed in to retrieve pluggable validators
       * the different sets of validation rules.
       *
  -    * @param	resources	<code>ValidatorResources</code> 
  +    * @param	resources	<code>ValidatorResources</code>
       *				to use during validation.
  -    * @param	formName	Key used for retrieving the set of 
  +    * @param	formName	Key used for retrieving the set of
       *				validation rules.
      */
      public Validator(ValidatorResources resources, String formName) {
         this.resources = resources;
         this.formName = formName;
      }
  -   
  +
      /**
  -    * Add a resource to be used during the processing 
  +    * Add a resource to be used during the processing
       * of validations.
       *
  -    * @param	key		The full class name of the parameter 
  -    *				of the validation method that 
  -    *				corresponds to the value/instance 
  +    * @param	key		The full class name of the parameter
  +    *				of the validation method that
  +    *				corresponds to the value/instance
       *				passed in with it.
  -    * @param	value		The instance that will be passed 
  +    * @param	value		The instance that will be passed
       *				into the validation method.
      */
      public void addResource(String key, Object value) {
  @@ -197,72 +197,72 @@
      }
   
      /**
  -    * Get a resource to be used during the processing 
  +    * Get a resource to be used during the processing
       * of validations.
       *
  -    * @param	key		The full class name of the parameter 
  -    *				of the validation method that 
  -    *				corresponds to the value/instance 
  +    * @param	key		The full class name of the parameter
  +    *				of the validation method that
  +    *				corresponds to the value/instance
       *				passed in with it.
      */
   
     public Object getResource(String key) {
         return hResources.get(key);
     }
  -   
  +
      /**
  -    * Gets the form name which is the key 
  +    * Gets the form name which is the key
       * to a set of validation rules.
      */
      public String getFormName() {
  -      return formName;	
  +      return formName;
      }
  -   
  +
      /**
  -    * Sets the form name which is the key 
  +    * Sets the form name which is the key
       * to a set of validation rules.
      */
      public void setFormName(String formName) {
  -      this.formName = formName;	
  +      this.formName = formName;
      }
   
      /**
  -    * Gets the page.  This in conjunction with 
  -    * the page property of a <code>Field<code> 
  -    * can control the processing of fields.  
  -    * If the field's page is less than or equal 
  +    * Gets the page.  This in conjunction with
  +    * the page property of a <code>Field<code>
  +    * can control the processing of fields.
  +    * If the field's page is less than or equal
       * to this page value, it will be processed.
      */
      public int getPage() {
  -      return page;	
  +      return page;
      }
  -   
  +
      /**
  -    * Sets the page.  This in conjunction with 
  -    * the page property of a <code>Field<code> 
  -    * can control the processing of fields.  
  -    * If the field's page is less than or equal 
  +    * Sets the page.  This in conjunction with
  +    * the page property of a <code>Field<code>
  +    * can control the processing of fields.
  +    * If the field's page is less than or equal
       * to this page value, it will be processed.
      */
      public void setPage(int page) {
  -      this.page = page;	
  +      this.page = page;
      }
   
      /**
  -    * Clears the form name, resources that were added, 
  -    * and the page that was set (if any).  This can 
  -    * be called to reinitialize the Validator instance 
  -    * so it can be reused.  The form name (key to 
  -    * set of validation rules) and any resources needed, 
  -    * like the JavaBean being validated, will need to 
  -    * set and/or added to this instance again.  The 
  -    * <code>ValidatorResources</code> will not be removed 
  +    * Clears the form name, resources that were added,
  +    * and the page that was set (if any).  This can
  +    * be called to reinitialize the Validator instance
  +    * so it can be reused.  The form name (key to
  +    * set of validation rules) and any resources needed,
  +    * like the JavaBean being validated, will need to
  +    * set and/or added to this instance again.  The
  +    * <code>ValidatorResources</code> will not be removed
       * since it can be used again and is thread safe.
      */
      public void clear() {
         formName = null;
         hResources = new HashMap();
  -      page = 0;   
  +      page = 0;
      }
   
      /**
  @@ -303,7 +303,7 @@
         if (this.classLoader != null) {
            return (this.classLoader);
         }
  -      
  +
         if (this.useContextClassLoader) {
            ClassLoader classLoader =
                    Thread.currentThread().getContextClassLoader();
  @@ -311,7 +311,7 @@
                return (classLoader);
            }
         }
  -      
  +
         return (this.getClass().getClassLoader());
      }
   
  @@ -327,330 +327,250 @@
          this.classLoader = classLoader;
   
      }
  -      
  +
  +
  +    private boolean validateFieldForRule(Field field,
  +					ValidatorAction va,
  +					ValidatorResults results,
  +					Map hActions,
  +					int pos) throws ValidatorException {
  +	if (results.getValidatorResult(va.getName()) != null) {
  +	    return isValid(results.getValidatorResult(va.getName()));
  +	}
  +
  +	if (va.getDepends() != null) {
  +	    StringTokenizer st = new StringTokenizer(va.getDepends(), ",");
  +	    while (st.hasMoreTokens()) {
  +		String depend = st.nextToken().trim();
  +
  +		ValidatorAction depAction = (ValidatorAction)hActions.get(depend);
  +		if (depAction == null) {
  +		    log.error("No ValidatorAction called " + depend +
  +			      " found for field " + field.getProperty());
  +		    return false;
  +		}
  +		if (!validateFieldForRule(field, depAction,
  +					  results, hActions, pos)) {
  +		    return false;
  +		}
  +	    }
  +	}
  +
  +	try {
  +	    // Add these two Objects to the resources since they reference
  +	    // the current validator action and field
  +	    hResources.put(VALIDATOR_ACTION_KEY, va);
  +	    hResources.put(FIELD_KEY, field);
  +
  +	    Class c = getClassLoader().loadClass(va.getClassname());
  +
  +	    List lParams = va.getMethodParamsList();
  +	    int size = lParams.size();
  +	    int beanIndexPos = -1;
  +	    int fieldIndexPos = -1;
  +	    Class[] paramClass = new Class[size];
  +	    Object[] paramValue = new Object[size];
  +
  +	    for (int x = 0; x < size; x++) {
  +		String paramKey = (String)lParams.get(x);
  +
  +		if (BEAN_KEY.equals(paramKey)) {
  +		    beanIndexPos = x;
  +		}
  +
  +		if (FIELD_KEY.equals(paramKey)) {
  +		    fieldIndexPos = x;
  +		}
  +
  +		// There were problems calling getClass on paramValue[]
  +		paramClass[x] = getClassLoader().loadClass(paramKey);
  +
  +		paramValue[x] = hResources.get(paramKey);
  +	    }
  +
  +	    Method m = c.getMethod(va.getMethod(), paramClass);
  +
  +	    // If the method is static we don't need an instance of the class
  +	    // to call the method.  If it isn't, we do.
  +	    if (!Modifier.isStatic(m.getModifiers())) {
  +		try {
  +		    if (va.getClassnameInstance() == null) {
  +			va.setClassnameInstance(c.newInstance());
  +		    }
  +		} catch (Exception ex) {
  +		    log.error("Couldn't load instance " +
  +			      "of class " + va.getClassname() + ".  " + ex.getMessage());
  +		}
  +	    }
  +
  +	    Object result = null;
  +
  +	    if (field.isIndexed()) {
  +		Object oIndexed = PropertyUtils.getProperty(hResources.get(BEAN_KEY), field.getIndexedListProperty());
  +		Object indexedList[] = new Object[0];
  +
  +		if (oIndexed instanceof Collection) {
  +		    indexedList = ((Collection)oIndexed).toArray();
  +		} else if(oIndexed.getClass().isArray()) {
  +		    indexedList = (Object[])oIndexed;
  +		}
  +
  +		// Set current iteration object to the parameter array
  +		paramValue[beanIndexPos] = indexedList[pos];
  +
  +		// Set field clone with the key modified to represent
  +		// the current field
  +		Field indexedField = (Field)field.clone();
  +		indexedField.setKey(ValidatorUtil.replace(indexedField.getKey(), Field.TOKEN_INDEXED, "[" + pos + "]"));
  +		paramValue[fieldIndexPos] = indexedField;
  +
  +		result = m.invoke(va.getClassnameInstance(), paramValue);
  +		results.add(field, va.getName(), isValid(result), result);
  +		if (!isValid(result)) {
  +		    return false;
  +		}
  +	    } else {
  +		result = m.invoke(va.getClassnameInstance(), paramValue);
  +		results.add(field, va.getName(), isValid(result), result);
  +		if (!isValid(result))
  +		    return false;
  +	    }
  +	} catch (Exception e) {
  +	    log.error("reflection: " + e.getMessage(), e);
  +
  +	    results.add(field, va.getName(), false);
  +
  +	    if (e instanceof ValidatorException) {
  +		throw ((ValidatorException)e);
  +	    }
  +	    return false;
  +	}
  +	return true;
  +    }
  +
  +    /**
  +     * Run the validations on a given field, modifying the passed
  +     * ValidatorResults to add in any new errors found.  If the
  +     * field is an indexed one, run all the validations in the depends
  +     * clause over each item in turn, returning when the first one fails.
  +     * If it's non-indexed, just run it on the field.
  +     **/
  +
  +    private void validateField (Field field, ValidatorResults allResults)
  +	throws ValidatorException {
  +
  +	Map hActions = resources.getValidatorActions();
  +	if (field.isIndexed()) {
  +	    Object oIndexed;
  +	    try {
  +		oIndexed = PropertyUtils.getProperty(hResources.get(BEAN_KEY), field.getIndexedListProperty());
  +	    } catch (Exception e) {
  +		log.error("in validateField", e);
  +		return;
  +	    }
  +
  +	    Object indexedList[] = new Object[0];
  +
  +	    if (oIndexed instanceof Collection) {
  +		indexedList = ((Collection)oIndexed).toArray();
  +	    } else if(oIndexed.getClass().isArray()) {
  +		indexedList = (Object[])oIndexed;
  +	    }
  +
  +	    for (int pos = 0; pos < indexedList.length; pos++) {
  +		ValidatorResults results = new ValidatorResults();
  +		StringTokenizer st = new StringTokenizer(field.getDepends(), ",");
  +		while (st.hasMoreTokens()) {
  +		    String depend = st.nextToken().trim();
  +
  +		    ValidatorAction depAction = (ValidatorAction)hActions.get(depend);
  +		    if (depAction == null) {
  +			log.error("No ValidatorAction called " + depend +
  +				  " found for field " + field.getProperty());
  +			return;
  +		    }
  +		    boolean good =validateFieldForRule(field, depAction,
  +						       results, hActions, pos);
  +		    allResults.merge(results);
  +		    if (!good) return;
  +		}
  +	    }
  +	} else {
  +	    ValidatorResults results = new ValidatorResults();
  +	    StringTokenizer st = new StringTokenizer(field.getDepends(), ",");
  +	    while (st.hasMoreTokens()) {
  +		String depend = st.nextToken().trim();
  +
  +		ValidatorAction depAction = (ValidatorAction)hActions.get(depend);
  +		if (depAction == null) {
  +		    log.error("No ValidatorAction called " + depend +
  +			      " found for field " + field.getProperty());
  +		    return;
  +		}
  +		boolean good = validateFieldForRule(field, depAction,
  +						    results, hActions, 0);
  +		allResults.merge(results);
  +
  +		if (good == false) {
  +		    return;
  +		}
  +	    }
  +	}
  +    }
  +
      /**
  -    * Performs validations based on the configured resources.  
  -    * 
  -    * @return	The <code>Map</code> returned uses the property 
  -    *		of the <code>Field</code> for the key and the value 
  +    * Performs validations based on the configured resources.
  +    *
  +    * @return	The <code>Map</code> returned uses the property
  +    *		of the <code>Field</code> for the key and the value
       *		is the number of error the field had.
  -   */ 
  +   */
      public ValidatorResults validate() throws ValidatorException {
  -      ValidatorResults results = new ValidatorResults();
  -      Locale locale = null;
  -      
  -      if (hResources.containsKey(LOCALE_KEY)) {
  -         locale = (Locale)hResources.get(LOCALE_KEY);
  -      }
  -      hResources.put(VALIDATOR_KEY, this);
  -      
  -      if (locale == null) {
  -         locale = Locale.getDefault();
  -      }
  -         
  -      Form form = null;
  -      if (resources == null) {
  -	  throw new ValidatorException("Resources not defined for Validator");
  -      }
  -      if ((form = resources.get(locale, formName)) != null) {	    
  -         Map hActions = resources.getValidatorActions();
  -         List lActions = new ArrayList();
  -         Map hActionsRun = new HashMap();
  -         boolean bMoreActions = true;
  -         boolean bErrors = false;
  -      
  -         for (Iterator actions = hActions.values().iterator(); actions.hasNext(); )
  -            lActions.add(actions.next());
  -      
  -         while (bMoreActions) {
  -            ValidatorAction va = null;
  -            int iErrorCount = 0;
  -            
  -            // FIX ME - These sorts will not work for all variations.
  -            // Sort by number dependencies
  -            Collections.sort(lActions, new DependencyComparator());
  -      
  -            // Sort by number of dependencies successfully run
  -            Collections.sort(lActions, new DependencySuccessComparator(hActionsRun));
  -            
  -            if (lActions.size() > 0)
  -               va = (ValidatorAction)lActions.get(0);
  -      
  -            if (va != null && va.getDepends() != null && va.getDepends().length() > 0) {
  -               StringTokenizer st = new StringTokenizer(va.getDepends(), ",");
  -               while (st.hasMoreTokens()) {
  -                  String depend = st.nextToken().trim();
  -                  Object o = hActionsRun.get(depend);
  -      
  -                  if (log.isDebugEnabled()) {
  -      	             log.debug("ValidatorAction name=" + va.getName() + "  depends=" + va.getDepends());
  -      	          }
  -      	                       
  -                  if (o == null) {
  -                     lActions.clear();
  -                     va = null;
  -                     bMoreActions = false;
  -                     break;
  -                  } else {
  -                     boolean bContinue = ((Boolean)o).booleanValue();
  -
  -                     if (log.isDebugEnabled()) {
  -      	                log.debug("ValidatorAction name=" + va.getName() + "  depend=" + depend + "  bContinue=" + bContinue);
  -      	             }
  -                     
  -                     if (!bContinue) {
  -                        lActions.clear();
  -                        va = null;
  -                        bMoreActions = false;
  -                        break;
  -                     }
  -                  }
  -               }
  -            }
  -            
  -            // For debug   
  -
  -            if (log.isDebugEnabled()) {
  -               StringBuffer sbLog = new StringBuffer();
  -      	       sbLog.append("Order \n");
  -               
  -               for (Iterator actions = lActions.iterator(); actions.hasNext(); ) {
  -                  ValidatorAction tmp = (ValidatorAction)actions.next();
  -                  sbLog.append("\t ValidatorAction name=" + tmp.getName() + "  depends=" + tmp.getDepends() + "\n");
  -               }
  -
  -               log.debug(sbLog.toString());
  -      	    }
  -            
  -            if (va != null) {
  -               for (Iterator i = form.getFields().iterator(); i.hasNext(); ) {
  -                  Field field = (Field)i.next();         
  -      
  -                  if (field.getPage() <= page && (field.getDepends() != null && field.isDependency(va.getName()))) {
  -                     try {
  -                     	  // Add these two Objects to the resources since they reference 
  -                     	  // the current validator action and field
  -                     	  hResources.put(VALIDATOR_ACTION_KEY, va);
  -                     	  hResources.put(FIELD_KEY, field);
  -      
  -                     	  Class c = getClassLoader().loadClass(va.getClassname());
  -
  -                     	  List lParams = va.getMethodParamsList();
  -                     	  int size = lParams.size();
  -                     	  int beanIndexPos = -1;
  -                     	  int fieldIndexPos = -1;
  -                     	  int validatorIndexPos = -1;
  -                     	  Class[] paramClass = new Class[size];
  -                     	  Object[] paramValue = new Object[size];
  -      
  -                     	  for (int x = 0; x < size; x++) {
  -                     	     String paramKey = (String)lParams.get(x);
  -             	             
  -			     if (VALIDATOR_KEY.equals(paramKey)) {
  -				 validatorIndexPos = x;
  -			     }
  -
  -             	             if (BEAN_KEY.equals(paramKey)) {
  -             	                beanIndexPos = x;
  -             	             }
  -             	                
  -             	             if (FIELD_KEY.equals(paramKey)) {
  -             	                fieldIndexPos = x;
  -             	             }
  -             	             
  -                     	     // There were problems calling getClass on paramValue[]
  -                     	     paramClass[x] = getClassLoader().loadClass(paramKey);
  -
  -                     	     paramValue[x] = hResources.get(paramKey);
  -                     	  }
  -      
  -                        Method m = c.getMethod(va.getMethod(), paramClass);
  -      		  
  -      		        // If the method is static we don't need an instance of the class 
  -      		        // to call the method.  If it isn't, we do.
  -                        if (!Modifier.isStatic(m.getModifiers())) {
  -                           try {
  -                              if (va.getClassnameInstance() == null) {
  -                                 va.setClassnameInstance(c.newInstance());
  -                              }
  -                           } catch (Exception ex) {
  -                              log.error("Couldn't load instance " +
  -                                        "of class " + va.getClassname() + ".  " + ex.getMessage());
  -                           }
  -                        }
  -      
  -                        Object result = null;
  -                        
  -                        if (field.isIndexed()) {
  -                           Object oIndexed = PropertyUtils.getProperty(hResources.get(BEAN_KEY), field.getIndexedListProperty());
  -                           Object indexedList[] = new Object[0];
  -                           
  -                           if (oIndexed instanceof Collection) {
  -                              indexedList = ((Collection)oIndexed).toArray();
  -                           } else if(oIndexed.getClass().isArray()) {
  -                              indexedList = (Object[])oIndexed;
  -                           }
  -                           
  -                           for (int pos = 0; pos < indexedList.length; pos++) {
  -                              // Set current iteration object to the parameter array
  -                              paramValue[beanIndexPos] = indexedList[pos];
  -                              
  -                              // Set field clone with the key modified to represent 
  -                              // the current field
  -                              Field indexedField = (Field)field.clone();
  -                              indexedField.setKey(ValidatorUtil.replace(indexedField.getKey(), Field.TOKEN_INDEXED, "[" + pos + "]"));
  -                              paramValue[fieldIndexPos] = indexedField;
  -                              
  -                              result = m.invoke(va.getClassnameInstance(), paramValue);
  -                           }
  -                        } else {
  -                           result = m.invoke(va.getClassnameInstance(), paramValue);
  -                        }
  -                        
  -                        if (!isValid(result)) {
  -                           iErrorCount++;
  -                        }
  -                         
  -                        results.add(field, va.getName(), isValid(result), result);
  -      	       } catch (Exception e) {
  -      	          bErrors = true;
  -      	          log.error("reflection: " + e.getMessage(), e);
  -      	          
  -      	          results.add(field, va.getName(), false);
  -      	          
  -      	          if (e instanceof ValidatorException) {
  -      	             throw ((ValidatorException)e);
  -      	          }
  -      	       }
  -               
  -                  }
  -               }
  -               
  -               if (iErrorCount == 0) {
  -                  hActionsRun.put(va.getName(), new Boolean(true));
  -               } else {
  -                  hActionsRun.put(va.getName(), new Boolean(false));
  -               }
  -               
  -               if (log.isDebugEnabled()) {
  -                  log.debug("name=" + va.getName() + "  size=" + lActions.size());
  -               }
  -                  
  -               if (lActions.size() > 0) {
  -                  lActions.remove(0);
  -               }
  -               
  -               if (log.isDebugEnabled()) {
  -                  log.debug("after remove - name=" + va.getName() + "  size=" + lActions.size());
  -               }
  -            }
  -            
  -            if (lActions.size() == 0) {
  -               bMoreActions = false;
  -            }
  -         }
  -      }
  -      
  -      return results;
  +       ValidatorResults results = new ValidatorResults();
  +       Locale locale = null;
  +
  +       if (hResources.containsKey(LOCALE_KEY)) {
  +	   locale = (Locale)hResources.get(LOCALE_KEY);
  +       }
  +       hResources.put(VALIDATOR_KEY, this);
  +
  +       if (locale == null) {
  +	   locale = Locale.getDefault();
  +       }
  +
  +       Form form = null;
  +       if (resources == null) {
  +	   throw new ValidatorException("Resources not defined for Validator");
  +       }
  +       if ((form = resources.get(locale, formName)) != null) {
  +       for (Iterator i = form.getFields().iterator(); i.hasNext(); ) {
  +	   Field field = (Field)i.next();
  +	   if (field.getPage() <= page) {
  +	       validateField(field, results);
  +	   }
  +       }
  +       }
  +       return results;
      }
   
      /**
  -    * Returns if the result if valid.  If the 
  -    * result object is <code>Boolean</code>, then it will 
  -    * the value.  If the result object isn't <code>Boolean</code>, 
  -    * then it will return <code>false</code> if the result 
  -    * object is <code>null</code> and <code>true</code> if it 
  +    * Returns if the result if valid.  If the
  +    * result object is <code>Boolean</code>, then it will
  +    * the value.  If the result object isn't <code>Boolean</code>,
  +    * then it will return <code>false</code> if the result
  +    * object is <code>null</code> and <code>true</code> if it
       * isn't.
      */
      private boolean isValid(Object result) {
         boolean bValid = false;
  -      
  +
         if (result instanceof Boolean) {
            Boolean valid = (Boolean)result;
            bValid = valid.booleanValue();
         } else {
            bValid = (result != null);
         }
  -      
  -      return bValid;
  -   }
  -
  -   /**
  -    * Sort by number dependencies.
  -   */
  -   protected class DependencyComparator implements Comparator {
  -      
  -      public int compare(Object o1, Object o2) {
  -         ValidatorAction va1 = (ValidatorAction)o1;
  -         ValidatorAction va2 = (ValidatorAction)o2;
  -      
  -         if ((va1.getDepends() == null || va1.getDepends().length() == 0) && 
  -              (va2.getDepends() == null || va2.getDepends().length() == 0)) {
  -            return 0;
  -         } else if ((va1.getDepends() != null && va1.getDepends().length() > 0) &&
  -                    (va2.getDepends() == null || va2.getDepends().length() == 0)) {
  -            return 1;
  -         } else if ((va1.getDepends() == null || va1.getDepends().length() == 0) && 
  -                  (va2.getDepends() != null && va2.getDepends().length() > 0)) {
  -            return -1;
  -         } else {
  -            return va1.getDependencies().size() - va2.getDependencies().size();
  -         }
  -      }
  -
  -   }
  -
  -   /**
  -    * Sort by number of dependencies successfully run.
  -   */
  -   protected class DependencySuccessComparator implements Comparator {
  -      Map hActionsRun = null;
  -      
  -      public DependencySuccessComparator(Map hActionsRun) {
  -         this.hActionsRun = hActionsRun;
  -      }
  -      
  -      public int compare(Object o1, Object o2) {
  -         ValidatorAction va1 = (ValidatorAction)o1;
  -         ValidatorAction va2 = (ValidatorAction)o2;
  -      
  -         if ((va1.getDepends() == null || va1.getDepends().length() == 0) && 
  -              (va2.getDepends() == null || va2.getDepends().length() == 0)) {
  -            return 0;
  -         } else if ((va1.getDepends() != null && va1.getDepends().length() > 0) &&
  -                    (va2.getDepends() == null || va2.getDepends().length() == 0)) {
  -            return 1;
  -         } else if ((va1.getDepends() == null || va1.getDepends().length() == 0) && 
  -                  (va2.getDepends() != null && va2.getDepends().length() > 0)) {
  -            return -1;
  -         } else {
  -            int iVA1 = 0;
  -            int iVA2 = 0;
  -            
  -            for (Iterator i = va1.getDependencies().iterator(); i.hasNext(); ) {
  -               String depend = ((String)i.next()).trim();
  -               Object o = hActionsRun.get(depend);
  -               
  -               if (o != null) {
  -                  if (((Boolean)o).booleanValue())
  -                    iVA1++;
  -               }
  -            }
  -      
  -            for (Iterator i = va2.getDependencies().iterator(); i.hasNext(); ) {
  -               String depend = ((String)i.next()).trim();
  -               Object o = hActionsRun.get(depend);
  -               
  -               if (o != null) {
  -                  if (((Boolean)o).booleanValue())
  -                    iVA2++;
  -               }	
  -            }
  -            
  -            return iVA1 - iVA2;
  -         }
  -      }
   
  +      return bValid;
      }
  -
   }
  
  
  
  1.5       +30 -28    jakarta-commons/validator/src/test/org/apache/commons/validator/ValidatorTestSuite.java
  
  Index: ValidatorTestSuite.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/test/org/apache/commons/validator/ValidatorTestSuite.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ValidatorTestSuite.java	19 Sep 2002 17:11:46 -0000	1.4
  +++ ValidatorTestSuite.java	24 Sep 2002 20:23:35 -0000	1.5
  @@ -62,44 +62,46 @@
   
   package org.apache.commons.validator;
   
  -import junit.framework.Test;                           
  -import junit.framework.TestCase;                          
  +import junit.framework.Test;
  +import junit.framework.TestCase;
   import junit.framework.TestSuite;
   
  -                                                          
  -/**                                                       
  +
  +/**
    * Test suite for <code>org.apache.commons.validator</code>
    * package.
    *
    * @author David Winterfeldt
  + * @author James Turner
    * @version $Revision$ $Date$
  -*/                                                       
  -public class ValidatorTestSuite extends TestCase {            
  -                                                          
  -    public ValidatorTestSuite(String name) {                  
  +*/
  +public class ValidatorTestSuite extends TestCase {
  +
  +    public ValidatorTestSuite(String name) {
           super(name);
  -    }                                                     
  +    }
   
       public static Test suite() {
          TestSuite suite = new TestSuite();
   
  -       suite.addTest(RequiredNameTest.suite()); 
  -       suite.addTest(RequiredIfTest.suite()); 
  -       suite.addTest(ByteTest.suite()); 
  -       suite.addTest(ShortTest.suite()); 
  -       suite.addTest(IntegerTest.suite()); 
  -       suite.addTest(LongTest.suite()); 
  -       suite.addTest(FloatTest.suite()); 
  -       suite.addTest(DoubleTest.suite()); 
  -       suite.addTest(TypeTest.suite()); 
  -       suite.addTest(EmailTest.suite()); 
  -       suite.addTest(ValidatorTest.suite()); 
  +       suite.addTest(RequiredNameTest.suite());
  +       suite.addTest(RequiredIfTest.suite());
  +       suite.addTest(MultipleTests.suite());
  +       suite.addTest(ByteTest.suite());
  +       suite.addTest(ShortTest.suite());
  +       suite.addTest(IntegerTest.suite());
  +       suite.addTest(LongTest.suite());
  +       suite.addTest(FloatTest.suite());
  +       suite.addTest(DoubleTest.suite());
  +       suite.addTest(TypeTest.suite());
  +       suite.addTest(EmailTest.suite());
  +       suite.addTest(ValidatorTest.suite());
   
          return suite;
       }
  -                                                          
  -    public static void main(String args[]) {              
  +
  +    public static void main(String args[]) {
           junit.textui.TestRunner.run(suite());
  -    }          
  -                                               
  +    }
  +
   }
  
  
  
  1.1                  jakarta-commons/validator/src/test/org/apache/commons/validator/MultipleTests.java
  
  Index: MultipleTests.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/validator/src/test/org/apache/commons/validator/MultipleTests.java,v 1.1 2002/09/24 20:23:35 turner Exp $
   * $Revision: 1.1 $
   * $Date: 2002/09/24 20:23:35 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   */
  
  
  package org.apache.commons.validator;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.Map;
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  import junit.framework.AssertionFailedError;
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogSource;
  
  /**
   * <p>Performs Validation Test.</p>
   *
   * @author James Turner
   * @version $Revision: 1.1 $ $Date: 2002/09/24 20:23:35 $
  */
  public class MultipleTests extends TestCase {
  
     /**
      * The key used to retrieve the set of validation
      * rules from the xml file.
     */
     protected static String FORM_KEY = "nameForm";
  
     /**
      * The key used to retrieve the validator action.
     */
     protected static String ACTION = "required";
  
  
     /**
      * Commons Logging instance.
     */
     private Log log = LogSource.getInstance(this.getClass().getName());
  
     /**
      * Resources used for validation tests.
     */
     private ValidatorResources resources = null;
  
     public MultipleTests(String name) {
         super(name);
     }
  
     /**
      * Start the tests.
      *
      * @param theArgs the arguments. Not used
      */
     public static void main(String[] theArgs) {
         junit.awtui.TestRunner.main(new String[] {MultipleTests.class.getName()});
     }
  
     /**
      * @return a test suite (<code>TestSuite</code>) that includes all methods
      *         starting with "test"
      */
     public static Test suite() {
         // All methods starting with "test" will be executed in the test suite.
         return new TestSuite(MultipleTests.class);
     }
  
     /**
      * Load <code>ValidatorResources</code> from
      * validator-name-required.xml.
     */
     protected void setUp() throws IOException {
        // Load resources
        InputStream in = null;
        resources = new ValidatorResources();
  
        try {
           in = this.getClass().getResourceAsStream("validator-multipletest.xml");
           ValidatorResourcesInitializer.initialize(resources, in);
        } catch (IOException e) {
           log.error(e.getMessage(), e);
           throw e;
        } finally {
           if (in != null) {
              try { in.close(); } catch (Exception e) {}
           }
        }
     }
  
     protected void tearDown() {
     }
  
     /**
      * With nothing provided, we should fail both because both are required.
     */
     public void testBothBlank() throws ValidatorException {
        // Create bean to run test on.
        NameBean name = new NameBean();
  
        // Construct validator based on the loaded resources
        // and the form key
        Validator validator = new Validator(resources, FORM_KEY);
        // add the name bean to the validator as a resource
        // for the validations to be performed on.
        validator.addResource(Validator.BEAN_KEY, name);
  
        // Get results of the validation.
        ValidatorResults results = null;
  
        // throws ValidatorException,
        // but we aren't catching for testing
        // since no validation methods we use
        // throw this
        results = validator.validate();
  
        assertNotNull("Results are null.", results);
  
        ValidatorResult firstNameResult = results.getValidatorResult("firstName");
        ValidatorResult lastNameResult = results.getValidatorResult("lastName");
  
        assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
        assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
        assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
  
        assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult);
        assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
        assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION));
        assertTrue("Last Name ValidatorResults should not contain the 'int' action.", !lastNameResult.containsAction("int"));
     }
  
     /**
      * If the first name fails required, and the second test fails int, we should get two errors.
     */
     public void testRequiredFirstNameBlankLastNameShort() throws ValidatorException {
        // Create bean to run test on.
        NameBean name = new NameBean();
        name.setFirstName("");
        name.setLastName("Test");
  
        // Construct validator based on the loaded resources
        // and the form key
        Validator validator = new Validator(resources, FORM_KEY);
        // add the name bean to the validator as a resource
        // for the validations to be performed on.
        validator.addResource(Validator.BEAN_KEY, name);
  
        // Get results of the validation.
        ValidatorResults results = null;
  
        results = validator.validate();
  
        assertNotNull("Results are null.", results);
  
        ValidatorResult firstNameResult = results.getValidatorResult("firstName");
        ValidatorResult lastNameResult = results.getValidatorResult("lastName");
  
        assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
        assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
        assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
  
        assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult);
        assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int"));
        assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int"));
     }
  
     /**
      * If the first name is there, and the last name fails int, we should get one error.
     */
     public void testRequiredLastNameShort() throws ValidatorException {
        // Create bean to run test on.
        NameBean name = new NameBean();
        name.setFirstName("Test");
        name.setLastName("Test");
  
        // Construct validator based on the loaded resources
        // and the form key
        Validator validator = new Validator(resources, FORM_KEY);
        // add the name bean to the validator as a resource
        // for the validations to be performed on.
        validator.addResource(Validator.BEAN_KEY, name);
  
        // Get results of the validation.
        ValidatorResults results = null;
  
        results = validator.validate();
  
        assertNotNull("Results are null.", results);
  
        ValidatorResult firstNameResult = results.getValidatorResult("firstName");
        ValidatorResult lastNameResult = results.getValidatorResult("lastName");
  
        assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
        assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
        assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION));
  
        assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult);
        assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int"));
        assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int"));
     }
  
     /**
      * If first name is ok and last name is ok and is an int, no errors.
     */
     public void testRequiredLastNameLong() throws ValidatorException {
        // Create bean to run test on.
        NameBean name = new NameBean();
        name.setFirstName("Joe");
        name.setLastName("12345678");
  
        // Construct validator based on the loaded resources
        // and the form key
        Validator validator = new Validator(resources, FORM_KEY);
        // add the name bean to the validator as a resource
        // for the validations to be performed on.
        validator.addResource(Validator.BEAN_KEY, name);
  
        // Get results of the validation.
        ValidatorResults results = null;
  
        results = validator.validate();
  
        assertNotNull("Results are null.", results);
  
        ValidatorResult firstNameResult = results.getValidatorResult("firstName");
        ValidatorResult lastNameResult = results.getValidatorResult("lastName");
  
        assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
        assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
        assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION));
  
        assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult);
        assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int"));
        assertTrue("Last Name ValidatorResult for the 'int' action should have passed.", lastNameResult.isValid("int"));
     }
  
  
  }
  
  
  
  1.1                  jakarta-commons/validator/src/test/org/apache/commons/validator/validator-multipletest.xml
  
  Index: validator-multipletest.xml
  ===================================================================
  <form-validation>
     <global>
        <validator name="int"
                   classname="org.apache.commons.validator.TestValidator"
                   method="validateInt"
                   methodParams="java.lang.Object,org.apache.commons.validator.Field"/>
        <validator name="required"
                   classname="org.apache.commons.validator.TestValidator"
                   method="validateRequired"
                   methodParams="java.lang.Object,org.apache.commons.validator.Field"/>
     </global>
     <formset>
        <form    name="nameForm">
           <field    property="firstName"  depends="required">
           	     <arg0 key="nameForm.firstname.displayname"/>
           </field>    
           <field    property="lastName"
           	   depends="required,int">
           	     <arg0 key="nameForm.lastname.displayname"/>
           </field>
        </form>
     </formset>   
  </form-validation>
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message