Coverage Report - org.apache.commons.validator.UrlValidator
 
Classes in this File Line Coverage Branch Coverage Complexity
UrlValidator
90%
111/123
89%
75/84
7.182
 
 1  
 /*
 2  
  * Licensed to the Apache Software Foundation (ASF) under one or more
 3  
  * contributor license agreements.  See the NOTICE file distributed with
 4  
  * this work for additional information regarding copyright ownership.
 5  
  * The ASF licenses this file to You under the Apache License, Version 2.0
 6  
  * (the "License"); you may not use this file except in compliance with
 7  
  * the License.  You may obtain a copy of the License at
 8  
  *
 9  
  *      http://www.apache.org/licenses/LICENSE-2.0
 10  
  *
 11  
  * Unless required by applicable law or agreed to in writing, software
 12  
  * distributed under the License is distributed on an "AS IS" BASIS,
 13  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14  
  * See the License for the specific language governing permissions and
 15  
  * limitations under the License.
 16  
  */
 17  
 package org.apache.commons.validator;
 18  
 
 19  
 import java.io.Serializable;
 20  
 import java.util.Arrays;
 21  
 import java.util.HashSet;
 22  
 import java.util.Set;
 23  
 import java.util.regex.Matcher;
 24  
 import java.util.regex.Pattern;
 25  
 
 26  
 import org.apache.commons.validator.routines.InetAddressValidator;
 27  
 import org.apache.commons.validator.util.Flags;
 28  
 
 29  
 /**
 30  
  * <p>Validates URLs.</p>
 31  
  * Behavour of validation is modified by passing in options:
 32  
  * <ul>
 33  
  * <li>ALLOW_2_SLASHES - [FALSE]  Allows double '/' characters in the path
 34  
  * component.</li>
 35  
  * <li>NO_FRAGMENT- [FALSE]  By default fragments are allowed, if this option is
 36  
  * included then fragments are flagged as illegal.</li>
 37  
  * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
 38  
  * considered valid schemes.  Enabling this option will let any scheme pass validation.</li>
 39  
  * </ul>
 40  
  *
 41  
  * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
 42  
  * http://javascript.internet.com. However, this validation now bears little resemblance
 43  
  * to the php original.</p>
 44  
  * <pre>
 45  
  *   Example of usage:
 46  
  *   Construct a UrlValidator with valid schemes of "http", and "https".
 47  
  *
 48  
  *    String[] schemes = {"http","https"}.
 49  
  *    UrlValidator urlValidator = new UrlValidator(schemes);
 50  
  *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
 51  
  *       System.out.println("url is valid");
 52  
  *    } else {
 53  
  *       System.out.println("url is invalid");
 54  
  *    }
 55  
  *
 56  
  *    prints "url is invalid"
 57  
  *   If instead the default constructor is used.
 58  
  *
 59  
  *    UrlValidator urlValidator = new UrlValidator();
 60  
  *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
 61  
  *       System.out.println("url is valid");
 62  
  *    } else {
 63  
  *       System.out.println("url is invalid");
 64  
  *    }
 65  
  *
 66  
  *   prints out "url is valid"
 67  
  *  </pre>
 68  
  *
 69  
  * @see
 70  
  * <a href="http://www.ietf.org/rfc/rfc2396.txt">
 71  
  *  Uniform Resource Identifiers (URI): Generic Syntax
 72  
  * </a>
 73  
  *
 74  
  * @version $Revision: 1739358 $
 75  
  * @since Validator 1.1
 76  
  * @deprecated Use the new UrlValidator in the routines package. This class
 77  
  * will be removed in a future release.
 78  
  */
 79  
 @Deprecated
 80  
 public class UrlValidator implements Serializable {
 81  
 
 82  
     private static final long serialVersionUID = 24137157400029593L;
 83  
 
 84  
     /**
 85  
      * Allows all validly formatted schemes to pass validation instead of
 86  
      * supplying a set of valid schemes.
 87  
      */
 88  
     public static final int ALLOW_ALL_SCHEMES = 1 << 0;
 89  
 
 90  
     /**
 91  
      * Allow two slashes in the path component of the URL.
 92  
      */
 93  
     public static final int ALLOW_2_SLASHES = 1 << 1;
 94  
 
 95  
     /**
 96  
      * Enabling this options disallows any URL fragments.
 97  
      */
 98  
     public static final int NO_FRAGMENTS = 1 << 2;
 99  
 
 100  
     private static final String ALPHA_CHARS = "a-zA-Z";
 101  
 
 102  
 // NOT USED   private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d";
 103  
 
 104  
     private static final String SPECIAL_CHARS = ";/@&=,.?:+$";
 105  
 
 106  
     private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
 107  
 
 108  
     // Drop numeric, and  "+-." for now
 109  
     private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\.";
 110  
 
 111  
     private static final String ATOM = VALID_CHARS + '+';
 112  
 
 113  
     /**
 114  
      * This expression derived/taken from the BNF for URI (RFC2396).
 115  
      */
 116  
     private static final String URL_REGEX =
 117  
             "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
 118  
     //                                                                      12            3  4          5       6   7        8 9
 119  1
     private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
 120  
 
 121  
     /**
 122  
      * Schema/Protocol (ie. http:, ftp:, file:, etc).
 123  
      */
 124  
     private static final int PARSE_URL_SCHEME = 2;
 125  
 
 126  
     /**
 127  
      * Includes hostname/ip and port number.
 128  
      */
 129  
     private static final int PARSE_URL_AUTHORITY = 4;
 130  
 
 131  
     private static final int PARSE_URL_PATH = 5;
 132  
 
 133  
     private static final int PARSE_URL_QUERY = 7;
 134  
 
 135  
     private static final int PARSE_URL_FRAGMENT = 9;
 136  
 
 137  
     /**
 138  
      * Protocol (ie. http:, ftp:,https:).
 139  
      */
 140  1
     private static final Pattern SCHEME_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*");
 141  
 
 142  
     private static final String AUTHORITY_REGEX =
 143  
        "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?";
 144  
     //                                                                            1                          2  3       4
 145  1
     private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);
 146  
 
 147  
     private static final int PARSE_AUTHORITY_HOST_IP = 1;
 148  
 
 149  
     private static final int PARSE_AUTHORITY_PORT = 2;
 150  
 
 151  
     /**
 152  
      * Should always be empty.
 153  
      */
 154  
     private static final int PARSE_AUTHORITY_EXTRA = 3;
 155  
 
 156  1
     private static final Pattern PATH_PATTERN = Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;]*)?$");
 157  
 
 158  1
     private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$");
 159  
 
 160  1
     private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
 161  
 
 162  1
     private static final Pattern DOMAIN_PATTERN =
 163  
             Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$");
 164  
 
 165  1
     private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$");
 166  
 
 167  1
     private static final Pattern ATOM_PATTERN = Pattern.compile("^(" + ATOM + ").*?$");
 168  
 
 169  1
     private static final Pattern ALPHA_PATTERN = Pattern.compile("^[" + ALPHA_CHARS + "]");
 170  
 
 171  
     /**
 172  
      * Holds the set of current validation options.
 173  
      */
 174  
     private final Flags options;
 175  
 
 176  
     /**
 177  
      * The set of schemes that are allowed to be in a URL.
 178  
      */
 179  5
     private final Set<String> allowedSchemes = new HashSet<String>();
 180  
 
 181  
     /**
 182  
      * If no schemes are provided, default to this set.
 183  
      */
 184  5
     protected String[] defaultSchemes = {"http", "https", "ftp"};
 185  
 
 186  
     /**
 187  
      * Create a UrlValidator with default properties.
 188  
      */
 189  
     public UrlValidator() {
 190  0
         this(null);
 191  0
     }
 192  
 
 193  
     /**
 194  
      * Behavior of validation is modified by passing in several strings options:
 195  
      * @param schemes Pass in one or more url schemes to consider valid, passing in
 196  
      *        a null will default to "http,https,ftp" being valid.
 197  
      *        If a non-null schemes is specified then all valid schemes must
 198  
      *        be specified. Setting the ALLOW_ALL_SCHEMES option will
 199  
      *        ignore the contents of schemes.
 200  
      */
 201  
     public UrlValidator(String[] schemes) {
 202  1
         this(schemes, 0);
 203  1
     }
 204  
 
 205  
     /**
 206  
      * Initialize a UrlValidator with the given validation options.
 207  
      * @param options The options should be set using the public constants declared in
 208  
      * this class.  To set multiple options you simply add them together.  For example,
 209  
      * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
 210  
      */
 211  
     public UrlValidator(int options) {
 212  0
         this(null, options);
 213  0
     }
 214  
 
 215  
     /**
 216  
      * Behavour of validation is modified by passing in options:
 217  
      * @param schemes The set of valid schemes.
 218  
      * @param options The options should be set using the public constants declared in
 219  
      * this class.  To set multiple options you simply add them together.  For example,
 220  
      * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
 221  
      */
 222  5
     public UrlValidator(String[] schemes, int options) {
 223  5
         this.options = new Flags(options);
 224  
 
 225  5
         if (this.options.isOn(ALLOW_ALL_SCHEMES)) {
 226  2
             return;
 227  
         }
 228  
 
 229  3
         if (schemes == null) {
 230  0
             schemes = this.defaultSchemes;
 231  
         }
 232  
 
 233  3
         this.allowedSchemes.addAll(Arrays.asList(schemes));
 234  3
     }
 235  
 
 236  
     /**
 237  
      * <p>Checks if a field has a valid url address.</p>
 238  
      *
 239  
      * @param value The value validation is being performed on.  A <code>null</code>
 240  
      * value is considered invalid.
 241  
      * @return true if the url is valid.
 242  
      */
 243  
     public boolean isValid(String value) {
 244  75606
         if (value == null) {
 245  0
             return false;
 246  
         }
 247  75606
         if (!LEGAL_ASCII_PATTERN.matcher(value).matches()) {
 248  0
            return false;
 249  
         }
 250  
 
 251  
         // Check the whole url address structure
 252  75606
         Matcher urlMatcher = URL_PATTERN.matcher(value);
 253  75606
         if (!urlMatcher.matches()) {
 254  0
             return false;
 255  
         }
 256  
 
 257  75606
         if (!isValidScheme(urlMatcher.group(PARSE_URL_SCHEME))) {
 258  28350
             return false;
 259  
         }
 260  
 
 261  47256
         if (!isValidAuthority(urlMatcher.group(PARSE_URL_AUTHORITY))) {
 262  39375
             return false;
 263  
         }
 264  
 
 265  7881
         if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) {
 266  2520
             return false;
 267  
         }
 268  
 
 269  5361
         if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) {
 270  0
             return false;
 271  
         }
 272  
 
 273  5361
         if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) {
 274  630
             return false;
 275  
         }
 276  
 
 277  4731
         return true;
 278  
     }
 279  
 
 280  
     /**
 281  
      * Validate scheme. If schemes[] was initialized to a non null,
 282  
      * then only those scheme's are allowed.  Note this is slightly different
 283  
      * than for the constructor.
 284  
      * @param scheme The scheme to validate.  A <code>null</code> value is considered
 285  
      * invalid.
 286  
      * @return true if valid.
 287  
      */
 288  
     protected boolean isValidScheme(String scheme) {
 289  75610
         if (scheme == null) {
 290  18900
             return false;
 291  
         }
 292  
 
 293  56710
         if (!SCHEME_PATTERN.matcher(scheme).matches()) {
 294  9450
             return false;
 295  
         }
 296  
 
 297  47260
         if (options.isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme)) {
 298  3
             return false;
 299  
         }
 300  
 
 301  47257
         return true;
 302  
     }
 303  
 
 304  
     /**
 305  
      * Returns true if the authority is properly formatted.  An authority is the combination
 306  
      * of hostname and port.  A <code>null</code> authority value is considered invalid.
 307  
      * @param authority Authority value to validate.
 308  
      * @return true if authority (hostname and port) is valid.
 309  
      */
 310  
     protected boolean isValidAuthority(String authority) {
 311  47256
         if (authority == null) {
 312  18831
             return false;
 313  
         }
 314  
 
 315  28425
         InetAddressValidator inetAddressValidator =
 316  
                 InetAddressValidator.getInstance();
 317  
 
 318  28425
         Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority);
 319  28425
         if (!authorityMatcher.matches()) {
 320  0
             return false;
 321  
         }
 322  
 
 323  28425
         boolean hostname = false;
 324  
         // check if authority is IP address or hostname
 325  28425
         String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
 326  28425
         boolean ipV4Address = inetAddressValidator.isValid(hostIP);
 327  
 
 328  28425
         if (!ipV4Address) {
 329  
             // Domain is hostname name
 330  25275
             hostname = DOMAIN_PATTERN.matcher(hostIP).matches();
 331  
         }
 332  
 
 333  
         //rightmost hostname will never start with a digit.
 334  28425
         if (hostname) {
 335  
             // LOW-TECH FIX FOR VALIDATOR-202
 336  
             // TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203
 337  17364
             char[] chars = hostIP.toCharArray();
 338  17364
             int size = 1;
 339  144090
             for(int i=0; i<chars.length; i++) {
 340  126726
                 if(chars[i] == '.') {
 341  26844
                     size++;
 342  
                 }
 343  
             }
 344  17364
             String[] domainSegment = new String[size];
 345  17364
             boolean match = true;
 346  17364
             int segmentCount = 0;
 347  17364
             int segmentLength = 0;
 348  
 
 349  78936
             while (match) {
 350  61572
                 Matcher atomMatcher = ATOM_PATTERN.matcher(hostIP);
 351  61572
                 match = atomMatcher.matches();
 352  61572
                 if (match) {
 353  44208
                     domainSegment[segmentCount] = atomMatcher.group(1);
 354  44208
                     segmentLength = domainSegment[segmentCount].length() + 1;
 355  44208
                     hostIP =
 356  
                             (segmentLength >= hostIP.length())
 357  
                             ? ""
 358  
                             : hostIP.substring(segmentLength);
 359  
 
 360  44208
                     segmentCount++;
 361  
                 }
 362  61572
             }
 363  17364
             String topLevel = domainSegment[segmentCount - 1];
 364  17364
             if (topLevel.length() < 2 || topLevel.length() > 4) { // CHECKSTYLE IGNORE MagicNumber (deprecated code)
 365  4749
                 return false;
 366  
             }
 367  
 
 368  
             // First letter of top level must be a alpha
 369  12615
             if (!ALPHA_PATTERN.matcher(topLevel.substring(0, 1)).matches()) {
 370  3150
                 return false;
 371  
             }
 372  
 
 373  
             // Make sure there's a host name preceding the authority.
 374  9465
             if (segmentCount < 2) {
 375  1584
                 return false;
 376  
             }
 377  
         }
 378  
 
 379  18942
         if (!hostname && !ipV4Address) {
 380  7911
             return false;
 381  
         }
 382  
 
 383  11031
         String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
 384  11031
         if (port != null && !PORT_PATTERN.matcher(port).matches()) {
 385  1575
             return false;
 386  
         }
 387  
 
 388  9456
         String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
 389  9456
         if (!GenericValidator.isBlankOrNull(extra)) {
 390  1575
             return false;
 391  
         }
 392  
 
 393  7881
         return true;
 394  
     }
 395  
 
 396  
     /**
 397  
      * Returns true if the path is valid.  A <code>null</code> value is considered invalid.
 398  
      * @param path Path value to validate.
 399  
      * @return true if path is valid.
 400  
      */
 401  
     protected boolean isValidPath(String path) {
 402  7881
         if (path == null) {
 403  0
             return false;
 404  
         }
 405  
 
 406  7881
         if (!PATH_PATTERN.matcher(path).matches()) {
 407  0
             return false;
 408  
         }
 409  
 
 410  7881
         int slash2Count = countToken("//", path);
 411  7881
         if (options.isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) {
 412  630
             return false;
 413  
         }
 414  
 
 415  7251
         int slashCount = countToken("/", path);
 416  7251
         int dot2Count = countToken("..", path);
 417  7251
         if (dot2Count > 0 && (slashCount - slash2Count - 1) <= dot2Count){
 418  1890
             return false;
 419  
         }
 420  
 
 421  5361
         return true;
 422  
     }
 423  
 
 424  
     /**
 425  
      * Returns true if the query is null or it's a properly formatted query string.
 426  
      * @param query Query value to validate.
 427  
      * @return true if query is valid.
 428  
      */
 429  
     protected boolean isValidQuery(String query) {
 430  5361
         if (query == null) {
 431  2211
             return true;
 432  
         }
 433  
 
 434  3150
         return QUERY_PATTERN.matcher(query).matches();
 435  
     }
 436  
 
 437  
     /**
 438  
      * Returns true if the given fragment is null or fragments are allowed.
 439  
      * @param fragment Fragment value to validate.
 440  
      * @return true if fragment is valid.
 441  
      */
 442  
     protected boolean isValidFragment(String fragment) {
 443  5361
         if (fragment == null) {
 444  4731
             return true;
 445  
         }
 446  
 
 447  630
         return options.isOff(NO_FRAGMENTS);
 448  
     }
 449  
 
 450  
     /**
 451  
      * Returns the number of times the token appears in the target.
 452  
      * @param token Token value to be counted.
 453  
      * @param target Target value to count tokens in.
 454  
      * @return the number of tokens.
 455  
      */
 456  
     protected int countToken(String token, String target) {
 457  22383
         int tokenIndex = 0;
 458  22383
         int count = 0;
 459  58631
         while (tokenIndex != -1) {
 460  36248
             tokenIndex = target.indexOf(token, tokenIndex);
 461  36248
             if (tokenIndex > -1) {
 462  13865
                 tokenIndex++;
 463  13865
                 count++;
 464  
             }
 465  
         }
 466  22383
         return count;
 467  
     }
 468  
 }