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