View Javadoc

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 org.apache.commons.validator.routines.InetAddressValidator;
20  import org.apache.oro.text.perl.Perl5Util;
21  
22  import java.util.regex.Matcher;
23  import java.util.regex.Pattern;
24  
25  /**
26   * <p>Perform email validations.</p>
27   * <p>
28   * This class is a Singleton; you can retrieve the instance via the getInstance() method.
29   * </p>
30   * <p>
31   * Based on a script by <a href="mailto:stamhankar@hotmail.com">Sandeep V. Tamhankar</a>
32   * http://javascript.internet.com
33   * </p>
34   * <p>
35   * This implementation is not guaranteed to catch all possible errors in an email address.
36   * For example, an address like nobody@noplace.somedog will pass validator, even though there
37   * is no TLD "somedog"
38   * </p>.
39   *
40   * @version $Revision: 595771 $ $Date: 2007-11-16 18:42:24 +0000 (Fri, 16 Nov 2007) $
41   * @since Validator 1.1
42   * @deprecated Use the new EmailValidator in the routines package. This class
43   * will be removed in a future release.
44   */
45  public class EmailValidator {
46  
47      private static final String SPECIAL_CHARS = "\\000-\\037\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]\\177";
48      private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
49      private static final String QUOTED_USER = "(\"[^\"]*\")";
50      private static final String ATOM = VALID_CHARS + '+';
51      private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")";
52  
53      // Each pattern must be surrounded by /
54      private static final String LEGAL_ASCII_PATTERN = "/^[\\000-\\177]+$/";
55      private static final String EMAIL_PATTERN = "/^(.+)@(.+)$/";
56      private static final String IP_DOMAIN_PATTERN = "^\\[(.*)\\]$";
57      private static final String TLD_PATTERN = "/^([a-zA-Z]+)$/";
58              
59      private static final String USER_PATTERN = "/^\\s*" + WORD + "(\\." + WORD + ")*$/";
60      private static final String DOMAIN_PATTERN = "/^" + ATOM + "(\\." + ATOM + ")*\\s*$/";
61      private static final String ATOM_PATTERN = "/(" + ATOM + ")/";
62  
63      /**
64       * Singleton instance of this class.
65       */
66      private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator();
67  
68      /**
69       * Returns the Singleton instance of this validator.
70       * @return singleton instance of this validator.
71       */
72      public static EmailValidator getInstance() {
73          return EMAIL_VALIDATOR;
74      }
75  
76      /**
77       * Protected constructor for subclasses to use.
78       */
79      protected EmailValidator() {
80          super();
81      }
82  
83      /**
84       * <p>Checks if a field has a valid e-mail address.</p>
85       *
86       * @param email The value validation is being performed on.  A <code>null</code>
87       * value is considered invalid.
88       * @return true if the email address is valid.
89       */
90      public boolean isValid(String email) {
91  	return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email);
92      }
93  
94      /**
95       * Returns true if the domain component of an email address is valid.
96       * @param domain being validated.
97       * @return true if the email address's domain is valid.
98       */
99      protected boolean isValidDomain(String domain) {
100         boolean symbolic = false;
101 
102         // see if domain is an IP address in brackets
103         Pattern ipDomainPattern = Pattern.compile(IP_DOMAIN_PATTERN);
104         Matcher ipDomainMatcher = ipDomainPattern.matcher(domain);
105 
106         if (ipDomainMatcher.matches()) {
107             InetAddressValidator inetAddressValidator =
108                     InetAddressValidator.getInstance();
109             if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) {
110                 return true;
111             }
112         } else {
113             // Domain is symbolic name
114             Perl5Util domainMatcher = new Perl5Util();
115             symbolic = domainMatcher.match(DOMAIN_PATTERN, domain);
116         }
117 
118         if (symbolic) {
119             if (!isValidSymbolicDomain(domain)) {
120                 return false;
121             }
122         } else {
123             return false;
124         }
125 
126         return true;
127     }
128 
129     /**
130      * Returns true if the user component of an email address is valid.
131      * @param user being validated
132      * @return true if the user name is valid.
133      */
134     protected boolean isValidUser(String user) {
135         Perl5Util userMatcher = new Perl5Util();
136         return userMatcher.match(USER_PATTERN, user);
137     }
138 
139     /**
140      * Validates an IP address. Returns true if valid.
141      * @param ipAddressMatcher Pattren matcher
142      * @return true if the ip address is valid.
143      */
144     protected boolean isValidIpAddress(Perl5Util ipAddressMatcher) {
145         for (int i = 1; i <= 4; i++) {
146             String ipSegment = ipAddressMatcher.group(i);
147             if (ipSegment == null || ipSegment.length() <= 0) {
148                 return false;
149             }
150 
151             int iIpSegment = 0;
152 
153             try {
154                 iIpSegment = Integer.parseInt(ipSegment);
155             } catch(NumberFormatException e) {
156                 return false;
157             }
158 
159             if (iIpSegment > 255) {
160                 return false;
161             }
162 
163         }
164         return true;
165     }
166 
167     /**
168      * Validates a symbolic domain name.  Returns true if it's valid.
169      * @param domain symbolic domain name
170      * @return true if the symbolic domain name is valid.
171      */
172     protected boolean isValidSymbolicDomain(String domain) {
173         String[] domainSegment = new String[10];
174         boolean match = true;
175         int i = 0;
176         Perl5Util atomMatcher = new Perl5Util();
177         while (match) {
178             match = atomMatcher.match(ATOM_PATTERN, domain);
179             if (match) {
180                 domainSegment[i] = atomMatcher.group(1);
181                 int l = domainSegment[i].length() + 1;
182                 domain =
183                         (l >= domain.length())
184                         ? ""
185                         : domain.substring(l);
186 
187                 i++;
188             } 
189         }
190 
191         int len = i;
192         
193         // Make sure there's a host name preceding the domain.
194         if (len < 2) {
195             return false;
196         }
197         
198         // TODO: the tld should be checked against some sort of configurable 
199         // list
200         String tld = domainSegment[len - 1];
201         if (tld.length() > 1) {
202             Perl5Util matchTldPat = new Perl5Util();
203             if (!matchTldPat.match(TLD_PATTERN, tld)) {
204                 return false;
205             }
206         } else {
207             return false;
208         }
209 
210         return true;
211     }
212     /**
213      *   Recursively remove comments, and replace with a single space.  The simpler
214      *   regexps in the Email Addressing FAQ are imperfect - they will miss escaped
215      *   chars in atoms, for example.
216      *   Derived From    Mail::RFC822::Address
217      * @param emailStr The email address
218      * @return address with comments removed.
219     */
220     protected String stripComments(String emailStr)  {
221      String input = emailStr;
222      String result = emailStr;
223      String commentPat = "s/^((?:[^\"\\\\]|\\\\.)*(?:\"(?:[^\"\\\\]|\\\\.)*\"(?:[^\"\\\\]|\111111\\\\.)*)*)\\((?:[^()\\\\]|\\\\.)*\\)/$1 /osx";
224      Perl5Util commentMatcher = new Perl5Util();
225      result = commentMatcher.substitute(commentPat,input);
226      // This really needs to be =~ or Perl5Matcher comparison
227      while (!result.equals(input)) {
228         input = result;
229         result = commentMatcher.substitute(commentPat,input);
230      }
231      return result;
232 
233     }
234 }