commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rlel...@apache.org
Subject cvs commit: jakarta-commons/validator/src/test/org/apache/commons/validator UrlTest.java
Date Fri, 02 May 2003 18:28:20 GMT
rleland     2003/05/02 11:28:19

  Modified:    validator/src/share/org/apache/commons/validator
                        UrlValidator.java
               validator/src/test/org/apache/commons/validator UrlTest.java
  Log:
  Breakup Urlvalidator method isvalid() into
  validators for each part of URL and
  add more test cases.
  
  Revision  Changes    Path
  1.4       +136 -96   jakarta-commons/validator/src/share/org/apache/commons/validator/UrlValidator.java
  
  Index: UrlValidator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/share/org/apache/commons/validator/UrlValidator.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- UrlValidator.java	30 Apr 2003 21:51:05 -0000	1.3
  +++ UrlValidator.java	2 May 2003 18:28:18 -0000	1.4
  @@ -62,6 +62,7 @@
   package org.apache.commons.validator;
   
   import java.io.Serializable;
  +import java.util.HashSet;
   
   import org.apache.oro.text.perl.Perl5Util;
   
  @@ -74,6 +75,30 @@
    * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date:
03/07/02,
    * http://javascript.internet.com. However, this validation now bears little resemblance
    * to the PHP original.</p>
  + * <pre>
  + *   Example of usage:
  + *   Construct a UrlValidator with valid schemes of "http", and "https".
  + *
  + *    String[] schemes = {"http","https"}.
  + *    Urlvalidator urlValidator = new Urlvalidator(schemes);
  + *    if (urlValidator.isValid("ftp")) {
  + *       System.out.println("url is valid");
  + *    } else {
  + *       System.out.println("url is invalid");
  + *    }
  + *
  + *    prints "url is invalid"
  + *   If instead the default constructor is used.
  + *
  + *    Urlvalidator urlValidator = new Urlvalidator();
  + *    if (urlValidator.isValid("ftp")) {
  + *       System.out.println("url is valid");
  + *    } else {
  + *       System.out.println("url is invalid");
  + *    }
  + *
  + *   prints out "url is valid"
  + *  </pre>
    * @see
    *   <a href='http://www.ietf.org/rfc/rfc2396.txt' >
    *  Uniform Resource Identifiers (URI): Generic Syntax
  @@ -118,59 +143,55 @@
      private static final String atomPat = ValidatorUtil.getDelimitedRegExp("(" + atom +
")");
      private static final String alphaPat = ValidatorUtil.getDelimitedRegExp("^[" + alphaChars
+ "]");
   
  -   /**
  -    * Allow a double slash in the path componet such that
  -    * path//file is treated as path/file.
  -    */
  -   public static final String OPTION_ALLOW_2_SLASH = "allow2Slash";
  -   /**
  -    * Don't allow a fragment in a url. A fragment is usually indicated
  -    * by a '#' character and follows a query.
  -    */
  -   public static final String OPTION_NO_FRAGMENT = "noFragment";
  -
      // Non static fields
      private boolean allow2Slash = false;
  +   private boolean allowAllScheme = false;
      private boolean noFragment = false;
  +   private HashSet allowedSchemeSet;
  +   protected String[] defaultSchemeSet = {"http", "https", "ftp"};
   
      /**
  -    * Construct a UrlValidator with default behaviour.
       */
      public UrlValidator() {
  -
  +      this(null);
      }
   
      /**
       * Behavour of validation is modified by passing in several strings options:
  -    * @param options Pass in one or more of the OPTION_XXXX predefined strings
  -    *   to change the validation behavour.
  -    *   allow2Slash - Allows double '/' characters in the path  component
  -    *   noFragment - If the noFragment option is included then fragments are flagged as
illegal.
  +    * @param schemes Pass in one or more url scheme to consider valid, passing in
  +    *        a null will default to "http,https,ftp" being valid.
  +    *        If a non-null schemes is specified then all valid schemes must
  +    *        be specified. Setting the allowAllScheme option to true will
  +    *        ignore the contents of schemes.
       **/
  -   public UrlValidator(String[] options) {
  -      int optionsIndex = 0;
  -      while ((options != null) && (optionsIndex < options.length)) {
  -         String option = options[optionsIndex];
  -         if ((option != null) && (option.equals(OPTION_ALLOW_2_SLASH))) {
  -            allow2Slash = true;
  -         }
  -         if ((option != null) && (option.equals(OPTION_NO_FRAGMENT))) {
  -            noFragment = true;
  -         }
  -         optionsIndex++;
  -      }
  -
  +   public UrlValidator(String[] schemes) {
  +      this(schemes, false, false, false);
      }
   
      /**
       * Behavour of validation is modified by passing in options:
  -    *   @param allow2Slash If True, allows double '/' characters in the path  component
  -    *   @param noFragment If true, fragments are flagged as illegal.
  +    *   @param allowAllScheme If true, allows all validly formatted schemes. [false]
  +    *   @param allow2Slash If true, allows double '/' characters in the path  component,
[false]
  +    *   @param noFragment If true, fragments are flagged as illegal.[false]
       **/
  -
  -   public UrlValidator(boolean allow2Slash, boolean noFragment) {
  +   public UrlValidator(String[] schemes, boolean allowAllScheme, boolean allow2Slash, boolean
noFragment) {
  +      this.allowAllScheme = allowAllScheme;
         this.allow2Slash = allow2Slash;
         this.noFragment = noFragment;
  +      if (!this.allowAllScheme) {
  +         if (schemes == null) {
  +            this.allowedSchemeSet = new HashSet(defaultSchemeSet.length);
  +            for (int sIndex = 0; sIndex < defaultSchemeSet.length; sIndex++) {
  +               this.allowedSchemeSet.add(defaultSchemeSet[sIndex]);
  +            }
  +
  +         } else if (schemes != null) {
  +            this.allowedSchemeSet = new HashSet(schemes.length);
  +            for (int sIndex = 0; sIndex < schemes.length; sIndex++) {
  +               this.allowedSchemeSet.add(schemes[sIndex]);
  +            }
  +         }
  +      }
   
      }
   
  @@ -184,13 +205,7 @@
      public boolean isValid(String value) {
         boolean bValid = true;
         try {
  -
  -
            Perl5Util matchUrlPat = new Perl5Util();
  -         Perl5Util matchSchemePat = new Perl5Util();
  -
  -         Perl5Util matchPathPat = new Perl5Util();
  -         Perl5Util matchQueryPat = new Perl5Util();
            Perl5Util matchAsciiPat = new Perl5Util();
   
            if (!matchAsciiPat.match(legalAsciiPat, value)) {
  @@ -200,69 +215,32 @@
            // Check the whole url address structure
            bValid = matchUrlPat.match(urlPat, value);
   
  -         if (value.endsWith(".")) {
  -            bValid = false;
  -         }
  -
            // Check the scheme component of the url address
            if (bValid) {
  -
  -            String scheme = matchUrlPat.group(PARSE_URL_SCHEME);
  -
  -            // See if "scheme" is valid
  -            bValid = matchSchemePat.match(schemePat, scheme);
  +            bValid = isValidScheme(matchUrlPat.group(PARSE_URL_SCHEME));
            }
   
            // Check the domain component of the url address
            if (bValid) {
               // Check the whole url address structure
               bValid = isValidAuthority(matchUrlPat.group(PARSE_URL_AUTHORITY));
  +         }
   
  -            if (bValid) {
  -
  -               // Check the path component of the url address
  -               if (bValid) {
  -
  -                  String path = matchUrlPat.group(PARSE_URL_PATH);
  -                  // See if "path" is valid
  -                  bValid = matchPathPat.match(pathPat, path);
  -                  if (bValid) {  //Shouldn't end with a '/'
  -                     bValid = (path.lastIndexOf("/") < (path.length() - 1));
  -                  }
  -                  if (bValid) {
  -                     int slash2Count = countToken("//", path);
  -                     if (!allow2Slash) {
  -                        bValid = (slash2Count == 0);
  -                     }
  -                     if (bValid) {
  -                        int slashCount = countToken("/", path);
  -                        int dot2Count = countToken("..", path);
  -                        if (dot2Count > 0) {
  -                           bValid = ((slashCount - slash2Count - 1) > dot2Count);
  -                        }
  -                     }
  -                  }
  -
  -               }
  -            }
  -            // Check the query component of the url address
  -            if (bValid) {
  +         // Check the path component of the url address
  +         if (bValid) {
  +            bValid = isValidPath(matchUrlPat.group(PARSE_URL_PATH));
  +         }
   
  -               String query = matchUrlPat.group(PARSE_URL_QUERY);
  -               if (null != query) {
  -                  // See if "query" is valid
  -                  bValid = matchQueryPat.match(queryPat, query);
  -               }
  -            }
  -            // Check the fragment component of the url address
  -            if (bValid) {
  -               String fragment = matchUrlPat.group(PARSE_URL_FRAGMENT);
  -               if (null != fragment) {
  -                  bValid = (noFragment == false);
  -               }
  -            }
  +         // Check the query component of the url address
  +         if (bValid) {
  +            bValid = isValidQuery(matchUrlPat.group(PARSE_URL_QUERY));
  +         }
   
  +         // Check the fragment component of the url address
  +         if (bValid) {
  +            bValid = isValidFragment(matchUrlPat.group(PARSE_URL_FRAGMENT));
            }
  +
         } catch (Exception e) {
            bValid = false;
         }
  @@ -270,7 +248,26 @@
         return bValid;
      }
   
  -   boolean isValidAuthority(String authority) {
  +   /**
  +    * Validate scheme. If schemes[] was initialized to a non null,
  +    * then only those scheme's are allowed.  Note this is slightly different
  +    * than for the Constructor.
  +    * @param scheme The scheme to validate.
  +    * @return   true is valid.
  +    */
  +   protected boolean isValidScheme(String scheme) {
  +      Perl5Util matchSchemePat = new Perl5Util();
  +      // See if "scheme" is valid
  +      boolean bValid = matchSchemePat.match(schemePat, scheme);
  +      if (bValid) {
  +         if (allowedSchemeSet != null) {
  +            bValid = allowedSchemeSet.contains(scheme);
  +         }
  +      }
  +      return bValid;
  +   }
  +
  +   protected boolean isValidAuthority(String authority) {
         boolean bValid = true;
         Perl5Util matchAuthorityPat = new Perl5Util();
         Perl5Util matchIPV4Pat = new Perl5Util();
  @@ -368,6 +365,49 @@
         }
         return bValid;
      }
  +
  +   protected boolean isValidPath(String path) {
  +      Perl5Util matchPathPat = new Perl5Util();
  +      boolean bValid = true;
  +      // See if "path" is bValid
  +      bValid = matchPathPat.match(pathPat, path);
  +      if (bValid) {  //Shouldn't end with a '/'
  +         bValid = (path.lastIndexOf("/") < (path.length() - 1));
  +      }
  +      if (bValid) {
  +         int slash2Count = countToken("//", path);
  +         if (!allow2Slash) {
  +            bValid = (slash2Count == 0);
  +         }
  +         if (bValid) {
  +            int slashCount = countToken("/", path);
  +            int dot2Count = countToken("..", path);
  +            if (dot2Count > 0) {
  +               bValid = ((slashCount - slash2Count - 1) > dot2Count);
  +            }
  +         }
  +      }
  +      return bValid;
  +   }
  +
  +   protected boolean isValidQuery(String query) {
  +      Perl5Util matchQueryPat = new Perl5Util();
  +      boolean bValid = true;
  +      if (null != query) {
  +         // See if "query" is bValid
  +         bValid = matchQueryPat.match(queryPat, query);
  +      }
  +      return bValid;
  +   }
  +
  +   protected boolean isValidFragment(String fragment) {
  +      boolean bValid = true;
  +      if (null != fragment) {
  +         bValid = (noFragment == false);
  +      }
  +      return bValid;
  +   }
  +
   
      protected static int countToken(String token, String target) {
         int tokenIndex = 0;
  
  
  
  1.3       +128 -70   jakarta-commons/validator/src/test/org/apache/commons/validator/UrlTest.java
  
  Index: UrlTest.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/validator/src/test/org/apache/commons/validator/UrlTest.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- UrlTest.java	1 May 2003 02:40:22 -0000	1.2
  +++ UrlTest.java	2 May 2003 18:28:19 -0000	1.3
  @@ -83,6 +83,9 @@
         }
      }
   
  +   private boolean printStatus = false;
  +   private boolean printIndex = false;//print index that indicates current scheme,host,port,path,
query test were using.
  +
      public UrlTest(String testName) {
         super(testName);
      }
  @@ -101,17 +104,49 @@
      }
   
      public void testIsValid() {
  -      testIsValid(testParts,null);
  +      testIsValid(testUrlParts, true,false,false);
         System.out.println("\nTesting options ....");
  -      String[] options = {UrlValidator.OPTION_ALLOW_2_SLASH,UrlValidator.OPTION_NO_FRAGMENT};
         setUp();
  -      testIsValid(testPartsOptions,options);
  +      testIsValid(testUrlPartsOptions, true,true,true);
      }
   
  -   public void testIsValid(Object[] testObjects,String[] options) {
  -      UrlValidator urlVal = new UrlValidator(options);
  -      final int statusPerLine = 6;
  +   public void testIsValidScheme() {
  +      if (printStatus) {
  +         System.out.print("\n testIsValidScheme() ");
  +      }
  +      String[] schemes = {"http", "gopher"};
  +      UrlValidator urlVal = new UrlValidator(schemes,false,false,false);
  +      for (int sIndex = 0; sIndex < testScheme.length; sIndex++) {
  +         TestPair testPair = testScheme[sIndex];
  +         boolean result = urlVal.isValidScheme(testPair.item);
  +         assertEquals(testPair.item, testPair.valid, result);
  +         if (printStatus) {
  +            if (result == testPair.valid) {
  +               System.out.print('.');
  +            } else {
  +               System.out.print('X');
  +            }
  +         }
  +      }
  +      if (printStatus) {
  +         System.out.println();
  +      }
  +
  +   }
  +
  +   /**
  +    * Create set of tests by taking the testUrlXXX arrays and
  +    * running through all possible permutations of their combinations.
  +    *
  +    * @param testObjects Used to create a url.
  +    */
  +   public void testIsValid(Object[] testObjects, boolean allow2Slash, boolean noFragment,boolean
allScheme) {
  +      UrlValidator urlVal = new UrlValidator(null, allow2Slash,noFragment,allScheme);
  +      int statusPerLine = 60;
         int printed = 0;
  +      if (printIndex)  {
  +         statusPerLine = 6;
  +      }
         do {
            StringBuffer testBuffer = new StringBuffer();
            boolean expected = true;
  @@ -123,15 +158,27 @@
            }
            String url = testBuffer.toString();
            boolean result = urlVal.isValid(url);
  -         //System.out.print(testPartsIndextoString());
            assertEquals(url, expected, result);
  -         printed++;
  -         if (printed == statusPerLine) {
  -            //System.out.println();
  -            printed = 0;
  +         if (printStatus) {
  +            if (printIndex) {
  +               System.out.print(testPartsIndextoString());
  +            } else {
  +               if (result == expected) {
  +                  System.out.print('.');
  +               } else {
  +                  System.out.print('X');
  +               }
  +            }
  +            printed++;
  +            if (printed == statusPerLine) {
  +               System.out.println();
  +               printed = 0;
  +            }
            }
         } while (incrementTestPartsIndex(testPartsIndex, testObjects));
  -      //System.out.println();
  +      if (printStatus) {
  +         System.out.println();
  +      }
      }
   
      static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) {
  @@ -184,8 +231,9 @@
         UrlTest fct = new UrlTest("url test");
         fct.setUp();
         fct.testIsValid();
  +      fct.testIsValidScheme();
      }
  -
  +   //-------------------- Test data for creating a composite URL
      /**
       * The data given below approximates the 4 parts of a URL
       * <scheme>://<authority><path>?<query> except that the port
number
  @@ -194,40 +242,42 @@
       * all of which must be individually valid for the entire URL to be considered
       * valid.
       */
  -   TestPair[] testScheme = {new TestPair("http://", true),
  -                            new TestPair("ftp://", true),
  -                            new TestPair("h3t://", true),
  -                            new TestPair("3ht://", false),
  -                            new TestPair("http:/", false),
  -                            new TestPair("http:", false),
  -                            new TestPair("http/", false),
  -                            new TestPair("", true)};
  -   TestPair[] testAuthority = {new TestPair("www.google.com", true),
  -                               new TestPair("go.com", true),
  -                               new TestPair("go.au", true),
  -                               new TestPair("0.0.0.0", true),
  -                               new TestPair("255.255.255.255", true),
  -                               new TestPair("256.256.256.256", false),
  -                               new TestPair("255.com", true),
  -                               new TestPair("1.2.3.4.5", false),
  -                               new TestPair("1.2.3.4.", false),
  -                               new TestPair("1.2.3", false),
  -                               new TestPair(".1.2.3.4", false),
  -                               new TestPair("go.a", false),
  -                               new TestPair("go.a1a", true),
  -                               new TestPair("go.1aa", false),
  -                               new TestPair("aaa.", false),
  -                               new TestPair(".aaa", false),
  -                               new TestPair("aaa", false),
  -                               new TestPair("", false)
  +   TestPair[] testUrlScheme = {new TestPair("http://", true),
  +                               new TestPair("ftp://", true),
  +                               new TestPair("h3t://", true),
  +                               new TestPair("3ht://", false),
  +                               new TestPair("http:/", false),
  +                               new TestPair("http:", false),
  +                               new TestPair("http/", false),
  +                               new TestPair("://", false),
  +                               new TestPair("", true)};
  +
  +   TestPair[] testUrlAuthority = {new TestPair("www.google.com", true),
  +                                  new TestPair("go.com", true),
  +                                  new TestPair("go.au", true),
  +                                  new TestPair("0.0.0.0", true),
  +                                  new TestPair("255.255.255.255", true),
  +                                  new TestPair("256.256.256.256", false),
  +                                  new TestPair("255.com", true),
  +                                  new TestPair("1.2.3.4.5", false),
  +                                  new TestPair("1.2.3.4.", false),
  +                                  new TestPair("1.2.3", false),
  +                                  new TestPair(".1.2.3.4", false),
  +                                  new TestPair("go.a", false),
  +                                  new TestPair("go.a1a", true),
  +                                  new TestPair("go.1aa", false),
  +                                  new TestPair("aaa.", false),
  +                                  new TestPair(".aaa", false),
  +                                  new TestPair("aaa", false),
  +                                  new TestPair("", false)
      };
  -   TestPair[] testPort = {new TestPair(":80", true),
  -                          new TestPair(":65535", true),
  -                          new TestPair(":0", true),
  -                          new TestPair("", true),
  -                          new TestPair(":-1", false),
  -                          new TestPair(":65636", true),
  -                          new TestPair(":65a", false)
  +   TestPair[] testUrlPort = {new TestPair(":80", true),
  +                             new TestPair(":65535", true),
  +                             new TestPair(":0", true),
  +                             new TestPair("", true),
  +                             new TestPair(":-1", false),
  +                             new TestPair(":65636", true),
  +                             new TestPair(":65a", false)
      };
      TestPair[] testPath = {new TestPair("/test1", true),
                             new TestPair("/t123", true),
  @@ -241,29 +291,37 @@
                             new TestPair("/test1//file", false)
      };
      //Test allow2slash, noFragment
  -   TestPair[] testPathOptions = {new TestPair("/test1", true),
  -                                 new TestPair("/t123", true),
  -                                 new TestPair("/$23", true),
  -                                 new TestPair("/..", false),
  -                                 new TestPair("/../", false),
  -                                 new TestPair("/test1/",false),
  -                                 new TestPair("/#", false),
  -                                 new TestPair("", false),
  -                                 new TestPair("/test1/file", true),
  -                                 new TestPair("/t123/file", true),
  -                                 new TestPair("/$23/file", true),
  -                                 new TestPair("/../file", false),
  -                                 new TestPair("/..//file", false),
  -                                 new TestPair("/test1//file", true),
  -                                 new TestPair("/#/file", false)
  +   TestPair[] testUrlPathOptions = {new TestPair("/test1", true),
  +                                    new TestPair("/t123", true),
  +                                    new TestPair("/$23", true),
  +                                    new TestPair("/..", false),
  +                                    new TestPair("/../", false),
  +                                    new TestPair("/test1/", false),
  +                                    new TestPair("/#", false),
  +                                    new TestPair("", false),
  +                                    new TestPair("/test1/file", true),
  +                                    new TestPair("/t123/file", true),
  +                                    new TestPair("/$23/file", true),
  +                                    new TestPair("/../file", false),
  +                                    new TestPair("/..//file", false),
  +                                    new TestPair("/test1//file", true),
  +                                    new TestPair("/#/file", false)
      };
   
  -   TestPair[] testQuery = {new TestPair("?action=view", true),
  -                           new TestPair("?action=edit&mode=up", true),
  -                           new TestPair("", true)
  +   TestPair[] testUrlQuery = {new TestPair("?action=view", true),
  +                              new TestPair("?action=edit&mode=up", true),
  +                              new TestPair("", true)
      };
   
  -   Object[] testParts = {testScheme, testAuthority, testPort, testPath, testQuery};
  -   Object[] testPartsOptions = {testScheme, testAuthority, testPort, testPathOptions, testQuery};
  +   Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery};
  +   Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions,
testUrlQuery};
      int[] testPartsIndex = {0, 0, 0, 0, 0};
  +
  +   //---------------- Test data for individual url parts ----------------
  +   TestPair[] testScheme = {new TestPair("http", true),
  +                            new TestPair("ftp", false),
  +                            new TestPair("httpd", false),
  +                            new TestPair("telnet", false)};
  +
  +
   }
  
  
  

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


Mime
View raw message