Commits

Anonymous committed 312fb1e

Issue number: XW-207
Obtained from:
Submitted by: jhouse
Reviewed by: jhouse, mail list

git-svn-id: http://svn.opensymphony.com/svn/xwork/trunk@397e221344d-f017-0410-9bd5-d282ab1896d7

  • Participants
  • Parent commits 13d0254

Comments (0)

Files changed (5)

src/java/com/opensymphony/xwork/validator/ActionValidatorManager.java

  *
  * @author Jason Carreira
  * @author Mark Woon
+ * @author James House
  */
 public class ActionValidatorManager {
 
 
         if (validatorCache.containsKey(validatorKey)) {
             if (FileManager.isReloadingConfigs()) {
-                validatorCache.put(validatorKey, buildValidators(clazz, context, true, null));
+                validatorCache.put(validatorKey, buildValidatorConfigs(clazz, context, true, null));
             }
         } else {
-            validatorCache.put(validatorKey, buildValidators(clazz, context, false, null));
+            validatorCache.put(validatorKey, buildValidatorConfigs(clazz, context, false, null));
         }
 
-        return (List) validatorCache.get(validatorKey);
+        // get the set of validator configs
+        List cfgs = (List) validatorCache.get(validatorKey);
+
+        // create clean instances of the validators for the caller's use
+        ArrayList validators = new ArrayList(cfgs.size());
+        for (Iterator iterator = cfgs.iterator(); iterator.hasNext(); ) {
+            ValidatorConfig cfg = (ValidatorConfig) iterator.next();
+            Validator validator = ValidatorFactory.getValidator(cfg);
+            validators.add(validator);
+        }
+        
+        return validators;
     }
 
     /**
         return sb.toString();
     }
 
-    private static List buildAliasValidators(Class aClass, String context, boolean checkFile) {
+    private static List buildAliasValidatorConfigs(Class aClass, String context, boolean checkFile) {
         String fileName = aClass.getName().replace('.', '/') + "-" + context + VALIDATION_CONFIG_SUFFIX;
 
         return loadFile(fileName, aClass, checkFile);
     }
 
-    private static List buildClassValidators(Class aClass, boolean checkFile) {
+    private static List buildClassValidatorConfigs(Class aClass, boolean checkFile) {
         String fileName = aClass.getName().replace('.', '/') + VALIDATION_CONFIG_SUFFIX;
 
         return loadFile(fileName, aClass, checkFile);
     }
 
     /**
-     * <p>This method 'collects' all the validators for a given action invocation.</p>
+     * <p>This method 'collects' all the validator configurations for a given 
+     * action invocation.</p>
      *
      * <p>It will traverse up the class hierarchy looking for validators for every super class
      * and directly implemented interface of the current action, as well as adding validators for
      * @param checkFile true if the validation config file should be checked to see if it has been
      *      updated.
      * @param checked the set of previously checked class-contexts, null if none have been checked
-     * @return a list of validators for the given class and context.
+     * @return a list of validator configs for the given class and context.
      */
-    private static List buildValidators(Class clazz, String context, boolean checkFile, Set checked) {
-        List validators = new ArrayList();
+    private static List buildValidatorConfigs(Class clazz, String context, boolean checkFile, Set checked) {
+        List validatorConfigs = new ArrayList();
 
         if (checked == null) {
             checked = new TreeSet();
         } else if (checked.contains(clazz.getName())) {
-            return validators;
+            return validatorConfigs;
         }
 
         if (clazz.isInterface()) {
             Class[] interfaces = clazz.getInterfaces();
 
             for (int x = 0; x < interfaces.length; x++) {
-                validators.addAll(buildValidators(interfaces[x], context, checkFile, checked));
+                validatorConfigs.addAll(buildValidatorConfigs(interfaces[x], context, checkFile, checked));
             }
         } else {
             if (!clazz.equals(Object.class)) {
-                validators.addAll(buildValidators(clazz.getSuperclass(), context, checkFile, checked));
+                validatorConfigs.addAll(buildValidatorConfigs(clazz.getSuperclass(), context, checkFile, checked));
             }
         }
 
                 continue;
             }
 
-            validators.addAll(buildClassValidators(interfaces[x], checkFile));
+            validatorConfigs.addAll(buildClassValidatorConfigs(interfaces[x], checkFile));
 
             if (context != null) {
-                validators.addAll(buildAliasValidators(interfaces[x], context, checkFile));
+                validatorConfigs.addAll(buildAliasValidatorConfigs(interfaces[x], context, checkFile));
             }
 
             checked.add(interfaces[x].getName());
         }
 
-        validators.addAll(buildClassValidators(clazz, checkFile));
+        validatorConfigs.addAll(buildClassValidatorConfigs(clazz, checkFile));
 
         if (context != null) {
-            validators.addAll(buildAliasValidators(clazz, context, checkFile));
+            validatorConfigs.addAll(buildAliasValidatorConfigs(clazz, context, checkFile));
         }
 
         checked.add(clazz.getName());
 
-        return validators;
+        return validatorConfigs;
     }
 
     private static List loadFile(String fileName, Class clazz, boolean checkFile) {
                 is = FileManager.loadFile(fileName, clazz);
 
                 if (is != null) {
-                    retList = new ArrayList(ValidatorFileParser.parseActionValidators(is));
+                    retList = new ArrayList(ValidatorFileParser.parseActionValidatorConfigs(is));
                 }
             } catch (Exception e) {
                 LOG.error("Caught exception while loading file " + fileName, e);

src/java/com/opensymphony/xwork/validator/ValidationInterceptor.java

 /**
  * Validates an action. This interceptor extends the {@link AroundInterceptor} and implements only the
  * {@link AroundInterceptor#before(com.opensymphony.xwork.ActionInvocation)} method. This class
- * simply class the {@link ActionValidatorManager#validate(java.lang.Object, java.lang.String)} method
+ * simply calls the {@link ActionValidatorManager#validate(java.lang.Object, java.lang.String)} method
  * with the given Action and its context.
  *
  * @author Jason Carreira

src/java/com/opensymphony/xwork/validator/ValidatorFactory.java

  * Created : Jan 20, 2003 12:11:11 PM
  *
  * @author Jason Carreira
+ * @author James House
  */
 public class ValidatorFactory {
     //~ Static fields/initializers /////////////////////////////////////////////
 
     //~ Methods ////////////////////////////////////////////////////////////////
 
-    public static Validator getValidator(String type, Map params) {
-        String className = (String) validators.get(type);
-
-        if (className == null) {
-            throw new IllegalArgumentException("There is no validator class mapped to the name " + type);
-        }
+    /**
+     * Get a Validator that matches the given configuration.
+     */
+    public static Validator getValidator(ValidatorConfig cfg) {
 
+        String className = lookupRegisteredValidatorType(cfg.getType());
+        
         Validator validator;
 
         try {
-            validator = ObjectFactory.getObjectFactory().buildValidator(className, params);
+            // instantiate the validator, and set configured parameters
+            validator = ObjectFactory.getObjectFactory().buildValidator(className, cfg.getParams());
         } catch (Exception e) {
             e.printStackTrace();
             throw new IllegalArgumentException("There was a problem creating a Validator of type " + className);
         }
 
+        // set other configured properties
+        validator.setMessageKey(cfg.getMessageKey());
+        validator.setDefaultMessage(cfg.getDefaultMessage());
+        if (validator instanceof ShortCircuitableValidator) {
+            ((ShortCircuitableValidator) validator).setShortCircuit(cfg.isShortCircuit());
+        }
+        
         return validator;
     }
 
 
         validators.put(name, className);
     }
+    
+    public static String lookupRegisteredValidatorType(String name) {
+        // lookup the validator class mapped to the type name
+        String className = (String) validators.get(name);
+
+        if (className == null) {
+            throw new IllegalArgumentException("There is no validator class mapped to the name " + name);
+        }
+        
+        return className;
+    }
 
     private static void parseValidators() {
         if (LOG.isDebugEnabled()) {

src/java/com/opensymphony/xwork/validator/ValidatorFileParser.java

  * Created : Jan 20, 2003 1:30:53 PM
  *
  * @author Jason Carreira
+ * @author James House
  */
 public class ValidatorFileParser {
     //~ Static fields/initializers /////////////////////////////////////////////
 
     //~ Methods ////////////////////////////////////////////////////////////////
 
-    public static List parseActionValidators(InputStream is) {
-        List validators = new ArrayList();
+    public static List parseActionValidatorConfigs(InputStream is) {
+        List validatorCfgs = new ArrayList();
         Document doc = null;
 
         try {
                 extraParams.put("fieldName", fieldName);
 
                 NodeList validatorNodes = fieldElement.getElementsByTagName("field-validator");
-                addValidators(validatorNodes, extraParams, validators);
+                addValidatorConfigs(validatorNodes, extraParams, validatorCfgs);
             }
 
             NodeList validatorNodes = doc.getElementsByTagName("validator");
-            addValidators(validatorNodes, new HashMap(), validators);
+            addValidatorConfigs(validatorNodes, new HashMap(), validatorCfgs);
         }
 
-        return validators;
+        return validatorCfgs;
     }
 
     public static void parseValidatorDefinitions(InputStream is) {
         }
     }
 
-    private static void addValidators(NodeList validatorNodes, Map extraParams, List validators) {
+    private static void addValidatorConfigs(NodeList validatorNodes, Map extraParams, List validatorCfgs) {
         for (int j = 0; j < validatorNodes.getLength(); j++) {
             Element validatorElement = (Element) validatorNodes.item(j);
             String validatorType = validatorElement.getAttribute("type");
                 params.put(paramName, paramValue);
             }
 
-            Validator validator = ValidatorFactory.getValidator(validatorType, params);
+            // ensure that the type is valid...
+            ValidatorFactory.lookupRegisteredValidatorType(validatorType);
+            
+            ValidatorConfig vCfg = new ValidatorConfig(validatorType, params);
 
-            if (validator instanceof ShortCircuitableValidator) {
-                ((ShortCircuitableValidator) validator).setShortCircuit(Boolean.valueOf(validatorElement.getAttribute("short-circuit")).booleanValue());
-            }
+            vCfg.setShortCircuit(Boolean.valueOf(validatorElement.getAttribute("short-circuit")).booleanValue());
 
             NodeList messageNodes = validatorElement.getElementsByTagName("message");
             Element messageElement = (Element) messageNodes.item(0);
             String key = messageElement.getAttribute("key");
 
             if ((key != null) && (key.trim().length() > 0)) {
-                validator.setMessageKey(key);
+                vCfg.setMessageKey(key);
             }
 
             final Node defaultMessageNode = messageElement.getFirstChild();
             String defaultMessage = (defaultMessageNode == null) ? "" : defaultMessageNode.getNodeValue();
-            validator.setDefaultMessage(defaultMessage);
-            validators.add(validator);
+            vCfg.setDefaultMessage(defaultMessage);
+            validatorCfgs.add(vCfg);
         }
     }
 }

src/test/com/opensymphony/xwork/validator/ValidatorFileParserTest.java

 
 import com.opensymphony.xwork.config.ConfigurationManager;
 import com.opensymphony.xwork.config.providers.MockConfigurationProvider;
-import com.opensymphony.xwork.validator.validators.ExpressionValidator;
-import com.opensymphony.xwork.validator.validators.IntRangeFieldValidator;
-import com.opensymphony.xwork.validator.validators.RequiredFieldValidator;
 
 import junit.framework.TestCase;
 
+import java.io.IOException;
 import java.io.InputStream;
 
 import java.util.List;
  * Created : Jan 20, 2003 3:41:26 PM
  *
  * @author Jason Carreira
+ * @author James House
  */
 public class ValidatorFileParserTest extends TestCase {
     //~ Methods ////////////////////////////////////////////////////////////////
     public void testParser() {
         InputStream is = ClassLoaderUtil.getResourceAsStream("com/opensymphony/xwork/validator/validator-parser-test.xml", this.getClass());
 
-        List configs = ValidatorFileParser.parseActionValidators(is);
+        List configs = ValidatorFileParser.parseActionValidatorConfigs(is);
+        
         assertNotNull(configs);
         assertEquals(5, configs.size());
 
-        Validator validator = (Validator) configs.get(0);
-        assertTrue(validator instanceof RequiredFieldValidator);
+        ValidatorConfig cfg = (ValidatorConfig) configs.get(0);
+        assertEquals("required", cfg.getType());
+        assertEquals("foo", cfg.getParams().get("fieldName"));
+        assertEquals("You must enter a value for foo.", cfg.getDefaultMessage());
 
-        FieldValidator fieldValidator = (FieldValidator) validator;
-        assertEquals("foo", fieldValidator.getFieldName());
-        assertEquals("You must enter a value for foo.", fieldValidator.getDefaultMessage());
+        cfg = (ValidatorConfig) configs.get(1);
+        assertEquals("required", cfg.getType());
+        assertTrue(cfg.isShortCircuit());
 
-        validator = (Validator) configs.get(1);
-        assertTrue(validator instanceof ShortCircuitableValidator);
-        assertTrue(((ShortCircuitableValidator) validator).isShortCircuit());
+        cfg = (ValidatorConfig) configs.get(2);
+        assertEquals("int", cfg.getType());
+        assertFalse(cfg.isShortCircuit());
 
-        validator = (Validator) configs.get(2);
-        assertTrue(validator instanceof IntRangeFieldValidator);
-        assertFalse(((ShortCircuitableValidator) validator).isShortCircuit());
+        cfg = (ValidatorConfig) configs.get(3);
+        assertEquals("expression", cfg.getType());
+        assertFalse(cfg.isShortCircuit());
 
-        validator = (Validator) configs.get(3);
-        assertTrue(validator instanceof ExpressionValidator);
-        assertFalse(((ShortCircuitableValidator) validator).isShortCircuit());
-
-        validator = (Validator) configs.get(4);
-        assertTrue(validator instanceof ExpressionValidator);
-        assertTrue(((ShortCircuitableValidator) validator).isShortCircuit());
+        cfg = (ValidatorConfig) configs.get(4);
+        assertEquals("expression", cfg.getType());
+        assertTrue(cfg.isShortCircuit());
     }
 
     protected void setUp() throws Exception {