01: /*
02: * ParameterTypes.java
03: *
04: * Copyright (C) 2007 Ferran Busquets
05: *
06: * This program is free software: you can redistribute it and/or modify
07: * it under the terms of the GNU General Public License as published by
08: * the Free Software Foundation, either version 3 of the License, or
09: * any later version.
10: *
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: * GNU General Public License for more details.
15: *
16: * You should have received a copy of the GNU General Public License
17: * along with this program. If not, see <http://www.gnu.org/licenses/>.
18: *
19: */
20:
21: package org.naturalcli;
22:
23: import java.util.Collection;
24:
25: import org.naturalcli.parameters.DefaultParameterTypes;
26:
27: /**
28: * This class checks parameters values against their types.
29: *
30: * @author Ferran Busquets
31: *
32: * @see IParameterType
33: */
34: public class ParameterValidator {
35:
36: /** Parameter types for the validation */
37: private Collection<IParameterType> parameterTypes;
38:
39: /**
40: * Creates a new instance of <code>ParameterValidator</code> with default parameter types
41: */
42: public ParameterValidator() {
43: this .parameterTypes = DefaultParameterTypes.createSet();
44: }
45:
46: /**
47: * Creates a new instance of <code>ParameterValidator</code>
48: *
49: * @param parameterTypes the parameter types collection
50: */
51: public ParameterValidator(Collection<IParameterType> parameterTypes) {
52: this .parameterTypes = parameterTypes;
53: }
54:
55: /**
56: * Validate a parameter value for a type
57: *
58: * @param value the parameter value
59: * @param type the parameter type name
60: * @return <code>null</code> if validated, otherwise a error message
61: * @throws UnknownParameterType raised if the parameter is not found
62: */
63: public String validate(String value, String type)
64: throws UnknownParameterType {
65: IParameterType pt = getParameterType(type);
66: // If not found throw exception
67: if (pt == null)
68: throw new UnknownParameterType(type);
69: // Validate the parameter
70: return pt.validationMessage(value);
71: }
72:
73: /**
74: * Gets the parameter type for the given type name
75: *
76: * @param type the type name
77: * @return the paramter type object
78: */
79: public IParameterType getParameterType(String type) {
80: IParameterType pt = null;
81: // Look for the parameter type
82: for (IParameterType s : this.parameterTypes) {
83: if (s.getParameterTypeName().equals(type)) {
84: pt = s;
85: break;
86: }
87: }
88: return pt;
89: }
90: }
|