KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > framework > CommandValidator


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.cli.framework;
25
26 import java.util.HashMap JavaDoc;
27 import java.util.Vector JavaDoc;
28 import java.util.Iterator JavaDoc;
29
30 /**
31  * The <code>CommandValidator</code> object validates the command line
32  * against the CLI Specification
33  * @version $Revision: 1.3 $
34  */

35 public class CommandValidator {
36     // Regular expression for command name
37
private static final String JavaDoc COMMAND_NAME_REGEXP = "^[a-z\\-][a-z0-9\\-\\_\\ ]*$";
38     
39     // Regular expression for option name
40
private static final String JavaDoc OPTION_NAME_REGEXP = "^\\w[-\\w]*";
41     
42     // Regular expression for number of operands in quantifier
43
private static final String JavaDoc NUMBER_OF_OPERANDS_QUANTIFIER_REGEXP = "^[\\*\\?\\+]";
44     
45     // Regular expression for number of operands in numbers
46
private static final String JavaDoc NUMBER_OF_OPERANDS_REGEXP = "^\\+?\\d+";
47     
48     // Regular expression for number of operands in inclusion
49
private static final String JavaDoc NUMBER_OF_OPERANDS_INCLUSION_REGEXP = "^\\d+\\-\\d+";
50     
51     // BOOLEAN STRING
52
private static final String JavaDoc BOOLEAN = "boolean";
53     
54     // TRUE STRING
55
private static final String JavaDoc TRUE = "true";
56     
57     // FALSE STRING
58
private static final String JavaDoc FALSE = "false";
59     
60     //PLUS STRING
61
private static final String JavaDoc PLUS = "+";
62     
63     //QUESTION_MARK STRING
64
private static final String JavaDoc QUESTION_MARK = "?";
65     
66     //DASH STRING
67
private static final String JavaDoc DASH = "-";
68     
69     /** Creates a new Command Validator */
70     public CommandValidator()
71     {
72     }
73     
74     
75     /** Validates the options and operands entered in the command line.
76      * @param validCommand - the valid command from command specification
77      * @param optionsList - the list of options in the command line
78      * @param operandsList - the list of operands in the command
79      * @throws CommandValidationException if there is an error during
80      * validation
81      */

82     public void validateCommandAndOptions(final ValidCommand validCommand,
83                                           final HashMap JavaDoc optionsList,
84                                           final Vector JavaDoc operands)
85         throws CommandValidationException
86     {
87         if (validCommand == null || optionsList == null || operands == null)
88         {
89             throw new CommandValidationException(getLocalizedString("CouldNotValidateCommand",
90                                                                     null));
91         }
92         
93         verifyCommandName(validCommand.getName());
94
95         //check for the number of operands
96
verifyNumberOfOperands(validCommand.getNumberOfOperands(),
97                                operands.size());
98         
99         verifyOptionsAreValid(validCommand, optionsList);
100         
101         verifyRequiredOptions(validCommand.getRequiredOptions(), optionsList,
102                               validCommand.getName());
103         
104         verifyDeprecatedOptions(validCommand.getDeprecatedOptions(),
105                                 optionsList, validCommand.getName());
106         
107         //check for boolean required options
108
verifyBooleanOptions(validCommand.getRequiredOptions(), optionsList);
109     }
110     
111     
112     /** Verify that the command name must be in lower-cose and that it
113      * must be alpha-numeric.
114      * @param commandName - name of command
115      * @return true if command name is valid
116      * @throw CommandValidationException if command name is invalid
117      */

118     private boolean verifyCommandName(final String JavaDoc commandName)
119         throws CommandValidationException
120     {
121         if (!commandName.matches(COMMAND_NAME_REGEXP))
122         {
123             throw new CommandValidationException(getLocalizedString("InvalidCommand",
124                                                  new Object JavaDoc[] {commandName}));
125         }
126         return true;
127     }
128     
129     
130     /** Verify that the option name is valid. Option name must be
131      * alpha-numeric with either a "-" between words.
132      * @param optionName - name of option
133      * @return true if option name is valid otherwise return false.
134      */

135     private boolean verifyOptionName(final String JavaDoc optionName)
136     {
137         return optionName.matches(OPTION_NAME_REGEXP);
138     }
139     
140     
141     /** verify if the deprecated options are entered in the command line
142      * @param deprecatedOptionsList - list of deprecated options
143      * @param optionsList - list of options enterd in command line
144      * @return true if all deprecated options are entered
145      * @throws CommandValidationException if deprecated option is not
146      * in command line.
147      */

148     private boolean verifyDeprecatedOptions(final Vector JavaDoc deprecatedOptionsList,
149                                             final HashMap JavaDoc optionsList,
150                                             final String JavaDoc commandName)
151         throws CommandValidationException
152     {
153         for (int ii=0; ii<deprecatedOptionsList.size(); ii++)
154         {
155             final String JavaDoc optionName =
156             ((ValidOption)deprecatedOptionsList.get(ii)).getName();
157             if (!verifyOptionName(optionName))
158             {
159                 throw new CommandValidationException(getLocalizedString("InvalidOption",
160                                                      new Object JavaDoc[] {optionName,
161                                                      commandName}));
162             }
163             
164             //check if deprecated option name is in the optionsList
165
if (optionsList.containsKey(optionName))
166             {
167                 CLILogger.getInstance().printWarning(getLocalizedString("OptionDeprecated",
168                                                      new Object JavaDoc[] {optionName}));
169             }
170         }
171         return true;
172     }
173     
174     
175     /** verify if the required options are entered in the command line
176      * @param requiredOptionsList - list of required options
177      * @param optionsList - list of options enterd in command line
178      * @return true if all required options are entered
179      * @throws CommandValidationException if required option is not
180      * in command line.
181      */

182     private boolean verifyRequiredOptions(final Vector JavaDoc requiredOptionsList,
183                                           final HashMap JavaDoc optionsList,
184                                           final String JavaDoc commandName)
185         throws CommandValidationException
186     {
187         for (int ii=0; ii<requiredOptionsList.size(); ii++)
188         {
189             final String JavaDoc optionName =
190             ((ValidOption)requiredOptionsList.get(ii)).getName();
191             if (!verifyOptionName(optionName))
192             {
193                 throw new CommandValidationException(getLocalizedString("InvalidOption",
194                                                      new Object JavaDoc[] {optionName,
195                                                      commandName}));
196             }
197             
198             //check if required option name is in the optionsList and if it has a
199
//default value
200
if (!optionsList.containsKey(optionName) &&
201                 !((ValidOption)requiredOptionsList.get(ii)).hasDefaultValue())
202             {
203                 throw new CommandValidationException(getLocalizedString("OptionIsRequired",
204                                                      new Object JavaDoc[] {optionName}));
205             }
206         }
207         return true;
208     }
209     
210     
211     /** verify options from the command line are valid
212      * also verifies that option values is not null.
213      * @param validCommand - the valid command object to check for valid options
214      * @param optionsList - list of options entered in command line
215      * @return true if all options are valid
216      * @throws CommandValidationException if options is not valid
217      */

218     private boolean verifyOptionsAreValid(final ValidCommand validCommand,
219                                           final HashMap JavaDoc optionsList)
220         throws CommandValidationException
221     {
222
223         final Iterator JavaDoc iter = (optionsList.keySet()).iterator();
224         while (iter.hasNext())
225         {
226             final String JavaDoc optionName = (String JavaDoc)iter.next();
227             if (!(validCommand.hasValidOption(optionName) ||
228                   validCommand.hasRequiredOption(optionName) ||
229                   validCommand.hasDeprecatedOption(optionName)))
230             {
231                 throw new CommandValidationException(getLocalizedString("InvalidOption",
232                                                      new Object JavaDoc[] {optionName,
233                                                      validCommand.getName()}));
234             }
235             //verify that the option value is not null
236
//if null then throw an CommandValidationException
237
if (optionsList.get(optionName) == null)
238                 throw new CommandValidationException(getLocalizedString("OptionValueNotSpecified",
239                           new Object JavaDoc[] {optionName} ));
240         }
241         return true;
242     }
243
244
245     /** verify that options with type boolean contains the value true or false
246      * @param baseOptionsList - base options list to check if options is boolean
247      * @param optionsList - list of options entered in command line
248      * @return true if options with type boolean contains true or false
249      * @throws CommandValidationException if boolean options contains contains
250      * values other than true or false.
251      */

252     private boolean verifyBooleanOptions(final Vector JavaDoc baseOptionsList,
253                                          final HashMap JavaDoc optionsList)
254         throws CommandValidationException
255     {
256         for (int ii=0; ii<baseOptionsList.size(); ii++)
257         {
258             final String JavaDoc optionType = ((ValidOption)baseOptionsList.get(ii)).getType();
259             final String JavaDoc optionName = ((ValidOption)baseOptionsList.get(ii)).getName();
260             if (optionType.compareToIgnoreCase(BOOLEAN) == 0 &&
261                 optionsList.containsKey(optionName))
262             {
263                 //if the option type is boolean, the value should be
264
//either true or false
265
final String JavaDoc optionValue =
266                 ((String JavaDoc)optionsList.get(optionName)).trim();
267                 if (optionValue == null ||
268                     !(optionValue.compareToIgnoreCase(TRUE) == 0 ||
269                       optionValue.compareToIgnoreCase(FALSE) == 0 ) )
270                 {
271                     throw new CommandValidationException(getLocalizedString(
272                                                              "OptionIsBoolean",
273                                                              new Object JavaDoc[] {optionName}));
274                 }
275                 
276             }
277         }
278         return true;
279     }
280     
281     
282     /** verify the number of operands is compliant with CLI specification
283      * the number of operands should follow the following convention:
284      * * - 0 or more
285      * ? - 0 or 1
286      * + - 1 or more
287      * number - the number of operand
288      * +number - the number of operand should be equal to or
289      * greater than the number
290      * number1-number2 - the number of operand should be greater than
291      * or equal to number1 and less than or equal to
292      * number2
293      * @param numberOfOperand - the number of operand specified in CLI spec
294      * @param operandSize - the exact number of operands
295      * @return true if the operand follow the convention
296      * @throws CommandValidationException if the operand does not follow
297      * the convention
298      */

299     private boolean verifyNumberOfOperands(final String JavaDoc numberOfOperands,
300                                            final int operandSize)
301         throws CommandValidationException
302     {
303         if (numberOfOperands.matches(NUMBER_OF_OPERANDS_QUANTIFIER_REGEXP))
304         {
305             //if numberofoperand is ?, then the operand size should be 0 or 1
306
if (numberOfOperands.equals(QUESTION_MARK) &&
307                 (operandSize < 0 || operandSize > 1))
308             {
309                 throw new CommandValidationException(getLocalizedString("ZeroOrOneOperand", null));
310             }
311             else if (numberOfOperands.equals(PLUS) && !(operandSize >= 1) )
312             {
313                 throw new CommandValidationException(getLocalizedString("GreaterThanOneOperand", null));
314             }
315         }
316         else if (numberOfOperands.matches(NUMBER_OF_OPERANDS_REGEXP))
317         {
318             if (numberOfOperands.startsWith(PLUS) &&
319                 Integer.parseInt(numberOfOperands.substring(1)) > operandSize)
320             {
321                 throw new CommandValidationException(getLocalizedString(
322                                                      "GreaterOrEqualToOperand",
323                                                      new Object JavaDoc[] {
324                                                      numberOfOperands.substring(1)}));
325             }
326             else if (!numberOfOperands.startsWith(PLUS) &&
327                      Integer.parseInt(numberOfOperands) == 1 &&
328                      operandSize < 1)
329             {
330                 throw new CommandValidationException(getLocalizedString("OperandIsRequired", null));
331             }
332             else if (!numberOfOperands.startsWith(PLUS) &&
333                      Integer.parseInt(numberOfOperands) != operandSize)
334             {
335                 throw new CommandValidationException(getLocalizedString("EqualToOperand",
336                                                      new Object JavaDoc[] {numberOfOperands}));
337             }
338         }
339         else if (numberOfOperands.matches(NUMBER_OF_OPERANDS_INCLUSION_REGEXP))
340         {
341             final int index = numberOfOperands.indexOf(DASH);
342             final int min = Integer.parseInt(numberOfOperands.substring(0,index));
343             final int max = Integer.parseInt(numberOfOperands.substring(index+1));
344             if (min > operandSize || max < operandSize)
345             {
346                 throw new CommandValidationException(getLocalizedString(
347                                                      "BetweenNumberOperand",
348                                                      new Object JavaDoc[] {
349                                                      String.valueOf(min),
350                                                      String.valueOf(max)}));
351             }
352         }
353         else
354         {
355             throw new CommandValidationException(getLocalizedString(
356                                                  "InvalidSytanxForNumberOfOperands",
357                                                  new Object JavaDoc[] {numberOfOperands}));
358         }
359         return true;
360     }
361
362
363     /**
364      * returns the localized string from framework's LocalStrings.properties.
365      * Calls the LocalStringsManagerFactory.getFrameworkLocalStringsManager()
366      * method, returns "Key not found" if it cannot find the key
367      * @param key, the string to be localized
368      * @param toInsert, the strings to be inserted in the placeholders
369      */

370     private String JavaDoc getLocalizedString(String JavaDoc key, Object JavaDoc[] toInsert)
371     {
372         try
373         {
374             final LocalStringsManager lsm =
375             LocalStringsManagerFactory.getFrameworkLocalStringsManager();
376             if (toInsert == null)
377                 return lsm.getString(key);
378             else
379                 return lsm.getString(key, toInsert);
380         }
381         catch (CommandValidationException cve)
382         {
383             return LocalStringsManager.DEFAULT_STRING_VALUE;
384         }
385     }
386
387     
388 }
389
Popular Tags