FileDocCategorySizeDatePackage
MultiProcessCommand.javaAPI DocGlassfish v2 API16154Fri May 04 22:25:12 BST 2007com.sun.enterprise.cli.commands

MultiProcessCommand

public class MultiProcessCommand extends S1ASCommand
Creates a multimode environment for executing the commands from a file or by supplying commands interactively. Displays the help message for the command if help is sought.

Fields Summary
private static final String
FILE_OPTION
private static final String
PRINTPROMPT_OPTION
private static final String
ENCODING_OPTION
private static final String
EXIT
private boolean
mDone
private boolean
printPrompt
private final String
kPromptString
private static HashMap
localEnvironment
Constructors Summary
public MultiProcessCommand()
Default constructor to initialize the class.


                
     
    
        super();
    
Methods Summary
private voidcheckValidCommand(ValidCommand validCommand, java.lang.String commandName)
check if validCommand is null

        try {
            if (validCommand == null) {
                CLILogger.getInstance().printMessage(getLocalizedString("InvalidCommand",
                                                     new Object[]{commandName}));
                CLIMain.displayClosestMatch(commandName);
                throw new CommandException(getLocalizedString("UseHelpCommand"));
            }
        }
        catch (CommandException ce) {
                //throw a different exception with different message.
            throw new CommandException(getLocalizedString("UseHelpCommand"));
        }
    
public static java.lang.StringgetLocalEnvironmentValue(java.lang.String key)
returns the local environment value by the given key

        return (String) localEnvironment.get(key);
    
public static java.util.HashMapgetLocalEnvironments()
Returns the HashMap of Local environment.

        return localEnvironment;
    
public static intgetNumLocalEnvironments()
Returns the number of elements in local environment

        return localEnvironment.size();
    
private voidinvokeHelpClass(java.lang.String helpClassName, java.lang.String helpCommandName, java.lang.String commandUsageText)
This method invokes the help command class. If help command clss is invalid then the usage text is displayed.

        try
        {
            Command helpCommand = null;
            Class  helpClass = Class.forName(helpClassName);
            helpCommand = (Command)helpClass.newInstance();
            helpCommand.setName(helpCommandName);
            if (helpCommandName != null)
                helpCommand.setOperands(new java.util.Vector(java.util.Arrays.asList(
                                                             new String[]{helpCommandName})));
            //set an internal option called isMultiMode
            helpCommand.setOption("isMultiMode", "true");

            //get interactive value from the environment
            final String interactiveVal = (String)CommandEnvironment.getInstance().
                                          getEnvironments().get(INTERACTIVE);
            //set the interactive mode
            helpCommand.setOption(INTERACTIVE,
                                  interactiveVal==null?"true":interactiveVal);
            
            helpCommand.runCommand();
        }
        catch (Exception e)
        {
            if (commandUsageText == null) {
                CLILogger.getInstance().printMessage(getLocalizedString("NoManualEntry",
                                                     new Object[]{helpCommandName}));
                try {
                    CLIMain.displayClosestMatch(helpCommandName);
                }
                catch (CommandException ce) {
                    CLILogger.getInstance().printMessage(ce.getLocalizedMessage());
                }
                
            }
            else
                CLILogger.getInstance().printMessage(getLocalizedString("Usage",
                                                     new Object[]{commandUsageText}));
        }
    
private booleanisExecutableLine(java.lang.String line)
Checks to see if the line is executable, i.e if the line in non-empty and the line doesnt start with "#"

        boolean isExecutable = true;
        if ( line == null )
        {
            isExecutable    = false;
        }
        else if ( line.trim().equals("") ||
                  line.startsWith("#") ||
                  line.length() < 1 )
        {
            isExecutable = false;
        }
        return isExecutable;
    
private booleanisExitLine(java.lang.String line)
Checks to see if the user supplied an "exit" or "quit"

        if ( line == null ||
             (line != null && (line.equalsIgnoreCase( "exit" ) ||
                               line.equalsIgnoreCase( "quit" )) ))
        {
            return true;
        }
        return false;
    
private booleanisFileOptionSpecified()
Checks to see if the 'file' option is specified

return
boolean returns true if specified else false

        return ( getOption(FILE_OPTION) != null );
    
private voidprintExitMessage()
Prints the exit message for the mulitprocess command input

        CLILogger.getInstance().printMessage(getLocalizedString("ExitMessage"));
    
private java.lang.StringprintPromptAndReadLine()
Prints the prompt to the standard output Reads the line from the buffered input stream

return
String The line read from the inputstream or file

        try 
        {
            if (printPrompt)
                InputsAndOutputs.getInstance().getUserOutput().print( kPromptString );
            String line = InputsAndOutputs.getInstance().getUserInput().getLine();
            if (line == null && isFileOptionSpecified() == true) 
                return EXIT;
            else
                return line;
        }
        catch (IOException ioe)
        {
            throw new CommandException(getLocalizedString("CouldNotPrintOrRead"), 
                                       ioe);
        }
    
private voidprintUsageText(ValidCommand validCommand)
this method prints the usage text from validCommand

param
validCommand - contains the usage text

        if (validCommand != null && validCommand.getUsageText() != null)
        {
            CLILogger.getInstance().printError(getLocalizedString("Usage",
                                               new Object[]{validCommand.getUsageText()}));
        }
    
private voidprocessLine(java.lang.String line)
Process the input line supplied by the user. The line is converted to array of args and supplied to CommandFactory

        ValidCommand validCommand = null;
        try 
        {
            String[] commandLine = splitStringToArray(line);

                //get CLI descriptor instance
            CLIDescriptorsReader cliDescriptorsReader = 
            CLIDescriptorsReader.getInstance();

                //get the validCommand object from CLI descriptor
            validCommand = cliDescriptorsReader.getCommand(
                commandLine[0]);

                //check if command is help then throw the HelpException to
                //display the manpage or usage-text
            if (commandLine[0].equals("help")) throw new HelpException(
                commandLine.length<2?null:commandLine[1]);

            checkValidCommand(validCommand, commandLine[0]);

                //parse the command line arguments
            CommandLineParser clp = new CommandLineParser(commandLine, 
                                                          validCommand);


            //creates the command object using command factory
            final Command command = CommandFactory.createCommand(
                                                   validCommand, clp.getOptionsMap(),
                                                   clp.getOperands());
            
            //validate the Command with the validCommand object
            new CommandValidator().validateCommandAndOptions(validCommand,
                                                             command.getOptions(),
                                                             command.getOperands());
                //invoke the command
            command.runCommand();
        }
        catch (HelpException he)
        {
            invokeHelpClass(he.getHelpClassName(), he.getCommandName(), he.getUsageText());

        }
        catch (CommandValidationException cve)
        {
            printUsageText(validCommand);
            CLILogger.getInstance().printExceptionStackTrace(cve);
            CLILogger.getInstance().printError(cve.getLocalizedMessage());
        }
        catch (CommandException ce)
        {
            CLILogger.getInstance().printExceptionStackTrace(ce);
            CLILogger.getInstance().printError(ce.getLocalizedMessage());
        }
    
public static voidremoveAllEnvironments()
This method removes all environment variables from HashMap

        localEnvironment.clear();
    
public static java.lang.ObjectremoveLocalEnvironment(java.lang.String name)
This method removes environment variable from the local environment.

param
name is the name in the local environment to be removed.

        return localEnvironment.remove(name);
    
public voidrunCommand()
Implements the execution of MultiProcessCommand whether the input is from a file or from a standard input interactively.

throws
CommandException

        validateOptions();
        String line = null;
     
        try
        {
            if (isFileOptionSpecified()) 
            { 
                CLILogger.getInstance().printDebugMessage("file option specified");
                checkForFileExistence(null, getOption(FILE_OPTION));
                setInputStreamToFile();
            }
            else
                printExitMessage();
            line = printPromptAndReadLine();

            while (!isExitLine(line))
            {
                if (isExecutableLine(line)) 
                {
                    processLine(line);
                }
                line = printPromptAndReadLine();
            } 
        }
        catch ( CommandException ce )
        {
            throw ce;
        }
        catch ( Exception e )
        {
            throw new CommandException(e);
        }
    
private voidsetInputStreamToFile()
set user input stream this method assumes that file option is set

throws
CommandException

        try
        {
            final String sEncoding = getOption("ENCODING_OPTION");
            if (sEncoding == null) 
            {
                CLILogger.getInstance().printDebugMessage("Set input stream");
                InputsAndOutputs.getInstance().setUserInputFile(
                    getOption(FILE_OPTION));
            }
            else 
            {
                InputsAndOutputs.getInstance().setUserInputFile(
                    getOption(FILE_OPTION), sEncoding);
            }
        }
        catch (IOException ioe) 
        {
            throw new CommandException(getLocalizedString("CouldNotSetInputStream"),
                                       ioe);
        }
    
public static voidsetLocalEnvironment(java.lang.String name, java.lang.String value)
This method adds a name and value to the local environment.

param
name - option name
param
value - option value

        if ( localEnvironment.containsKey(name) )
        {
            localEnvironment.remove( name );
        }
        localEnvironment.put(name, value );
    
private java.lang.String[]splitStringToArray(java.lang.String line)
This method will split the string to array of string separted by space(s) If there is a quote " around the string, then the string will not be splitted. For example, if the string is: abcd efg "hij klm", the string array will contain abcd|efg|hij klm|

param
line - string to be converted
return
- string array
throws
CommandException

        final CLITokenizer cliTokenizer = new CLITokenizer(line, " ");
        String[] strArray = new String[cliTokenizer.countTokens()];
        int ii=0;
        while (cliTokenizer.hasMoreTokens()) 
        {
            strArray[ii++] = cliTokenizer.nextTokenWithoutEscapeAndQuoteChars();
            CLILogger.getInstance().printDebugMessage("CLIToken = [" + strArray[ii-1] +"]");

        }
        return strArray;
    
public booleanvalidateOptions()
Checks whether options are specified at the command line. If options are specified, then it validates for the options else it assumes no options are specified. In MultiProcessCommand without specifying an option brings up the interactive mode, otherwise it reads the commands from a file with option specified.

        printPrompt = getBooleanOption(PRINTPROMPT_OPTION);
        return super.validateOptions();