FileDocCategorySizeDatePackage
CLIMain.javaAPI DocGlassfish v2 API14839Tue Jul 24 00:21:56 BST 2007com.sun.enterprise.cli.framework

CLIMain

public class CLIMain extends Object
The CLIMain contains a main that calls the appropriate objects in the CLI framework and invokes the command object.
version
$Revision: 1.13 $

Fields Summary
private static final String
HelpCommandAndOptions
private static final String
VERSION_OPTION
private static final String
VERSION_COMMAND
private static final int
MAX_COMMANDS_TO_DISPLAY
Constructors Summary
Methods Summary
private static voidcheckValidCommand(ValidCommand validCommand, java.lang.String commandName)
check if validCommand is null

        if (validCommand == null) {
            displayClosestMatch(commandName);
                //throw an empty exception so that exit code is 1.
            throw new CommandException(getLocalizedString("InvalidCommand",
                                                  new Object[] {commandName}));
        }
    
public static voiddisplayClosestMatch(java.lang.String commandName)

        try {
                //remove leading "*" and ending "*" chars
            int beginIndex = 0;
            int endIndex = commandName.length();
            if (commandName.startsWith("*")) beginIndex = 1;
            if (commandName.endsWith("*")) endIndex = commandName.length()-1;
            final String trimmedCommandName = commandName.substring(beginIndex, endIndex);
                
            //add all matches to the search String since we want
            //to search all the commands that matches the string
            final String[] matchedCommands = SearchCommands.getMatchedCommands(".*"+trimmedCommandName+".*");
                //don't want to display more than 50 commands
            if (matchedCommands.length > 0 && matchedCommands.length<MAX_COMMANDS_TO_DISPLAY)
            {
                System.out.println(getLocalizedString("ClosestMatchedCommands",null));
                for (String eachCommand : matchedCommands)
                {
                    System.out.println("    "+eachCommand);
                }
            }
                //find the closest distance
            else {
                final String[] allCommands = SearchCommands.getAllCommands();
                final String nearestString = StringEditDistance.findNearest(commandName, allCommands);
                    //do not want to display the string if the edit distance is too large
                if (StringEditDistance.editDistance(commandName, nearestString) < 3) {
                    System.out.println(getLocalizedString("ClosestMatchedCommands",null));
                    System.out.println("    "+nearestString);
                }
                else
                    throw new CommandException(getLocalizedString("InvalidCommand",
                                                                  new Object[] {commandName}));
            }
        }
        catch (Exception e)
        {
            throw new CommandException(getLocalizedString("InvalidCommand",
                                                          new Object[] {commandName}));
        }
    
private static java.lang.StringgetLocalizedString(java.lang.String key, java.lang.Object[] toInsert)
returns the localized string from the properties file Calls the LocalStringsManagerFactory.getFrameworkLocalStringsManager() method, returns "Key not found" if it cannot find the key

param
key, the string to be localized
param
toInsert, the strings to be inserted in the placeholders

        try
        {
            final LocalStringsManager lsm = LocalStringsManagerFactory.getFrameworkLocalStringsManager();
            if (toInsert == null) 
                return lsm.getString(key);
            else
                return lsm.getString(key, toInsert);
        }
        catch (CommandValidationException cve)
        {
            return LocalStringsManager.DEFAULT_STRING_VALUE;
        }
    
private static java.lang.StringgetUsageTextFromValidCommand(ValidCommand validCommand)
This method returns the usages text from validCommand object

param
validCommand
return
usage text

        if (validCommand != null && validCommand.getUsageText() != null)
        {
            return getLocalizedString("Usage", new Object[]{validCommand.getUsageText()});
        }
        return "";
    
public static voidinvokeCLI(java.lang.String cmdline, InputsAndOutputs io)



          
          
    
        InputsAndOutputs.setInstance(io);
        String[] args = splitStringToArray(cmdline);
        invokeCommand(args);
    
public static voidinvokeCommand(java.lang.String[] args)
This is the important bulk of reading the xml, validating, creating command vi command factory and invoke the command.

        ValidCommand validCommand = null;

        try 
        {
            //read CLI descriptor
            final CLIDescriptorsReader cliDescriptorsReader = CLIDescriptorsReader.getInstance();

            if (args.length < 1)
            {
                cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.DONT_SERIALIZE);
                    //pass in null as the command Name.  The default command
                    //shall be returned, else an exception is thrown.
                validCommand = cliDescriptorsReader.getCommand(null);
                    //set args[0] to the default command.
                args = new String[] {cliDescriptorsReader.getDefaultCommand()};
            }
            else 
            {
                //check if command is -V, as stated in the CLIP that
                //-V is supported and it is the same as version command
                if (args[0].equals(VERSION_OPTION))
                    args[0] = VERSION_COMMAND;

                //cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILE);
                cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILES);

                //get the validCommand object from CLI descriptor
                validCommand = cliDescriptorsReader.getCommand(args[0]);
            }
            setCommandLocalizedProperty(cliDescriptorsReader.getProperties());

                //check if command is help then throw the HelpException to 
                //display the manpage or usage-text
            if (args[0].matches(HelpCommandAndOptions))
                throw new HelpException(args);



            checkValidCommand(validCommand, args[0]);

            //parse the command line arguments
            final CommandLineParser clp = new CommandLineParser(args, 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();
            return;
        }
        catch (HelpException he)
        {
            invokeHelpClass(he.getHelpClassName(), he.getCommandName(), he.getUsageText(),he.isShell());
        }
        catch (CommandValidationException cve )
        {
                //rethrow CommandValidationException with Usage Text
            throw new CommandValidationException(getUsageTextFromValidCommand(validCommand)
                                                 + "\n" + cve.getLocalizedMessage());
        }

    
private static voidinvokeHelpClass(java.lang.String helpClassName, java.lang.String helpCommandName, java.lang.String commandUsageText, boolean isShell)
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<String>(java.util.Arrays.asList(
                                        new String[]{helpCommandName})));
            if(isShell){
                helpCommand.setOption("isMultiMode","true");
                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) {
                displayClosestMatch(helpCommandName);
                throw new CommandException(getLocalizedString("InvalidCommand",
                                           new Object[] {helpCommandName}));
            }
            else
                CLILogger.getInstance().printMessage(getLocalizedString("Usage",
                                                     new Object[]{commandUsageText}));
        }
    
public static voidmain(java.lang.String[] args)

        long startTime = 0;        
        boolean time = false;
        if (System.getProperty("com.sun.appserv.cli.timing") != null) {
           time = true;
           startTime = System.currentTimeMillis();
        }
        
        try 
        {
            invokeCommand(args);
            if (time) {
                CLILogger.getInstance().printDebugMessage(
                    "Command execution time: " + 
                    (System.currentTimeMillis() - startTime) + " ms");
            }
            System.exit(0);
        }
        catch (CommandValidationException cve) 
        {
            CLILogger.getInstance().printExceptionStackTrace(cve);
            CLILogger.getInstance().printError(cve.getLocalizedMessage());
            System.exit(1);
        }
        catch (CommandException ce) 
        {
    	    CLILogger.getInstance().printExceptionStackTrace(ce);
            CLILogger.getInstance().printError(ce.getLocalizedMessage());
            System.exit(1);
        }
        catch (Throwable ex) 
        {
            CLILogger.getInstance().printExceptionStackTrace(ex);
            CLILogger.getInstance().printError(ex.getLocalizedMessage());
            System.exit(1);
        } 
    
private static voidsetCommandLocalizedProperty(java.util.Iterator localizePropertiesIter)
sets the localized property in the command module

params
Iterator - iterator containing the localized properties

 
        LocalStringsManagerFactory.setCommandLocalStringsManagerProperties(
            localizePropertiesIter);
    
private static 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;