9d1421b46951adcce86899ffa51993c55020c044
[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  * @author Erik Brakkee
25  */
26 public class RegexpNameValidator implements NameValidator {
27     
28     /**
29      * Convenience pattern for an id. 
30      */
31     public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
32     
33     /**
34      * Convenience pattern for a password consisting of at least 6 characters. 
35      */
36     public static final String PASSWORD_PATTERN = ".{6}.*";
37     
38     /**
39      * Pattern to use. 
40      */
41     private String pattern;
42     
43     /**
44      * Reason to use when validation fails. 
45      */
46     private Reason reason; 
47     
48     /**
49      * Message to report. 
50      */
51     private String message; 
52     
53     /**
54      * Validates a regular expression. 
55      * @param aPattern Pattern that names must comply to. 
56      * @param aReason Reason to report when validation fails. 
57      * @param aMessage Message to report. 
58      */
59     public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) { 
60         pattern = aPattern; 
61         reason = aReason;
62         message = aMessage; 
63     }
64     
65     /**
66      * Convenience constructor with all string parameters. Useful for configuration 
67      * in Spring. 
68      * @param aPattern Pattern to use.
69      * @param aReason Reason. 
70      * @param aMessage Message. 
71      */
72     public RegexpNameValidator(String aPattern, String aReason, String aMessage) { 
73         this(aPattern, Reason.valueOf(aReason), aMessage);
74     }
75
76     /* (non-Javadoc)
77      * @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
78      */
79     public void validate(String aName) throws UserMgtException {
80         if ( !aName.matches(pattern)) { 
81             throw new UserMgtException(reason, message); 
82         }
83     }
84
85 }