KickJava   Java API By Example, From Geeks To Geeks.

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


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.Iterator JavaDoc;
27 import java.util.StringTokenizer JavaDoc;
28
29
30 /**
31  * The <code>CLIMain</code> contains a main that calls the appropriate
32  * objects in the CLI framework and invokes the command object.
33  * @version $Revision: 1.4 $
34  */

35 public class CLIMain
36 {
37     // Help command and options for asadmin
38
private static final String JavaDoc HelpCommandAndOptions = "help|--help|-[?]";
39     private static final String JavaDoc VERSION_OPTION = "-V";
40     private static final String JavaDoc VERSION_COMMAND = "version";
41
42
43     public static void invokeCLI(String JavaDoc cmdline, InputsAndOutputs io)
44         throws CommandException, CommandValidationException
45     {
46         InputsAndOutputs.setInstance(io);
47         String JavaDoc[] args = splitStringToArray(cmdline);
48         invokeCommand(args);
49     }
50
51     
52     public static void main(String JavaDoc[] args)
53     {
54         long startTime = 0;
55         boolean time = false;
56         if (System.getProperty("com.sun.appserv.cli.timing") != null) {
57            time = true;
58            startTime = System.currentTimeMillis();
59         }
60         
61         try
62         {
63             invokeCommand(args);
64             if (time) {
65                 CLILogger.getInstance().printDebugMessage(
66                     "Command execution time: " +
67                     (System.currentTimeMillis() - startTime) + " ms");
68             }
69             System.exit(0);
70         }
71         catch (CommandValidationException cve)
72         {
73             CLILogger.getInstance().printExceptionStackTrace(cve);
74             CLILogger.getInstance().printError(cve.getLocalizedMessage());
75             System.exit(1);
76         }
77         catch (CommandException ce)
78         {
79             CLILogger.getInstance().printExceptionStackTrace(ce);
80             CLILogger.getInstance().printError(ce.getLocalizedMessage());
81             System.exit(1);
82         }
83         catch (Throwable JavaDoc ex)
84         {
85             CLILogger.getInstance().printExceptionStackTrace(ex);
86             CLILogger.getInstance().printError(ex.getLocalizedMessage());
87             System.exit(1);
88         }
89     }
90
91     
92
93     /**
94      * This is the important bulk of reading the xml, validating, creating
95      * command vi command factory and invoke the command.
96      */

97     public static void invokeCommand(String JavaDoc[] args)
98         throws CommandException, CommandValidationException
99     {
100         ValidCommand validCommand = null;
101
102         try
103         {
104             //read CLI descriptor
105
final CLIDescriptorsReader cliDescriptorsReader = CLIDescriptorsReader.getInstance();
106
107             if (args.length < 1)
108             {
109                 cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.DONT_SERIALIZE);
110                     //pass in null as the command Name. The default command
111
//shall be returned, else an exception is thrown.
112
validCommand = cliDescriptorsReader.getCommand(null);
113                     //set args[0] to the default command.
114
args = new String JavaDoc[] {cliDescriptorsReader.getDefaultCommand()};
115             }
116             else
117             {
118                 //check if command is -V, as stated in the CLIP that
119
//-V is supported and it is the same as version command
120
if (args[0].equals(VERSION_OPTION))
121                     args[0] = VERSION_COMMAND;
122
123                 //cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILE);
124
cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILES);
125
126                 //get the validCommand object from CLI descriptor
127
validCommand = cliDescriptorsReader.getCommand(args[0]);
128             }
129             setCommandLocalizedProperty(cliDescriptorsReader.getProperties());
130
131                 //check if command is help then throw the HelpException to
132
//display the manpage or usage-text
133
if (args[0].matches(HelpCommandAndOptions))
134                 throw new HelpException(args);
135
136
137
138             checkValidCommand(validCommand, args[0]);
139
140                 //parse the command line arguments
141
final CommandLineParser clp = new CommandLineParser(args, validCommand);
142
143                 //validate the command line arguments with the validCommand object
144
final CommandValidator commandValidator = new CommandValidator();
145             commandValidator.validateCommandAndOptions(validCommand,
146                                                        clp.getOptionsList(),
147                                                        clp.getOperands());
148         
149                 //creates the command object using command factory
150
final Command command = CommandFactory.createCommand(
151                                         validCommand, clp.getOptionsList(),
152                                         clp.getValidEnvironmentOptions(),
153                                         clp.getOperands());
154                 //invoke the command
155
command.runCommand();
156             return;
157         }
158         catch (HelpException he)
159         {
160             invokeHelpClass(he.getHelpClassName(), he.getCommandName(), he.getUsageText(),he.isShell());
161         }
162         catch (CommandValidationException cve )
163         {
164                 //rethrow CommandValidationException with Usage Text
165
throw new CommandValidationException(getUsageTextFromValidCommand(validCommand)
166                                                  + "\n" + cve.getLocalizedMessage());
167         }
168
169     }
170     
171
172     /**
173      * This method invokes the help command class.
174      * If help command clss is invalid then the usage text is displayed.
175      */

176     private static void invokeHelpClass(String JavaDoc helpClassName,
177                                         String JavaDoc helpCommandName,
178                                         String JavaDoc commandUsageText,
179                                         boolean isShell)
180         throws CommandException
181     {
182         try
183         {
184             Command helpCommand = null;
185             Class JavaDoc helpClass = Class.forName(helpClassName);
186             helpCommand = (Command)helpClass.newInstance();
187             helpCommand.setName(helpCommandName);
188             if (helpCommandName != null)
189                 helpCommand.setOperands(new java.util.Vector JavaDoc(java.util.Arrays.asList(
190                                         new String JavaDoc[]{helpCommandName})));
191             if(isShell){
192                 helpCommand.setOption("isMultiMode","true");
193                 final String JavaDoc interactiveVal = (String JavaDoc)CommandEnvironment.getInstance().
194                                           getEnvironments().get("interactive");
195                     //set the interactive mode
196
helpCommand.setOption("interactive",
197                                   interactiveVal==null?"true":interactiveVal);
198             }
199             helpCommand.runCommand();
200         }
201         catch (Exception JavaDoc e)
202         {
203             if (commandUsageText == null)
204                 throw new CommandException(getLocalizedString("NoUsageText",
205                                            new Object JavaDoc[] {helpCommandName}));
206             else
207                 CLILogger.getInstance().printMessage(getLocalizedString("Usage",
208                                                      new Object JavaDoc[]{commandUsageText}));
209         }
210     }
211     
212     /**
213      * This method returns the usages text from validCommand object
214      * @param validCommand
215      * @return usage text
216      */

217     private static String JavaDoc getUsageTextFromValidCommand(final ValidCommand validCommand)
218     {
219         if (validCommand != null && validCommand.getUsageText() != null)
220         {
221             return getLocalizedString("Usage", new Object JavaDoc[]{validCommand.getUsageText()});
222         }
223         return "";
224     }
225
226
227     /**
228      * check if validCommand is null
229      */

230     private static void checkValidCommand(ValidCommand validCommand,
231                                           String JavaDoc commandName)
232         throws CommandValidationException
233     {
234         if (validCommand == null)
235         {
236             throw new CommandValidationException(getLocalizedString(
237                                                  "InvalidCommand",
238                                                  new Object JavaDoc[] {commandName}));
239         }
240
241     }
242
243     /**
244      * sets the localized property in the command module
245      * @params Iterator - iterator containing the localized properties
246      */

247     private static void setCommandLocalizedProperty(Iterator JavaDoc localizePropertiesIter)
248         throws CommandValidationException
249     {
250         LocalStringsManagerFactory.setCommandLocalStringsManagerProperties(
251             localizePropertiesIter);
252     }
253
254
255     /**
256      * returns the localized string from the properties file
257      * Calls the LocalStringsManagerFactory.getFrameworkLocalStringsManager()
258      * method, returns "Key not found" if it cannot find the key
259      * @param key, the string to be localized
260      * @param toInsert, the strings to be inserted in the placeholders
261      */

262     private static String JavaDoc getLocalizedString(String JavaDoc key, Object JavaDoc[] toInsert)
263     {
264         try
265         {
266             final LocalStringsManager lsm = LocalStringsManagerFactory.getFrameworkLocalStringsManager();
267             if (toInsert == null)
268                 return lsm.getString(key);
269             else
270                 return lsm.getString(key, toInsert);
271         }
272         catch (CommandValidationException cve)
273         {
274             return LocalStringsManager.DEFAULT_STRING_VALUE;
275         }
276     }
277
278
279     /**
280      * This method will split the string to array of string separted by space(s)
281      * If there is a quote " around the string, then the string will not be
282      * splitted. For example, if the string is: abcd efg "hij klm", the string
283      * array will contain abcd|efg|hij klm|
284      * @param line - string to be converted
285      * @return - string array
286      * @throws CommandException
287      */

288     private static String JavaDoc[] splitStringToArray( String JavaDoc line )
289         throws CommandException
290     {
291         final CLITokenizer cliTokenizer = new CLITokenizer(line, " ");
292         String JavaDoc[] strArray = new String JavaDoc[cliTokenizer.countTokens()];
293         int ii=0;
294         while (cliTokenizer.hasMoreTokens())
295         {
296             strArray[ii++] = cliTokenizer.nextTokenWithoutEscapeAndQuoteChars();
297             CLILogger.getInstance().printDebugMessage("CLIToken = [" + strArray[ii-1] +"]");
298         }
299         return strArray;
300     }
301
302 }
303
Popular Tags