fdc220f22d03a8bc24e20e1b1f85d7d7b1daf328
[utils] / security / src / main / java / org / wamblee / usermgt / RegexpNameValidator.java
1 /*
2  * Copyright 2005 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */ 
16
17 package org.wamblee.usermgt;
18
19 import org.wamblee.usermgt.UserMgtException.Reason;
20
21 /**
22  * Validation of names based on a regular expression. 
23  */
24 public class RegexpNameValidator implements NameValidator {
25     
26     /**
27      * Convenience pattern for an id. 
28      */
29     public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
30     
31     /**
32      * Convenience pattern for a password consisting of at least 6 characters. 
33      */
34     public static final String PASSWORD_PATTERN = ".{6}.*";
35     
36     /**
37      * Pattern to use. 
38      */
39     private String _pattern;
40     
41     /**
42      * Reason to use when validation fails. 
43      */
44     private Reason _reason; 
45     
46     /**
47      * Message to report. 
48      */
49     private String _message; 
50     
51     /**
52      * Validates a regular expression. 
53      * @param aPattern Pattern that names must comply to. 
54      * @param aReason Reason to report when validation fails. 
55      * @param aMessage Message to report. 
56      */
57     public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) { 
58         _pattern = aPattern; 
59         _reason = aReason;
60         _message = aMessage; 
61     }
62     
63     /**
64      * Convenience constructor with all string parameters. Useful for configuration 
65      * in Spring. 
66      * @param aPattern Pattern to use.
67      * @param aReason Reason. 
68      * @param aMessage Message. 
69      */
70     public RegexpNameValidator(String aPattern, String aReason, String aMessage) { 
71         this(aPattern, Reason.valueOf(aReason), aMessage);
72     }
73
74     /* (non-Javadoc)
75      * @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
76      */
77     public void validate(String aName) throws UserMgtException {
78         if ( !aName.matches(_pattern)) { 
79             throw new UserMgtException(_reason, _message); 
80         }
81     }
82
83 }