40f9e669804589187e074878897d4bc4c9196cf3
[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 package org.wamblee.usermgt;
17
18 import org.wamblee.usermgt.UserMgtException.Reason;
19
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      * Convenience pattern for an id.
29      */
30     public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
31
32     /**
33      * Convenience pattern for a password consisting of at least 6
34      * 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     /**
80      * DOCUMENT ME!
81      *
82      * @param aName DOCUMENT ME!
83      *
84      * @throws UserMgtException DOCUMENT ME!
85      */
86     public void validate(String aName) throws UserMgtException {
87         if (!aName.matches(pattern)) {
88             throw new UserMgtException(reason, message);
89         }
90     }
91 }