Command Line

For using the command line tool there must be a help text document which defines the usage of the command line. It holds the description displayed to the user as a help output as well. The help document is named like the commando used to start the application. The extension for the help document is ".help ". By convention the lines in the help document are no longer than 80 characters. Here you have a sample cmd.help .

Find more to read about the command line feature in the Package Description .

Usage

Now lets have a short example how to use this package. This example relies on a help document C:\MyApplication\cmd.help . It also relies on a batch that starts the java application and is found in C:\MyApplication\cmd.bat .

See the help document for this example .

And this is how the sample class looks like:

package my.project;

import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;

import de.goerntkai.toolbox.cmdln.CommandLine;
import de.goerntkai.toolbox.cmdln.CommandLineFactory;
import de.goerntkai.toolbox.cmdln.CommandLineParameter;
import de.goerntkai.toolbox.cmdln.HelpTextException;
import de.goerntkai.toolbox.fs.Folder;


/**
 * <p>Testclass to show how the <code>cmdln</code> package works.</p>
 *
 * @author <a href="mailto:kai.goernt@dimensionswandler.de">Kai Görnt</a>
 * @version $Id: MyClass.java 39 2008-09-20 07:39:22Z goerntkai $
 * @since 28.08.2008 19:07:41 v/1.0.1
 */
public class MyClass {

    /**
     * <p>Holds the command.</p>
     * <p>Needed, because this sample is unit tested.</p>
     */
    private static String command = MyClass.DEFAULT_COMMAND;

    /**
     * <p>Holds the default command.</p>
     */
    private static final String DEFAULT_COMMAND = "cmd"; //$NON-NLS-1$

    /**
     * <p>Holds the help directory.</p>
     */
    private static Folder helpDir = null;

    /**
     * <p>Holds the log.</p>
     */
    private static Logger log = null;

    /**
     * <p>Suppresses external instantiation and initializes the logger. Used by
     * <code>main(String[])</code>.</p>
     */
    private MyClass() {

        super();

        MyClass.log = Logger.getLogger(this.getClass().getName());
    }

    /**
     * <p>Displays the help text if needed.</p>
     *
     * @param theText to display
     */
    private static void displayText(final String[] theText) {

        for (int idx = 0; idx < theText.length; idx++) {
            MyClass.log.info(theText[idx]);
        }
    }

    /**
     * <p>Resets the members to their initial values.</p>
     * <p>Needed, because this sample is unit tested.</p>
     */
    static void reset() {

        MyClass.command = MyClass.DEFAULT_COMMAND;
        MyClass.setHelpDir(null);
    }

    /**
     * <p>Sets the command.</p>
     * <p>Needed, because this sample is unit tested.</p>
     *
     * @param theCommand to set
     */
    static void setCommand(final String theCommand) {

        command = theCommand;
    }

    /**
     * <p>Sets the helpDir.</p>
     * <p>Needed, because this sample is unit tested.</p>
     *
     * @param theHelpDir to set
     */
    static void setHelpDir(final Folder theHelpDir) {

        helpDir = theHelpDir;
    }

    /**
     * <p>Illustrates the usage of the <code>cmdln</code> package.</p>
     *
     * @param theArgs from the commandline
     * @throws FileNotFoundException from creating the commad line
     */
    public static void main(
        final String[] theArgs
    ) throws FileNotFoundException {

        //MyClass.helpDir = new Folder("C:/MyApplication");
        //...

        /*
         * Calls the constructor to set the logger.
         */
        new MyClass();

        MyClass.log.config(MyClass.helpDir.getCanonicalPath());

        CommandLine cmdLn = null;
        try {
            cmdLn = CommandLineFactory.createCommandLine(
                MyClass.command,
                theArgs,
                MyClass.helpDir
            );

            if (cmdLn.isValid()) {
                MyClass.log.info(
                    "Given command line is valid." //$NON-NLS-1$
                );

                //...

                CommandLineParameter help = cmdLn.getParameter(
                    "help" //$NON-NLS-1$
                );
                if (help.isSet()) {
                    displayText(cmdLn.getHelpText());

                } else {

                    CommandLineParameter myArg = cmdLn.getParameter(
                        "myArg" //$NON-NLS-1$
                    );
                    MyClass.log.info(myArg.getValue());

                    CommandLineParameter opArg = cmdLn.getParameter(
                        "opArg" //$NON-NLS-1$
                    );
                    MyClass.log.info(opArg.getValue());

                    CommandLineParameter op1 = cmdLn.getParameter(
                        "op1" //$NON-NLS-1$
                    );
                    if (op1.isSet()) {
                        MyClass.log.info("Yippie"); //$NON-NLS-1$
                    }

                    CommandLineParameter op2 = cmdLn.getParameter(
                        "op2" //$NON-NLS-1$
                    );
                    MyClass.log.info(op2.getValue());
                }

                //...

            } else {
                MyClass.log.info(
                    "Given command line is invalid!" //$NON-NLS-1$
                );
                displayText(cmdLn.getHelpText());
            }

        } catch (HelpTextException exception) {
            MyClass.log.log(
                Level.SEVERE,
                "Caught exception with command=[" + //$NON-NLS-1$
                    MyClass.command +
                    "], args=[" + //$NON-NLS-1$
                    theArgs.toString() +
                    "], helpDir=[" + //$NON-NLS-1$
                    MyClass.helpDir.getCanonicalPath() +
                    "]", //$NON-NLS-1$
                exception
            );
        }
    }
}

See the log file this class produces during several calls.

The Help Text Document

A help text file should always be named like {commandName}.help . As the text is displayed as it is found in the document be careful not to have lines longer than 80 characters. It is always given in the following structure:

Usage:
  commandName [options] {requiredArguments} [{optionalArguments}]

Description:
  a brief description of the commando

Required arguments:
  {argument} argumentDescription

Optional arguments:
  {argument} argumentDescription; default: (defaultValue)

Options:
  -{option}             optionDescription
  -{option}             optionDescription; superior
  -{option} <parameter> optionDescription; default: (defaultValue)

Usage: , Description: , Required arguments: , Optional arguments: , Options: , superior and default: are keywords and must not be changed or misspelled. The usage block and the description block are mandatory. The other blocks can be omitted but must not change their order when used. Indentation is for ease of legibility. Indent by two spaces and build columns also with spaces. There can be as many options and arguments as you like.

In the usage block there is no need to list up all possible options. Just use [options] to make clear that they are all optional. Though there is need to list up every argument, both required and optional.

Curly brackets mark the end and the beginning of an arguments or options name and are required. Square brackets mark beginning and end of an optional parameter. They are required in the usage block and may be omitted in the description lines. The parenthesis around the default values are mandatory as well as the angle bracket around the parameter names. Use the minus before every options name to show that an option must always be given with it in the command line.

The order of the options is not important. Indeed, the order of the arguments is very important. So you should note the description of the arguments in the same order as you gave them in the usage line.

Default Values

Required arguments do not have default values. That's why they are required. Optional arguments and options with parameters must have default values. Don't forget!

Default values are set by the keyword default: and are surrounded by parenthesis. This combination lets you use the keyword and parenthesis in the text for your description. However, to set the default value must be the last use of parenthesis in the description.

Superior Options

An option with the keyword superior in the end of its description is an option that needs no Required arguments . Usually the commandline is invalidly given when leaving the required arguments out. In case of a commandline with a superior -option the commandline is always valid. When a superior option is set by the user, the program should follow this option over all means and stop after processing the option. Options like help or version may serve as examples.

Please be sure that the keyword superior ends the description.