01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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: */package org.apache.commons.cli;
17:
18: /**
19: * Validates an Option string.
20: *
21: * @author John Keyes ( john at integralsource.com )
22: */
23: public class OptionValidator {
24:
25: /**
26: * <p>Validates whether <code>opt</code> is a permissable Option
27: * shortOpt. The rules that specify if the <code>opt</code>
28: * is valid are:</p>
29: * <ul>
30: * <li><code>opt</code> is not NULL</li>
31: * <li>a single character <code>opt</code> that is either
32: * ' '(special case), '?', '@' or a letter</li>
33: * <li>a multi character <code>opt</code> that only contains
34: * letters.</li>
35: * </ul>
36: *
37: * @param opt The option string to validate
38: * @throws IllegalArgumentException if the Option is not valid.
39: */
40: static void validateOption(String opt)
41: throws IllegalArgumentException {
42: // check that opt is not NULL
43: if (opt == null) {
44: return;
45: }
46:
47: // handle the single character opt
48: else if (opt.length() == 1) {
49: char ch = opt.charAt(0);
50:
51: if (!isValidOpt(ch)) {
52: throw new IllegalArgumentException(
53: "illegal option value '" + ch + "'");
54: }
55: }
56:
57: // handle the multi character opt
58: else {
59: char[] chars = opt.toCharArray();
60:
61: for (int i = 0; i < chars.length; i++) {
62: if (!isValidChar(chars[i])) {
63: throw new IllegalArgumentException(
64: "opt contains illegal character value '"
65: + chars[i] + "'");
66: }
67: }
68: }
69: }
70:
71: /**
72: * <p>Returns whether the specified character is a valid Option.</p>
73: *
74: * @param c the option to validate
75: * @return true if <code>c</code> is a letter, ' ', '?' or '@',
76: * otherwise false.
77: */
78: private static boolean isValidOpt(char c) {
79: return (isValidChar(c) || (c == ' ') || (c == '?') || c == '@');
80: }
81:
82: /**
83: * <p>Returns whether the specified character is a valid character.</p>
84: *
85: * @param c the character to validate
86: * @return true if <code>c</code> is a letter.
87: */
88: private static boolean isValidChar(char c) {
89: return Character.isJavaIdentifierPart(c);
90: }
91: }
|