You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by hu...@apache.org on 2004/06/08 16:48:35 UTC

cvs commit: jakarta-commons/validator/src/test/org/apache/commons/validator BSFTest.java EmailTest.java ValidatorTestSuite.java

husted      2004/06/08 07:48:35

  Modified:    validator project.xml
               validator/src/share/org/apache/commons/validator
                        EmailValidator.java
               validator/src/test/org/apache/commons/validator
                        EmailTest.java ValidatorTestSuite.java
  Added:       validator/src/share/org/apache/commons/validator
                        BSFValidator.java
               validator/src/test/org/apache/commons/validator BSFTest.java
  Log:
  Apply #23990 "EmailValidator" and #29205 "Add BSFValidator", submitted by Don Brown.
  
  Revision  Changes    Path
  1.45      +12 -0     jakarta-commons/validator/project.xml
  
  Index: project.xml
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/project.xml,v
  retrieving revision 1.44
  retrieving revision 1.45
  diff -u -r1.44 -r1.45
  --- project.xml	10 Apr 2004 19:39:10 -0000	1.44
  +++ project.xml	8 Jun 2004 14:48:35 -0000	1.45
  @@ -269,6 +269,18 @@
       </dependency>
   
       <dependency>
  +      <id>bsf</id>
  +      <version>2.3.0</version>
  +      <url>http://jakarta.apache.org/bsf/index.html</url>
  +    </dependency>
  +    
  +    <dependency>
  +      <id>bsh</id>
  +      <version>2.0b1</version>
  +      <url>http://www.beanshell.org/index.html</url>
  +    </dependency>
  + 
  +    <dependency>
         <id>xml-apis</id>
         <version>2.0.2</version>
         <url>http://xml.apache.org/commons/</url>
  
  
  
  1.15      +9 -8      jakarta-commons/validator/src/share/org/apache/commons/validator/EmailValidator.java
  
  Index: EmailValidator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/share/org/apache/commons/validator/EmailValidator.java,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- EmailValidator.java	3 May 2004 00:50:23 -0000	1.14
  +++ EmailValidator.java	8 Jun 2004 14:48:35 -0000	1.15
  @@ -51,10 +51,10 @@
       private static final String LEGAL_ASCII_PATTERN = "/^[\\000-\\177]+$/";
       private static final String EMAIL_PATTERN = "/^(.+)@(.+)$/";
       private static final String IP_DOMAIN_PATTERN =
  -            "/^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$/";
  +            "/^\\[(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})\\]$/";
   
  -    private static final String USER_PATTERN = "/^" + WORD + "(\\." + WORD + ")*$/";
  -    private static final String DOMAIN_PATTERN = "/^" + ATOM + "(\\." + ATOM + ")*$/";
  +    private static final String USER_PATTERN = "/^\\s*" + WORD + "(\\." + WORD + ")*\\s*$/";
  +    private static final String DOMAIN_PATTERN = "/^\\s*" + ATOM + "(\\." + ATOM + ")*\\s*$/";
       private static final String ATOM_PATTERN = "/(" + ATOM + ")/";
   
       /**
  @@ -126,6 +126,8 @@
           if (ipAddressMatcher.match(IP_DOMAIN_PATTERN, domain)) {
               if (!isValidIpAddress(ipAddressMatcher)) {
                   return false;
  +            } else {
  +                return true;
               }
           } else {
               // Domain is symbolic name
  @@ -189,7 +191,6 @@
           boolean match = true;
           int i = 0;
           Perl5Util atomMatcher = new Perl5Util();
  -
           while (match) {
               match = atomMatcher.match(ATOM_PATTERN, domain);
               if (match) {
  @@ -201,7 +202,7 @@
                           : domain.substring(l);
   
                   i++;
  -            }
  +            } 
           }
   
           int len = i;
  
  
  
  1.1                  jakarta-commons/validator/src/share/org/apache/commons/validator/BSFValidator.java
  
  Index: BSFValidator.java
  ===================================================================
  /*
   *  $Header: /home/cvs/jakarta-commons/validator/src/share/org/apache/commons/validator/BSFValidator.java,v 1.1 2004/06/08 14:48:35 husted Exp $
   *  $Revision: 1.1 $
   *  $Date: 2004/06/08 14:48:35 $
   *
   *  ====================================================================
   *  Copyright 2001-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *  http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   */
  package org.apache.commons.validator;
  
  import org.apache.bsf.BSFManager;
  import org.apache.bsf.BSFEngine;
  import org.apache.bsf.BSFException;
  import org.apache.commons.beanutils.PropertyUtils;
  import java.util.Iterator;
  import java.lang.reflect.InvocationTargetException;
  import org.apache.commons.beanutils.PropertyUtils;
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  
  /**
   *  <p>
   *
   *  Perform validations using script snippets.</p> <p>
   *
   *  The script snippet in var "eval" will be evaluated against the field value
   *  Any Bean Scripting Framework (BSF) supported language can be used, but
   *  BeanShell is used by default. This validator can be used with passed <code>BSFEngine</code>
   *  and <code>BSFManager</code> instances containing predefined
   *  application-specific objects in the scripting scope. matches for the field
   *  property xpath expression are allowed. </p> <p>
   *
   *  The following variables are automatically defined in the script scope: </p>
   *
   *  <ul>
   *    <li> <code>value</code> - The value of the current field</li>
   *    <li> <code>target</code> - The whole object/form being validated</li>
   *    <li> <code>field</code> - The <code>Field</code> object containg the field
   *    definition</li>
   *  </ul>
   *  <p>
   *
   *  This implementation is thread safe. </p> .
   */
  public class BSFValidator {
  
      /**
       *  Resources key the <code>BSFEngine</code> is stored under. This will be
       *  automatically passed into a validation method with the current <code>BSFEngine</code>
       *  if it is specified in the method signature. The <code>BSFEngine</code>
       *  will be used to execute the script snippet.
       */
      public final static String BSF_ENGINE_PARAM = "org.apache.bsf.BSFEngine";
  
      /**
       *  Resources key the <code>BSFManager</code> is stored under. This will be
       *  automatically passed into a validation method with the current <code>BSFManager</code>
       *  if it is specified in the method signature. The <code>BSFManager</code>
       *  will be used to declare beans for the engine.
       */
      public final static String BSF_MANAGER_PARAM = "org.apache.bsf.BSFManager";
  
      private final static Log log = LogFactory.getLog(BSFValidator.class);
  
  
      /**
       *  Determine whether the field is valid by evaluating the xpath expression
       *  in the "test" variable and returning the boolean result.
       *
       *@param  obj    The object to validate
       *@param  field  The field to validate
       *@return        The boolean result of the xpath evaluation
       */
      public boolean isValid(Object obj, Field field) {
          BSFManager manager = new BSFManager();
          BSFEngine engine = null;
          try {
              engine = manager.loadScriptingEngine("beanshell");
          } catch (BSFException ex) {
              log.error("Unable to load beanshell bsf engine", ex);
          }
          if (engine != null) {
              return isValid(obj, field, manager, engine);
          } else {
              return false;
          }
      }
  
  
      /**
       *  Determine whether the field is valid by evaluating the xpath expression
       *  in the "test" variable and returning the boolean result.
       *
       *@param  obj         The object to validate
       *@param  field       The field to validate
       *@param  bsfManager  Description of the Parameter
       *@param  engine      Description of the Parameter
       *@return             The boolean result of the xpath evaluation
       */
      public boolean isValid(Object obj, Field field, BSFManager bsfManager, BSFEngine engine) {
          try {
              Object value = getFieldValue(field, obj);
  
              if (value != null) {
                  bsfManager.declareBean("value", value, value.getClass());
              }
              bsfManager.declareBean("field", field, Field.class);
              bsfManager.declareBean("target", obj, obj.getClass());
              Object ret = engine.eval("field:" + field.getProperty(), 0, 0, field.getVarValue("eval"));
              if (ret != null) {
                  if (ret instanceof Boolean) {
                      log.debug("found boolean:" + ret);
                      return ((Boolean) ret).booleanValue();
                  } else {
                      log.debug("unknown object returned");
                      return true;
                  }
              } else {
                  log.debug("no object returned");
                  return false;
              }
          } catch (BSFException ex) {
              log.debug(ex, ex);
              return false;
          }
      }
  
  
      /**
       *  Gets the field value from the source object. Override to support other
       *  field location strategies such as JXPath expressions.
       *
       *@param  field  The field definition to validate
       *@param  obj    The object to validate
       *@return        The value of the field
       */
      protected Object getFieldValue(Field field, Object obj) {
          Object value = null;
          try {
              value = PropertyUtils.getProperty(obj, field.getProperty());
          } catch (IllegalAccessException e) {
              log.warn(e.getMessage(), e);
          } catch (InvocationTargetException e) {
              log.warn(e.getMessage(), e);
          } catch (NoSuchMethodException e) {
              log.warn(e.getMessage(), e);
          }
          return value;
      }
  }
  
  
  
  
  1.26      +14 -3     jakarta-commons/validator/src/test/org/apache/commons/validator/EmailTest.java
  
  Index: EmailTest.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/test/org/apache/commons/validator/EmailTest.java,v
  retrieving revision 1.25
  retrieving revision 1.26
  diff -u -r1.25 -r1.26
  --- EmailTest.java	30 Mar 2004 02:42:06 -0000	1.25
  +++ EmailTest.java	8 Jun 2004 14:48:35 -0000	1.26
  @@ -88,6 +88,17 @@
         info.setValue("jsmith@apache.org");
         valueTest(info, true);
      }
  +    
  +   /**
  +    * Tests the email validation with numeric domains.
  +    */
  +    public void testEmailWithNumericAddress() throws ValidatorException {
  +        ValueBean info = new ValueBean();
  +        info.setValue("someone@[216.109.118.76]");
  +        valueTest(info, true);
  +        info.setValue("someone@yahoo.com");
  +        valueTest(info, true);
  +    }
   
       /**
        * Tests the e-mail validation.
  
  
  
  1.17      +4 -3      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.16
  retrieving revision 1.17
  diff -u -r1.16 -r1.17
  --- ValidatorTestSuite.java	4 Apr 2004 13:53:25 -0000	1.16
  +++ ValidatorTestSuite.java	8 Jun 2004 14:48:35 -0000	1.17
  @@ -40,6 +40,7 @@
       public static Test suite() {
          TestSuite suite = new TestSuite();
   
  +       suite.addTest(BSFTest.suite());
          suite.addTest(RequiredNameTest.suite());
          suite.addTest(RequiredIfTest.suite());
          suite.addTest(MultipleTests.suite());
  
  
  
  1.1                  jakarta-commons/validator/src/test/org/apache/commons/validator/BSFTest.java
  
  Index: BSFTest.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/validator/src/test/org/apache/commons/validator/BSFTest.java,v 1.1 2004/06/08 14:48:35 husted Exp $
   * $Revision: 1.1 $
   * $Date: 2004/06/08 14:48:35 $
   *
   * ====================================================================
   * Copyright 2001-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package org.apache.commons.validator;
  
  import java.io.IOException;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.xml.sax.SAXException;
  
  /**                                                       
   * Performs Validation Test for BSF validations.
   */                                                       
  public class BSFTest extends TestCommon {
  
     /**
      * The key used to retrieve the validator action.
      */
     protected static String ACTION = "bsf";
  
  
     public BSFTest(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[] {BSFTest.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(BSFTest.class);
     }
  
     /**
      * Load <code>ValidatorResources</code> from 
      * validator-BSF.xml.
      */
     protected void setUp() throws IOException, SAXException {
        loadResources("validator-bsf.xml");
     }
  
     protected void tearDown() {
     }
  
     /**
      * Tests the BSF validation.
      */
     public void testBSF() throws ValidatorException {
        // Create bean to run test on.
        ValueBean info = new ValueBean();
  
        info.setValue("foo");
        valueTest(info, "bsfForm", true);
        info.setValue("foobar");
        valueTest(info, "bsfForm", false);
     }
     
     /**
      * Tests BSF validation test for a numeric range
      */
     public void testBSF_numeric() throws ValidatorException {
        // Create bean to run test on.
        ValueBean info = new ValueBean();
  
        info.setValue("12");
        valueTest(info, "bsfForm-numeric",true);
        info.setValue("123");
        valueTest(info, "bsfForm-numeric",false);
        info.setValue("foobar");
        valueTest(info, "bsfForm-numeric",false);
     }
     
     /**
      * Tests BSF validation on nested objects
      */
      /*
      FIXME; Where is ObjectBean imported?
     public void testBSF_nested() throws ValidatorException {
        // Create bean to run test on.
        ObjectBean info = new ObjectBean();
        ValueBean kid = new ValueBean();
        kid.setValue("foo");
        info.setObject(kid);
        
        objectTest(info, "bsfForm-nested",true);
        kid.setValue("foobar");
        objectTest(info, "bsfForm-nested",false);
     }
    */
  
  
     /**
      * Utlity class to run a test on a value.
      *
      * @param info	Value to run test on.
      * @param passed	Whether or not the test is expected to pass.
      */
     private void valueTest(ValueBean info, String form, boolean passed) throws ValidatorException {
        // Construct validator based on the loaded resources 
        // and the form key
        Validator validator = new Validator(resources, form);
        // add the name bean to the validator as a resource 
        // for the validations to be performed on.
        validator.setParameter(Validator.BEAN_PARAM, info);
        //validator.setParameter(BSFValidator.LANGUAGE_PARAM, "beanshell");
  
        // 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 result = results.getValidatorResult("value");
  
        assertNotNull(ACTION + " value ValidatorResult should not be null.", result);
        assertTrue("Value "+info.getValue()+" ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION));
        assertTrue("Value "+info.getValue()+"ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION)));
      }
      
      /**
      * Utlity class to run a test on an object.
      *
      * @param info	Object to run test on.
      * @param passed	Whether or not the test is expected to pass.
      */
      /*
      FIXME: Where is ObjectBean imported?
     private void objectTest(ObjectBean info, String form, boolean passed) throws ValidatorException {
        // Construct validator based on the loaded resources 
        // and the form key
        Validator validator = new Validator(resources, form);
        // add the name bean to the validator as a resource 
        // for the validations to be performed on.
        validator.setParameter(Validator.BEAN_PARAM, info);
        //validator.setParameter(BSFValidator.LANGUAGE_PARAM, "beanshell");
  
        // 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 result = results.getValidatorResult("object");
  
        assertNotNull(ACTION + " object ValidatorResult should not be null.", result);
        assertTrue("Object "+info.getObject()+" ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION));
        assertTrue("Object "+info.getObject()+"ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION)));
      }
      */
  }                                                         
  
  
  

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