KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > commands > MultiProcessCommand


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 /*
25  * $Id: MultiProcessCommand.java,v 1.4 2006/02/02 00:21:46 pa100654 Exp $
26  */

27
28
29 package com.sun.enterprise.cli.commands;
30
31 import java.lang.Character JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import java.util.Vector JavaDoc;
35
36 import com.sun.enterprise.cli.framework.*;
37
38 /**
39    Creates a multimode environment for executing the commands from a file or
40    by supplying commands interactively. Displays the help message for the
41    command if help is sought.
42 */

43 public class MultiProcessCommand extends S1ASCommand
44 {
45
46     private static final String JavaDoc FILE_OPTION = "file";
47     private static final String JavaDoc PRINTPROMPT_OPTION = "printprompt";
48     private static final String JavaDoc ENCODING_OPTION = "encoding";
49     private static final String JavaDoc EXIT = "exit";
50     private boolean mDone = false;
51     private boolean printPrompt = true;
52     private final String JavaDoc kPromptString = getLocalizedString("AsadminPrompt");
53
54
55     /**
56      * Default constructor to initialize the class.
57      */

58     public MultiProcessCommand()
59     {
60         super();
61     }
62
63     /**
64      * Checks whether options are specified at the command line.
65      * If options are specified, then it validates for the options else
66      * it assumes no options are specified. In MultiProcessCommand without
67      * specifying an option brings up the interactive mode, otherwise it
68      * reads the commands from a file with option specified.
69      */

70     public boolean validateOptions() throws CommandValidationException
71     {
72         printPrompt = getBooleanOption(PRINTPROMPT_OPTION);
73         return super.validateOptions();
74     }
75
76
77     /**
78      * Implements the execution of MultiProcessCommand whether the input
79      * is from a file or from a standard input interactively.
80      * @throws CommandException
81      */

82     public void runCommand() throws CommandException, CommandValidationException
83     {
84         validateOptions();
85         String JavaDoc line = null;
86      
87         try
88         {
89             if (isFileOptionSpecified())
90             {
91                 CLILogger.getInstance().printDebugMessage("file option specified");
92                 checkForFileExistence(null, getOption(FILE_OPTION));
93                 setInputStreamToFile();
94             }
95             else
96                 printExitMessage();
97             line = printPromptAndReadLine();
98
99             while (!isExitLine(line))
100             {
101                 if (isExecutableLine(line))
102                 {
103                     processLine(line);
104                 }
105                 line = printPromptAndReadLine();
106             }
107         }
108         catch ( CommandException ce )
109         {
110             throw ce;
111         }
112         catch ( Exception JavaDoc e )
113         {
114             throw new CommandException(e);
115         }
116     }
117
118
119     
120     /**
121      * Prints the exit message for the mulitprocess command input
122      */

123     private void printExitMessage()
124     {
125         CLILogger.getInstance().printMessage(getLocalizedString("ExitMessage"));
126     }
127
128
129     /**
130      * Prints the prompt to the standard output
131      * Reads the line from the buffered input stream
132      * @return String The line read from the inputstream or file
133      */

134     private String JavaDoc printPromptAndReadLine() throws CommandException
135     {
136         try
137         {
138             if (printPrompt)
139                 InputsAndOutputs.getInstance().getUserOutput().print( kPromptString );
140             String JavaDoc line = InputsAndOutputs.getInstance().getUserInput().getLine();
141             if (line == null && isFileOptionSpecified() == true)
142                 return EXIT;
143             else
144                 return line;
145         }
146         catch (IOException JavaDoc ioe)
147         {
148             throw new CommandException(getLocalizedString("CouldNotPrintOrRead"),
149                                        ioe);
150         }
151     }
152
153     /**
154      * Checks to see if the line is executable, i.e if the line in non-empty and
155      * the line doesnt start with "#"
156      */

157     private boolean isExecutableLine( final String JavaDoc line )
158     {
159         boolean isExecutable = true;
160         if ( line == null )
161         {
162             isExecutable = false;
163         }
164         else if ( line.trim().equals("") ||
165                   line.startsWith("#") ||
166                   line.length() < 1 )
167         {
168             isExecutable = false;
169         }
170         return isExecutable;
171     }
172
173
174     /**
175      * set user input stream
176      * this method assumes that file option is set
177      * @throws CommandException
178      */

179     private void setInputStreamToFile() throws CommandException
180     {
181         try
182         {
183             final String JavaDoc sEncoding = getOption("ENCODING_OPTION");
184             if (sEncoding == null)
185             {
186                 CLILogger.getInstance().printDebugMessage("Set input stream");
187                 InputsAndOutputs.getInstance().setUserInputFile(
188                     getOption(FILE_OPTION));
189             }
190             else
191             {
192                 InputsAndOutputs.getInstance().setUserInputFile(
193                     getOption(FILE_OPTION), sEncoding);
194             }
195         }
196         catch (IOException JavaDoc ioe)
197         {
198             throw new CommandException(getLocalizedString("CouldNotSetInputStream"),
199                                        ioe);
200         }
201     }
202
203
204     /**
205      * This method will split the string to array of string separted by space(s)
206      * If there is a quote " around the string, then the string will not be
207      * splitted. For example, if the string is: abcd efg "hij klm", the string
208      * array will contain abcd|efg|hij klm|
209      * @param line - string to be converted
210      * @return - string array
211      * @throws CommandException
212      */

213     private String JavaDoc[] splitStringToArray( String JavaDoc line )
214         throws CommandException
215     {
216         final CLITokenizer cliTokenizer = new CLITokenizer(line, " ");
217         String JavaDoc[] strArray = new String JavaDoc[cliTokenizer.countTokens()];
218         int ii=0;
219         while (cliTokenizer.hasMoreTokens())
220         {
221             strArray[ii++] = cliTokenizer.nextTokenWithoutEscapeAndQuoteChars();
222             CLILogger.getInstance().printDebugMessage("CLIToken = [" + strArray[ii-1] +"]");
223
224         }
225         return strArray;
226     }
227
228
229     /**
230      * Checks to see if the user supplied an "exit" or "quit"
231      */

232     private boolean isExitLine( final String JavaDoc line )
233     {
234         if ( line == null ||
235              (line != null && (line.equalsIgnoreCase( "exit" ) ||
236                                line.equalsIgnoreCase( "quit" )) ))
237         {
238             return true;
239         }
240         return false;
241     }
242
243
244     /**
245      * Checks to see if the 'file' option is specified
246      * @return boolean returns true if specified else false
247      */

248     private boolean isFileOptionSpecified()
249     {
250         return ( getOption(FILE_OPTION) != null );
251     }
252
253
254     /**
255      * check if validCommand is null
256      */

257     private void checkValidCommand(ValidCommand validCommand,
258                                    String JavaDoc commandName)
259         throws CommandException
260     {
261         if (validCommand == null)
262         {
263             throw new CommandException(getLocalizedString(
264                                            "InvalidCommand", new Object JavaDoc[] {commandName}));
265         }
266
267     }
268
269     /**
270      * Process the input line supplied by the user.
271      * The line is converted to array of args and supplied to CommandFactory
272      **/

273     private void processLine(String JavaDoc line)
274     {
275         ValidCommand validCommand = null;
276         try
277         {
278             String JavaDoc[] commandLine = splitStringToArray(line);
279
280                 //get CLI descriptor instance
281
CLIDescriptorsReader cliDescriptorsReader =
282             CLIDescriptorsReader.getInstance();
283
284                 //get the validCommand object from CLI descriptor
285
validCommand = cliDescriptorsReader.getCommand(
286                 commandLine[0]);
287
288                 //check if command is help then throw the HelpException to
289
//display the manpage or usage-text
290
if (commandLine[0].equals("help")) throw new HelpException(
291                 commandLine.length<2?null:commandLine[1]);
292
293             checkValidCommand(validCommand, commandLine[0]);
294
295                 //parse the command line arguments
296
CommandLineParser clp = new CommandLineParser(commandLine,
297                                                           validCommand);
298
299
300                 //validate the command line arguments with the validCommand object
301
CommandValidator commandValidator = new CommandValidator();
302             commandValidator.validateCommandAndOptions(validCommand,
303                                                        clp.getOptionsList(),
304                                                        clp.getOperands());
305
306                 //creates the command object using command factory
307
Command command = CommandFactory.createCommand(
308                                         validCommand, clp.getOptionsList(),
309                                         clp.getValidEnvironmentOptions(),
310                                         clp.getOperands());
311                 //invoke the command
312
command.runCommand();
313         }
314         catch (HelpException he)
315         {
316             invokeHelpClass(he.getHelpClassName(), he.getCommandName(), he.getUsageText());
317
318         }
319         catch (CommandValidationException cve)
320         {
321             printUsageText(validCommand);
322             CLILogger.getInstance().printExceptionStackTrace(cve);
323             CLILogger.getInstance().printError(cve.getLocalizedMessage());
324         }
325         catch (CommandException ce)
326         {
327             CLILogger.getInstance().printExceptionStackTrace(ce);
328             CLILogger.getInstance().printError(ce.getLocalizedMessage());
329         }
330     }
331
332     /**
333      * This method invokes the help command class.
334      * If help command clss is invalid then the usage text is displayed.
335      */

336     private void invokeHelpClass(String JavaDoc helpClassName,
337                                  String JavaDoc helpCommandName,
338                                  String JavaDoc commandUsageText)
339     {
340         try
341         {
342             Command helpCommand = null;
343             Class JavaDoc helpClass = Class.forName(helpClassName);
344             helpCommand = (Command)helpClass.newInstance();
345             helpCommand.setName(helpCommandName);
346             if (helpCommandName != null)
347                 helpCommand.setOperands(new java.util.Vector JavaDoc(java.util.Arrays.asList(
348                                                              new String JavaDoc[]{helpCommandName})));
349             //set an internal option called isMultiMode
350
helpCommand.setOption("isMultiMode", "true");
351
352             //get interactive value from the environment
353
final String JavaDoc interactiveVal = (String JavaDoc)CommandEnvironment.getInstance().
354                                           getEnvironments().get(INTERACTIVE);
355             //set the interactive mode
356
helpCommand.setOption(INTERACTIVE,
357                                   interactiveVal==null?"true":interactiveVal);
358             
359             helpCommand.runCommand();
360         }
361         catch (Exception JavaDoc e)
362         {
363             if (commandUsageText == null)
364                 CLILogger.getInstance().printMessage(getLocalizedString("NoUsageText",
365                                                      new Object JavaDoc[] {helpCommandName}));
366             else
367                 CLILogger.getInstance().printMessage(getLocalizedString("Usage",
368                                                      new Object JavaDoc[]{commandUsageText}));
369         }
370     }
371
372
373     /**
374      * this method prints the usage text from validCommand
375      * @param validCommand - contains the usage text
376      */

377     private void printUsageText(final ValidCommand validCommand)
378     {
379         if (validCommand != null && validCommand.getUsageText() != null)
380         {
381             CLILogger.getInstance().printError(getLocalizedString("Usage",
382                                                new Object JavaDoc[]{validCommand.getUsageText()}));
383         }
384     }
385
386
387 }
388
389
Popular Tags