Class CLICommand

  • All Implemented Interfaces:
    org.glassfish.hk2.api.PostConstruct
    Direct Known Subclasses:
    ExportCommand, HelpCommand, ListCommandsCommand, LoginCommand, MultimodeCommand, RemoteCLICommand, RemoteCommand, UnsetCommand, VersionCommand

    @Contract
    @PerLookup
    public abstract class CLICommand
    extends Object
    implements org.glassfish.hk2.api.PostConstruct
    Base class for a CLI command. An instance of a subclass of this class is created using the getCommand method with the name of the command and the information about its environment.

    A command is executed with a list of arguments using the execute method. The implementation of the execute method in this class saves the arguments in the protected argv field, then calls the following protected methods in order: prepare, parse, validate, and executeCommand. A subclass must implement the prepare method to initialize the metadata that specified the valid options for the command, and the executeCommand method to actually perform the command. The parse and validate method may also be overridden if needed. Or, the subclass may override the execute method and provide the complete implementation for the command, including option parsing.

    Author:
    Bill Shannon
    • Field Detail

      • logger

        protected static final Logger logger
      • name

        protected String name
        The name of the command. Initialized in the constructor.
      • programOpts

        @Inject
        protected ProgramOptions programOpts
        The program options for the command. Initialized in the constructor.
      • env

        @Inject
        protected Environment env
        The environment for the command. Initialized in the constructor.
      • argv

        protected String[] argv
        The command line arguments for this execution. Initialized in the execute method.
      • commandModel

        protected org.glassfish.api.admin.CommandModel commandModel
        The metadata describing the command's options and operands.
      • options

        protected org.glassfish.api.admin.ParameterMap options
        The options parsed from the command line. Initialized by the parse method. The keys are the parameter names from the command model, not the "forced to all lower case" names that are presented to the user.
      • operands

        protected List<String> operands
        The operands parsed from the command line. Initialized by the parse method.
      • passwords

        protected Map<String,​String> passwords
        The passwords read from the password file. Initialized by the initializeCommandPassword method.
    • Constructor Detail

      • CLICommand

        protected CLICommand()
        Constructor used by subclasses when instantiated by HK2. ProgramOptions and Environment are injected. name is set here.
      • CLICommand

        protected CLICommand​(String name,
                             ProgramOptions programOpts,
                             Environment env)
        Constructor used by subclasses to save the name, program options, and environment information into corresponding protected fields. Finally, this constructor calls the initializeLogger method.
    • Method Detail

      • getCommand

        public static CLICommand getCommand​(org.glassfish.hk2.api.ServiceLocator serviceLocator,
                                            String name)
                                     throws org.glassfish.api.admin.CommandException
        Get a CLICommand object representing the named command.
        Throws:
        org.glassfish.api.admin.CommandException
      • getCommand

        public static CLICommand getCommand​(CLIContainer cLIContainer,
                                            String name)
                                     throws org.glassfish.api.admin.CommandException
        Throws:
        org.glassfish.api.admin.CommandException
      • postConstruct

        public void postConstruct()
        Initialize the logger after being instantiated by HK2.
        Specified by:
        postConstruct in interface org.glassfish.hk2.api.PostConstruct
      • execute

        public int execute​(String... argv)
                    throws org.glassfish.api.admin.CommandException
        Execute this command with the given arguemnts. The implementation in this class saves the passed arguments in the argv field and calls the initializePasswords method. Then it calls the prepare, parse, and validate methods, finally returning the result of calling the executeCommand method. Note that argv[0] is the command name.
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • getName

        public String getName()
        Return the name of this command.
      • getCommandScope

        public static String getCommandScope()
      • setCommandScope

        public static void setCommandScope​(String ctx)
      • getProgramOptions

        public ProgramOptions getProgramOptions()
        Returns the program options associated with this command.
        Returns:
        the command's program options
      • getManPage

        public BufferedReader getManPage()
        Return a BufferedReader for the man page for this command, or null if not found.
      • expandManPage

        public BufferedReader expandManPage​(Reader r)
        Return a man page for this command that has the tokens substituted
      • getUsage

        public String getUsage()
        Get the usage text for the subcommand. This method shows the details for the subcommand options but does not provide details about the command options.
        Returns:
        usage text
      • usageOptions

        protected Collection<org.glassfish.api.admin.CommandModel.ParamModel> usageOptions()
        Subclasses can override this method to supply additional or different options that should be part of the usage text. Most commands will never need to do this, but the create-domain command uses it to include the --user option as a required option.
      • getCommandUsage

        public String getCommandUsage()
        Get the usage text for the command. This usage text shows the details of the command options but does not show the details for the subcommand options. The subcommand argument is used to fill in the subcommand name in the usage text.
        Returns:
        usage text for the command
      • getBriefCommandUsage

        public String getBriefCommandUsage()
      • quote

        public static String quote​(String value)
        Quote a value, if the value contains any special characters.
        Parameters:
        value - value to be quoted
        Returns:
        the possibly quoted value
      • processProgramOptions

        protected void processProgramOptions()
                                      throws org.glassfish.api.admin.CommandException
        If the program options haven't already been set, parse them on the command line and remove them from the command line. Subclasses should call this method in their prepare method after initializing commandOpts (so usage is available on failure) if they want to allow program options after the command name. Currently RemoteCommand does this, as well as the local commands that also need to talk to the server.
        Throws:
        org.glassfish.api.admin.CommandException
      • initializeLogger

        protected void initializeLogger()
        Initialize the state of the logger based on any program options.
      • initializePasswords

        protected void initializePasswords()
                                    throws org.glassfish.api.admin.CommandException
        Initialize the passwords field based on the password file specified in the program options, and initialize the program option's password if available in the password file.
        Throws:
        org.glassfish.api.admin.CommandException
      • prepare

        protected void prepare()
                        throws org.glassfish.api.admin.CommandException
        The prepare method must ensure that the commandModel field is set.
        Throws:
        org.glassfish.api.admin.CommandException
      • parse

        protected void parse()
                      throws org.glassfish.api.admin.CommandException
        The parse method sets the options and operands fields based on the content of the command line arguments. If the program options say this is a help request, we set options and operands as if "--help" had been specified.
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • checkHelp

        protected boolean checkHelp()
                             throws org.glassfish.api.admin.CommandException
        Check if the current request is a help request, either because --help was specified as a program option or a command option. If so, get the man page using the getManPage method, copy the content to System.out, and return true. Otherwise return false. Subclasses may override this method to perform a different check or to use a different method to display the man page. If this method returns true, the validate and executeCommand methods won't be called.
        Throws:
        org.glassfish.api.admin.CommandException
      • prevalidate

        protected void prevalidate()
                            throws org.glassfish.api.admin.CommandException
        The prevalidate method supplies missing options from the environment. It also supplies passwords from the password file or prompts for them if interactive.
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • inject

        protected void inject()
                       throws org.glassfish.api.admin.CommandException
        Inject this instance with the final values of all the command parameters.
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • validate

        protected void validate()
                         throws org.glassfish.api.admin.CommandException
        The validate method can be used by a subclass to validate that the type and quantity of parameters and operands matches the requirements for this command.
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • executeCommand

        protected abstract int executeCommand()
                                       throws org.glassfish.api.admin.CommandException
        Execute the command using the options in options and the operands in operands.
        Returns:
        the exit code
        Throws:
        org.glassfish.api.admin.CommandException - if execution of the command fails
        org.glassfish.api.admin.CommandValidationException - if there's something wrong with the options or arguments
      • getPassword

        protected char[] getPassword​(String paramname,
                                     String localizedPrompt,
                                     String localizedPromptConfirm,
                                     boolean create)
                              throws org.glassfish.api.admin.CommandValidationException
        Throws:
        org.glassfish.api.admin.CommandValidationException
      • getPassword

        protected char[] getPassword​(org.glassfish.api.admin.CommandModel.ParamModel opt,
                                     String defaultPassword,
                                     boolean create)
                              throws org.glassfish.api.admin.CommandValidationException
        Get a password for the given option. First, look in the passwords map. If found, return it. If not found, and not required, return null; If not interactive, return null. Otherwise, prompt for the password. If create is true, prompt twice and compare the two values to make sure they're the same. If the password meets other validity criteria (i.e., length) returns the password. If defaultPassword is not null, "Enter" selects this default password, which is returned.
        Throws:
        org.glassfish.api.admin.CommandValidationException
      • readPassword

        protected char[] readPassword​(String prompt)
        Display the given prompt and read a password without echoing it. Returns null if no console available.
      • getOperandModel

        protected org.glassfish.api.admin.CommandModel.ParamModel getOperandModel()
        Get the ParamModel that corresponds to the operand (primary parameter). Return null if none.
      • getOption

        protected String getOption​(String name)
        Get an option value, that might come from the command line or from the environment. Return the default value for the option if not otherwise specified.
      • getOptions

        protected List<String> getOptions​(String name)
        Get option values, that might come from the command line or from the environment. Return the default value for the option if not otherwise specified. This method works with options for with multiple() is true.
      • getBooleanOption

        protected boolean getBooleanOption​(String name)
        Get a boolean option value, that might come from the command line or from the environment.
      • getSystemProperty

        protected String getSystemProperty​(String name)
        Return the named system property, or property set in asenv.conf.
      • getSystemProperties

        protected Map<String,​String> getSystemProperties()
        Return all the system properties and properties set in asenv.conf. The returned Map may not be modified.
      • printExceptionStackTrace

        protected void printExceptionStackTrace​(Throwable e)
        Prints the exception message with level as FINER.
        Parameters:
        e - the exception object to print
      • ok

        protected static boolean ok​(String s)