Example usage for org.apache.commons.cli OptionGroup setRequired

List of usage examples for org.apache.commons.cli OptionGroup setRequired

Introduction

In this page you can find the example usage for org.apache.commons.cli OptionGroup setRequired.

Prototype

public void setRequired(boolean required) 

Source Link

Usage

From source file:org.tolven.passwordrecovery.PasswordRecoveryPlugin.java

private Options getCommandOptions() {
    Options cmdLineOptions = new Options();
    OptionGroup optionGroup = new OptionGroup();
    Option dispalyOption = new Option(CMD_LINE_DISPLAY_OPTION, CMD_LINE_DISPLAY_OPTION, false,
            "\"display security questions from repositoryRuntime\"");
    optionGroup.addOption(dispalyOption);
    Option importOption = new Option(CMD_LINE_LOAD_OPTION, CMD_LINE_LOAD_OPTION, false,
            "\"load security questions from repositoryRuntime\"");
    optionGroup.addOption(importOption);
    Option addOption = new Option(CMD_LINE_ADD_OPTION, CMD_LINE_ADD_OPTION, true,
            "\"add a security question\"");
    optionGroup.addOption(addOption);//from w  w  w  .  ja v a2s .co  m
    Option changeOption = new Option(CMD_LINE_CHANGE_OPTION, CMD_LINE_CHANGE_OPTION, true,
            "\"change a security question\"");
    optionGroup.addOption(changeOption);
    Option removeOption = new Option(CMD_LINE_REMOVE_OPTION, CMD_LINE_REMOVE_OPTION, true,
            "\"remove a security question\"");
    optionGroup.addOption(removeOption);
    Option guiOption = new Option(CMD_LINE_GUI_OPTION, CMD_LINE_GUI_OPTION, false,
            "\"start the password recovery gui\"");
    optionGroup.addOption(guiOption);
    optionGroup.setRequired(true);
    cmdLineOptions.addOptionGroup(optionGroup);
    Option newValueOption = new Option(CMD_LINE_NEW_OPTION, CMD_LINE_NEW_OPTION, true,
            "\"supplied with -" + CMD_LINE_CHANGE_OPTION + " option\"");
    cmdLineOptions.addOption(newValueOption);
    return cmdLineOptions;
}

From source file:org.tolven.plugin.boot.TPFBoot.java

public static void main(String[] args) throws Exception {
    URL manifestURL = ClassLoader.getSystemResource("tolven-plugin.xml");
    TPF_VERSION = RepositoryMetadata.getVersion(manifestURL);
    System.setProperty(TPF_VERSION_PROPERTY, TPF_VERSION);
    Option confOption = new Option(CMD_LINE_CONF_OPTION, CMD_LINE_CONF_OPTION, true, "configuration directory");
    OptionGroup optionGroup = new OptionGroup();
    optionGroup.setRequired(true);
    Option upgradeOption = new Option(CMD_LINE_GETPLUGINS_OPTION, CMD_LINE_GETPLUGINS_OPTION, false,
            "getPlugins from repositories");
    optionGroup.addOption(upgradeOption);
    Option pluginOption = new Option(CMD_LINE_PLUGIN_OPTION, CMD_LINE_PLUGIN_OPTION, true,
            "execute one or more plugins");
    optionGroup.addOption(pluginOption);
    Option genMetadataOption = new Option(CMD_LINE_GENMETADATA_OPTION, CMD_LINE_GENMETADATA_OPTION, true,
            "generate a repository metadata file");
    optionGroup.addOption(genMetadataOption);
    Option versionOption = new Option(CMD_LINE_VERSION_OPTION, CMD_LINE_VERSION_OPTION, false, "TPF Version");
    optionGroup.addOption(versionOption);
    Option repositorySnapshotOption = new Option(CMD_LINE_REPOSITORYSNAPSHOT_OPTION,
            CMD_LINE_REPOSITORYSNAPSHOT_OPTION, false, "create snapshot of repositories");
    optionGroup.addOption(repositorySnapshotOption);
    Options cmdLineOptions = new Options();
    cmdLineOptions.addOption(confOption);
    cmdLineOptions.addOptionGroup(optionGroup);
    try {/*w  ww  . j  a va2 s .c  om*/
        GnuParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(cmdLineOptions, args, true);
        String configDirname = getCommandLineConfigDir(commandLine);
        File configDir = new File(configDirname);
        pluginsWrapper = new ConfigPluginsWrapper();
        pluginsWrapper.loadConfigDir(configDir);
        Logger.getLogger(TPFBoot.class.getName()).info("TPF Version: " + TPF_VERSION);
        Logger.getLogger(TPFBoot.class.getName()).info("Loaded configDir " + configDir.getPath());
        boolean upgrade = commandLine.hasOption(CMD_LINE_GETPLUGINS_OPTION);
        String plugins = commandLine.getOptionValue(CMD_LINE_PLUGIN_OPTION);
        boolean genMetadata = commandLine.hasOption(CMD_LINE_GENMETADATA_OPTION);
        boolean versionRequest = commandLine.hasOption(CMD_LINE_VERSION_OPTION);
        boolean repositorySnapshot = commandLine.hasOption(CMD_LINE_REPOSITORYSNAPSHOT_OPTION);
        if (upgrade) {
            //RepositoryUpgrade.main(commandLine.getArgs()); //CLI seems to only recognize the first letter of an option?
            StringBuffer buff = new StringBuffer();
            for (String arg : args) {
                if (!("-" + CMD_LINE_GETPLUGINS_OPTION).equals(arg)) {
                    buff.append(arg + ",");
                }
            }
            RepositoryUpgrade.main(buff.toString().split(","));
        } else if (genMetadata) {
            StringBuffer buff = new StringBuffer();
            for (String arg : args) {
                if (!("-" + CMD_LINE_GENMETADATA_OPTION).equals(arg)) {
                    buff.append(arg + ",");
                }
            }
            RepositoryMetadata.main(buff.toString().split(","));
        } else if (versionRequest) {
            System.out.println("\nTPF Version: " + TPF_VERSION);
        } else if (repositorySnapshot) {
            StringBuffer buff = new StringBuffer();
            for (String arg : args) {
                if (!("-" + CMD_LINE_REPOSITORYSNAPSHOT_OPTION).equals(arg)) {
                    buff.append(arg + ",");
                }
            }
            RepositorySnapshot.main(buff.toString().split(","));
        } else if (plugins != null) {
            addBootRepositoryRuntime(pluginsWrapper, configDir);
            Boot.main(args);
        }
    } catch (ParseException ex) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(TPFBoot.class.getName(), cmdLineOptions);
        throw new RuntimeException("Could not parse command line for: " + TPFBoot.class.getName(), ex);
    }
}

From source file:org.tolven.scheduler.SchedulerPlugin.java

private Options getCommandOptions() {
    Options cmdLineOptions = new Options();
    OptionGroup optionGroup = new OptionGroup();
    Option startOption = new Option(CMD_LINE_START_OPTION, CMD_LINE_START_OPTION, true,
            "\"-start schedulerId intervalDuration(ms)\"");
    startOption.setArgs(2);//from  w w w.  j  a  v  a2s .  co m
    optionGroup.addOption(startOption);
    Option stopOption = new Option(CMD_LINE_STOP_OPTION, CMD_LINE_STOP_OPTION, true, "\"-stop schedulerId\"");
    optionGroup.addOption(stopOption);
    Option statusOption = new Option(CMD_LINE_STATUS_OPTION, CMD_LINE_STATUS_OPTION, true,
            "\"-status schedulerId\"");
    optionGroup.addOption(statusOption);
    optionGroup.setRequired(true);
    cmdLineOptions.addOptionGroup(optionGroup);
    return cmdLineOptions;
}

From source file:org.tuxedoberries.transformo.app.frontend.CommandLineLauncher.java

public static Options getOptions() {
    Options options = new Options();
    options.addOption("help", "Print this message.");

    // Generation
    OptionGroup genGroup = new OptionGroup();
    Option tablesOption = new Option("tables", "Generate filled templates by using each table information.");
    Option fieldsOption = new Option("fields", "Generate filled templates by using each field information.");
    Option dataOption = new Option("data", "Generate data using a specific format.");
    genGroup.addOption(tablesOption);//from  w w w  . j a  v  a 2  s .  c o  m
    genGroup.addOption(fieldsOption);
    genGroup.addOption(dataOption);
    genGroup.setRequired(true);
    options.addOptionGroup(genGroup);

    // Database
    Option database = new Option("d", "Use the given Database. Just XLSX format Supported for now.");
    database.setArgs(1);
    database.setArgName("file");
    database.setRequired(true);
    options.addOption(database);

    // Target Folder
    Option targetFolder = new Option("tfolder", "Target folder where to save the result.");
    targetFolder.setArgs(1);
    targetFolder.setArgName("folder");
    options.addOption(targetFolder);

    // Target File
    Option targetFile = new Option("tfile",
            "Target file name expresion. For -tables or -fields can use $file_name$, $field_name$ and/or $field_type$ and any modifiers.");
    targetFile.setArgs(1);
    targetFile.setArgName("file");
    options.addOption(targetFile);

    // Target Format
    OptionGroup formatGroup = new OptionGroup();
    Option jsonOption = new Option("json", "[-data only] Generate data using JSON format.");
    Option shortJsonOption = new Option("sjson",
            "[-data only] Generate data using Short field name JSON format.");
    formatGroup.addOption(jsonOption);
    formatGroup.addOption(shortJsonOption);
    options.addOptionGroup(formatGroup);

    // Template Folder
    Option templateFolder = new Option("sfolder",
            "[-tables or -fields only] Template source folder. Where to locate all different templates to use.");
    templateFolder.setArgs(1);
    templateFolder.setArgName("folder");
    options.addOption(templateFolder);

    // Template File
    Option templateFile = new Option("sfile",
            "[-tables or -fields only] Template index source file. The point of origin for the templates.");
    templateFile.setArgs(1);
    templateFile.setArgName("file");
    options.addOption(templateFile);

    return options;
}

From source file:pl.koziolekweb.options.TodConverterOptions.java

public TodConverterOptions() {
    OptionGroup optionGroup = new OptionGroup();
    optionGroup.addOption(new HelpOption(this));
    optionGroup.addOption(new ConvertAllOption());
    optionGroup.addOption(new ConvertOneOption());
    optionGroup.setRequired(true);
    addOptionGroup(optionGroup);/* w  ww.  j a v  a 2 s. co m*/
}

From source file:pl.nask.hsn2.unicorn.CommandLineParams.java

private void initOptions() {
    OptionGroup optionGroup = new OptionGroup();
    optionGroup.setRequired(true);

    OptionBuilder.withArgName(JOB_ID);/*www  .  j  ava  2 s .c  om*/
    OptionBuilder.withLongOpt("jobCancel");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Job cancel");
    optionGroup.addOption(OptionBuilder.create("jc"));

    OptionBuilder.withArgName("workflowName [serviceParams]");
    OptionBuilder.withLongOpt("jobDescriptor");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("Job descriptor");
    optionGroup.addOption(OptionBuilder.create("jd"));

    OptionBuilder.withArgName("workflowName filePath");
    OptionBuilder.withLongOpt("jobDescriptorFlood");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("Job descriptor flood");
    optionGroup.addOption(OptionBuilder.create("jdf"));

    OptionBuilder.withLongOpt("jobList");
    OptionBuilder.withDescription("Job list");
    optionGroup.addOption(OptionBuilder.create("jl"));

    OptionBuilder.withLongOpt("jobListQuery");
    OptionBuilder.withArgName("workflowName");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("List of jobs with the given workflow name");
    optionGroup.addOption(OptionBuilder.create("jlq"));

    OptionBuilder.withArgName(JOB_ID);
    OptionBuilder.withLongOpt("jobInfo");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Job info");
    optionGroup.addOption(OptionBuilder.create("ji"));

    OptionBuilder.withLongOpt("listWorkflow");
    OptionBuilder.withDescription("Workflow list");
    optionGroup.addOption(OptionBuilder.create("lw"));

    OptionBuilder.withArgName("workflowName revision");
    OptionBuilder.withLongOpt("getWorkflow");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("get Workflow");
    optionGroup.addOption(OptionBuilder.create("gw"));

    OptionBuilder.withArgName("workflowFilePath");
    OptionBuilder.withLongOpt("uploadWorkflow");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Uploads worklfow definition file");
    optionGroup.addOption(OptionBuilder.create("uw"));

    OptionBuilder.withLongOpt("getConfig");
    OptionBuilder.withDescription("get config");
    optionGroup.addOption(OptionBuilder.create("gcr"));

    OptionBuilder.withArgName("queueName");
    OptionBuilder.withLongOpt("getMessage");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Print message from queue without consuming");
    optionGroup.addOption(OptionBuilder.create("gm"));

    OptionBuilder.withArgName("queueName messagesNumber");
    OptionBuilder.withLongOpt("getMessages");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("Print messages from queue without consuming");
    optionGroup.addOption(OptionBuilder.create("gms"));

    OptionBuilder.withArgName("queueName");
    OptionBuilder.withLongOpt("streamMessage");
    OptionBuilder.hasArgs(1);
    OptionBuilder.withDescription("Get and print all messages from queue. Listens in infinite loop.");
    optionGroup.addOption(OptionBuilder.create("sm"));

    OptionBuilder.withArgName("jobId objectId");
    OptionBuilder.withLongOpt("objectStoreGet");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("return object having the same jobId and objectId");
    optionGroup.addOption(OptionBuilder.create("osg"));

    OptionBuilder.withArgName(JOB_ID);
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Make dump");
    optionGroup.addOption(OptionBuilder.create("dump"));

    OptionBuilder.withArgName(JOB_ID);
    OptionBuilder.withLongOpt("objectStoreQueryAll");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Query for objectStore return ALL objects with jobId");
    optionGroup.addOption(OptionBuilder.create("osqa"));

    OptionBuilder.withArgName("jobId name");
    OptionBuilder.withLongOpt("objectStoreQueryName");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription(
            "Query for objectStore return objects having the same jobId and attribute name as given");
    optionGroup.addOption(OptionBuilder.create("osqn"));

    OptionBuilder.withArgName("jobId name type[s/i/b/o] value");
    OptionBuilder.withLongOpt("objectStoreQueryValue");
    OptionBuilder.hasArgs(4);
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription(
            "Query for objectStore return objects having the same jobId attribute named and value as given.");
    optionGroup.addOption(OptionBuilder.create("osqv"));

    OptionBuilder.withArgName(JOB_ID);
    OptionBuilder.withLongOpt("objectStoreJobClean");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "Sends JobFinished message. As a result of this msg ObjectStore will clean all data with given jobId.");
    optionGroup.addOption(OptionBuilder.create("osjc"));

    OptionBuilder.withLongOpt("help");
    OptionBuilder.withDescription("Prints this help");
    optionGroup.addOption(OptionBuilder.create("h"));

    OptionBuilder.withArgName("fileName jobId");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("Import objects from file to os");
    optionGroup.addOption(OptionBuilder.create("import"));

    OptionBuilder.withArgName(JOB_ID);
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("checking status of job");
    optionGroup.addOption(OptionBuilder.create("status"));

    OptionBuilder.withArgName("action[id|w] param count [interval]");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription(
            "When action type is 'id' it monitors job and starts new if it ends. When type is 'w' it starts new job, monitors it and starts new if it ends. Count defines how many time to repeat job. Time interval defines sleep between checks in seconds (10s if nothing provided).");
    OptionBuilder.withLongOpt("jobDescriptorLooped");
    optionGroup.addOption(OptionBuilder.create("jdl"));

    options.addOptionGroup(optionGroup);

    OptionBuilder.withArgName("address");
    OptionBuilder.withLongOpt("serverAddress");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Address for server, default: " + address);
    options.addOption(OptionBuilder.create("sa"));

    OptionBuilder.withArgName("name");
    OptionBuilder.withLongOpt("queueName");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Name for objestStore queue, default: " + osQueueName);
    options.addOption(OptionBuilder.create("qn"));

    OptionBuilder.withArgName("name");
    OptionBuilder.withLongOpt("fwQueueName");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("Name for framework queue, default: " + frameworkQueueName);
    options.addOption(OptionBuilder.create("fqn"));

    OptionBuilder.withLongOpt("verbose");
    OptionBuilder.withDescription("Whether to print objects in osqa, osqn and osqv, default: not enabled.");
    options.addOption(OptionBuilder.create("verb"));

    OptionBuilder.withLongOpt("brief");
    OptionBuilder.withDescription("Used with '-jl' and '-osqa' only. Shows brief info. Default: not enabled.");
    options.addOption(OptionBuilder.create("b"));
}

From source file:scalabilityTests.scenarios.SchedulerJobSubmission.java

private static void addCommandLineOptions(Options options) {

    Option help = new Option("h", "help", false, "Display this help");
    help.setRequired(false);//from   ww w  .  j  a  v a2  s .  c  o  m
    options.addOption(help);

    Option xmlDescriptor = new Option("ad", "gcmad", true, "path to the GCM Aplication Descriptor to be used");
    xmlDescriptor.setArgName("GCMA_xml");
    xmlDescriptor.setArgs(1);
    xmlDescriptor.setRequired(true);
    options.addOption(xmlDescriptor);

    Option vnode = new Option("vn", "virtualNode", true,
            "the name of the virtual node which identifies the nodes onto which the Active Object Actors will be deployed");
    vnode.setArgName("AO_nodes");
    vnode.setArgs(1);
    vnode.setRequired(true);
    options.addOption(vnode);

    Option schedulerUrl = new Option("u", "schedulerUrl", true, "the URL of the Scheduler");
    schedulerUrl.setArgName("schedulerURL");
    schedulerUrl.setArgs(1);
    schedulerUrl.setRequired(true);
    options.addOption(schedulerUrl);

    Option username = new Option("l", "login", true, "The username to join the Scheduler");
    username.setArgName("login");
    username.setArgs(1);
    username.setRequired(false);
    options.addOption(username);

    Option password = new Option("p", "password", true, "The password to join the Scheduler");
    password.setArgName("pwd");
    password.setArgs(1);
    password.setRequired(false);
    options.addOption(password);

    Option loginFile = new Option("lf", "loginFile", true,
            "The path to a file containing valid username:password combinations for the Scheduler");
    loginFile.setArgName("login_cfg");
    loginFile.setArgs(1);
    loginFile.setRequired(false);
    options.addOption(loginFile);

    Option jobDescriptor = new Option("j", "jobDesc", true, "The path to the XML job descriptor");
    jobDescriptor.setArgName("XML_Job_Descriptor");
    jobDescriptor.setArgs(1);
    jobDescriptor.setRequired(true);
    options.addOption(jobDescriptor);

    Option registerListeners = new Option("rl", "listener", false,
            "Register the specified Scheduler listener for each user. If no listener is specified, then a 'simple' scheduler listener will be registered");
    registerListeners.setRequired(false);
    registerListeners.setOptionalArg(true);
    registerListeners.setArgs(1);
    registerListeners.setArgName("listenerClassName");
    options.addOption(registerListeners);

    Option jobRepetition = new Option("rp", "repeats", true,
            "The number of times the job will be submitted(optional parameter; by default it will be set to 1)");
    jobRepetition.setRequired(false);
    jobRepetition.setArgName("jobRepeats");
    jobRepetition.setArgs(1);
    options.addOption(jobRepetition);

    Option jobResult = new Option("jr", "jobResult", false,
            "Fetch the result for the submitted jobs. Optional parameter, defaults to false");
    jobResult.setRequired(false);
    options.addOption(jobResult);

    OptionGroup initialStateGroup = new OptionGroup();
    initialStateGroup.setRequired(false);

    Option gui = new Option("gu", "gui", false,
            "Simulate an user which interacts with the Scheduler using a GUI(all scheduler state will be downloaded at login)");
    gui.setRequired(false);
    initialStateGroup.addOption(gui);

    Option cli = new Option("cu", "cli", false,
            "Simulate an user which interacts with the Scheduler using a CLI(the scheduler state will NOT be downloaded at login)");
    cli.setRequired(false);
    initialStateGroup.addOption(cli);

    options.addOptionGroup(initialStateGroup);

    Option myEventsOnly = new Option("me", "myEvsOnly", false,
            "While registering a listener, get only the events which concern me");
    myEventsOnly.setRequired(false);
    options.addOption(myEventsOnly);
}

From source file:scoutdoc.main.Main.java

/**
 * @param args/*  w  ww .  j  a v  a  2 s  . c om*/
 */
public static void main(String[] args) {
    Option optHelp = new Option(HELP_ID, "help", false, "print this message");

    Option optProp = new Option(PROP_ID, "config", true, "configuration file");
    optProp.setArgName("file");

    //source
    Option optTask = new Option(SOURCE_TASKS_ID, "task", true, "(source) one or many task files");
    optTask.setArgName("files");
    optTask.setArgs(Option.UNLIMITED_VALUES);

    Option optAllPages = new Option(SOURCE_ALL_PAGES_ID, "pages", false,
            "(source) use the pages contained in the source folder");

    Option optListPages = new Option(SOURCE_LIST_ID, "list", true,
            "(source) list of pages contained in the file");
    optListPages.setArgName("file");

    Option optRecentChange = new Option(SOURCE_RECENT_CHANGES_ID, "recent-changes", false,
            "(source) use the pages from the wiki recent changes");

    Option optRss = new Option(SOURCE_RSS_ID, "rss", false,
            "(source) use the pages from the rss feed of the wiki");

    OptionGroup sourceGroup = new OptionGroup();
    sourceGroup.setRequired(true);
    sourceGroup.addOption(optTask);
    sourceGroup.addOption(optAllPages);
    sourceGroup.addOption(optListPages);
    sourceGroup.addOption(optRecentChange);
    sourceGroup.addOption(optRss);

    Option optfilter = new Option(SOURCE_FILTER_ID, "filter", true, "Filter for list of pages used as source");
    optfilter.setArgName("class");

    List<String> values = Lists.newArrayList();
    for (Operation o : Operation.values()) {
        values.add(o.name());
    }
    Option optOperation = new Option(OPERATION_ID, "operation", true,
            "operation: " + Joiner.on(", ").join(values));
    optOperation.setArgName("operations");
    optOperation.setArgs(Option.UNLIMITED_VALUES);
    optOperation.setRequired(true);

    Option optOutputCheckstyle = new Option(OUTPUT_CHECKSTYLE_ID, "output-checkstyle", true,
            "(CHECK output) create a xml checkstyle file (<filename> is optional. Default: "
                    + DEFAULT_CHECKSTYLE_NAME + ")");
    optOutputCheckstyle.setArgName("filename");
    optOutputCheckstyle.setOptionalArg(true);

    Option optOutputDashboard = new Option(OUTPUT_DASHBOARD_ID, "output-dashboard", true,
            "(CHECK output) create an html dashboard (<folder> is optional. Default: " + DEFAULT_DASHBOARD_NAME
                    + ")");
    optOutputDashboard.setArgName("folder");
    optOutputDashboard.setOptionalArg(true);

    Options options = new Options();
    options.addOption(optHelp);
    options.addOption(optProp);
    options.addOptionGroup(sourceGroup);
    options.addOption(optfilter);
    options.addOption(optOperation);
    options.addOption(optOutputCheckstyle);
    options.addOption(optOutputDashboard);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(HELP_ID)) {
            printHelpAndExit(options);
        }

        if (cmd.hasOption(PROP_ID)) {
            ProjectProperties.initProperties(cmd.getOptionValue(PROP_ID));
        }
        Pages.initPageList();

        List<Operation> operations = readOptionEnum(cmd, optOperation, Operation.class);
        List<Task> tasks = readTasks(cmd, optTask);

        Collection<Page> pageList;
        if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
            pageList = PageUtility.loadPages(ProjectProperties.getFolderWikiSource());
        } else if (cmd.hasOption(SOURCE_LIST_ID)) {
            String name = cmd.getOptionValue(SOURCE_LIST_ID);
            try {
                pageList = PageUtility.readList(name);
            } catch (IOException e) {
                throw new MissingArgumentException("IOException for file <" + name + "> for <"
                        + optListPages.getLongOpt() + "> : " + e.getMessage());
            }
        } else {
            pageList = Collections.emptyList();
        }

        IPageFilter filter;
        if (cmd.hasOption(SOURCE_FILTER_ID)) {
            if (tasks.size() > 0) {
                throw new MissingArgumentException("Filter <" + optfilter.getLongOpt()
                        + "> is not allowed for source <" + optTask.getLongOpt() + ">.");
            }
            filter = newInstance(cmd.getOptionValue(SOURCE_FILTER_ID), IPageFilter.class,
                    new AcceptAllPageFilter());
        } else {
            filter = new AcceptAllPageFilter();
        }
        List<Page> pages = Lists.newArrayList();
        for (Page page : pageList) {
            if (filter.keepPage(page)) {
                pages.add(page);
            }
        }

        if (operations.contains(Operation.FETCH)) {
            if (pages.size() > 0) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                RelatedPagesStrategy strategy;
                if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
                    strategy = RelatedPagesStrategy.NO_RELATED_PAGES;
                } else if (cmd.hasOption(SOURCE_LIST_ID)) {
                    strategy = RelatedPagesStrategy.IMAGES_TEMPLATES_AND_LINKS;
                } else {
                    throw new IllegalStateException("Page list comes from an unexpected option");
                }
                sdf.execute(pages, strategy);
            } else if (cmd.hasOption(SOURCE_RECENT_CHANGES_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRecentChanges(filter);
            } else if (cmd.hasOption(SOURCE_RSS_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRss(filter);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocFetch sdf = new ScoutDocFetch();
                    sdf.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

        if (operations.contains(Operation.CHECK)) {
            ScoutDocCheck sdc = new ScoutDocCheck();
            List<Check> checks = Lists.newArrayList();
            ensureNotSet(cmd, optRecentChange, Operation.CHECK);
            ensureNotSet(cmd, optRss, Operation.CHECK);
            if (pages.size() > 0) {
                checks = sdc.analysePages(pages);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocCheck sdcForTask = new ScoutDocCheck();
                    checks.addAll(sdcForTask.execute(task));
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
            //output:
            if (cmd.hasOption(OUTPUT_CHECKSTYLE_ID)) {
                String fileName = cmd.getOptionValue(OUTPUT_CHECKSTYLE_ID, DEFAULT_CHECKSTYLE_NAME);
                sdc.writeCheckstyleFile(checks, fileName);
            }
            if (cmd.hasOption(OUTPUT_DASHBOARD_ID)) {
                String folderName = cmd.getOptionValue(OUTPUT_DASHBOARD_ID, DEFAULT_DASHBOARD_NAME);
                sdc.writeDashboardFiles(checks, folderName);
            }
        }

        if (operations.contains(Operation.CONVERT)) {
            ensureNotSet(cmd, optAllPages, Operation.CONVERT);
            ensureNotSet(cmd, optListPages, Operation.CONVERT);
            ensureNotSet(cmd, optRecentChange, Operation.CONVERT);
            ensureNotSet(cmd, optRss, Operation.CONVERT);
            if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocConverter sdc = new ScoutDocConverter();
                    sdc.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

    } catch (MissingOptionException e) {
        // Check if it is an error or if optHelp was selected.
        boolean help = false;
        try {
            Options helpOptions = new Options();
            helpOptions.addOption(optHelp);
            CommandLineParser parser = new PosixParser();
            CommandLine line = parser.parse(helpOptions, args);
            if (line.hasOption(HELP_ID)) {
                help = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (!help) {
            System.err.println(e.getMessage());
            System.err.flush();
        }
        printHelpAndExit(options);
    } catch (MissingArgumentException e) {
        System.err.println(e.getMessage());
        printHelpAndExit(options);
    } catch (ParseException e) {
        System.err.println("Error while parsing the command line: " + e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:treecmp.commandline.CommandLineParser.java

public Command run(String args[]) {
    Command cmd = null;//from ww  w  .jav a 2s . co  m
    DefinedMetricsSet DMSet = DefinedMetricsSet.getInstance();

    Option oS = new Option("s", S_DESC);
    Option oW = new Option("w", W_DESC);
    oW.setArgName(W_ARG);
    oW.setArgs(1);
    Option oM = new Option("m", M_DESC);
    Option oR = new Option("r", R_DESC);
    oR.setArgName(R_ARG);
    oR.setArgs(1);

    OptionGroup cmdOpts = new OptionGroup();
    cmdOpts.addOption(oS);
    cmdOpts.addOption(oW);
    cmdOpts.addOption(oM);
    cmdOpts.addOption(oR);

    cmdOpts.setRequired(true);
    //set metric option
    Option oD = new Option("d", D_DESC);
    oD.setArgName(D_ARG);
    oD.setValueSeparator(' ');
    oD.setArgs(DMSet.size());
    oD.setRequired(true);

    Option oI = new Option("i", I_DESC);
    oI.setArgName(I_ARG);
    oI.setArgs(1);
    oI.setRequired(true);

    Option oO = new Option("o", O_DESC);
    oO.setArgs(1);
    oO.setArgName(O_ARG);
    oO.setRequired(true);

    Option oP = new Option("P", P_DESC);
    Option oSS = new Option("N", SS_DESC);
    Option oII = new Option("I", II_DESC);

    Option oOO = new Option("O", OO_DESC);
    Option oA = new Option("A", A_DESC);
    OptionGroup customMOpts = new OptionGroup();
    customMOpts.addOption(oOO);
    customMOpts.addOption(oA);

    Options opts = new Options();

    opts.addOptionGroup(cmdOpts);
    opts.addOption(oD);
    opts.addOption(oI);
    opts.addOption(oO);
    opts.addOption(oP);
    opts.addOption(oSS);
    opts.addOption(oII);
    opts.addOptionGroup(customMOpts);

    //getting version from manifest file
    String version = CommandLineParser.class.getPackage().getImplementationVersion();
    if (version == null) {
        version = "";
    }
    String FOOTER = "";
    String HEADER = " ";
    String APP_NAME = "TreeCmp version " + version + "\n";
    GnuParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new OptOrder());

    System.out.println(APP_NAME);
    if (args.length == 0) {
        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
        return null;
    }

    try {
        CommandLine commandLine = parser.parse(opts, args);
        if (commandLine != null) {
            // process these values
            //set IO settings
            String inputFileName = (String) commandLine.getOptionValue(oI.getOpt());
            String outputFileName = (String) commandLine.getOptionValue(oO.getOpt());

            if (inputFileName == null) {
                System.out.println("Error: input file not specified!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

                return null;
            }
            if (outputFileName == null) {
                System.out.println("Error: output file not specified!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                return null;
            }

            //commandLine.
            IOSettings IOset = IOSettings.getIOSettings();
            IOset.setInputFile(inputFileName);
            IOset.setOutputFile(outputFileName);

            //custom additinal options
            ArrayList<Option> custOpts = new ArrayList<Option>();

            if (commandLine.hasOption(oP.getOpt())) {
                IOset.setPruneTrees(true);
                custOpts.add(oP);
            }
            if (commandLine.hasOption(oSS.getOpt())) {
                IOset.setRandomComparison(true);
                custOpts.add(oSS);
            }
            if (commandLine.hasOption(oA.getOpt())) {
                IOset.setGenAlignments(true);
                custOpts.add(oA);
            }
            if (commandLine.hasOption(oOO.getOpt())) {
                IOset.setOptMsMcByRf(true);
                custOpts.add(oOO);
            }
            if (commandLine.hasOption(oII.getOpt())) {
                IOset.setGenSummary(true);
                custOpts.add(oII);
            }
            Collections.sort(custOpts, new OptOrder());

            //set active metrics
            ActiveMetricsSet AMSet = ActiveMetricsSet.getInstance();

            final String[] metrics = commandLine.getOptionValues(oD.getOpt());
            for (int i = 0; i < metrics.length; i++) {

                final DefinedMetric definedMetric = DMSet.getDefinedMetric(metrics[i]);
                if (definedMetric != null) {
                    AMSet.addMetric(definedMetric);
                } else {
                    System.out.print("Error: ");
                    System.out.println("Metric: " + metrics[i] + " is unknown\n.");
                    formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                    return null;
                }

            }

            //set active command
            String analysisType = "";

            if (commandLine.hasOption(oW.getOpt())) {
                String sWindowSize = (String) commandLine.getOptionValue(oW.getOpt());
                int iWindowSize = Integer.parseInt(sWindowSize);
                cmd = new RunWCommand(1, "-w", iWindowSize);
                analysisType = "window comparison mode (-w) with window size: " + iWindowSize;
            } else if (commandLine.hasOption(oM.getOpt())) {
                cmd = new RunMCommand(0, "-m");
                analysisType = "matrix comparison mode (-m)";
            } else if (commandLine.hasOption(oS.getOpt())) {
                cmd = new RunSCommand(0, "-s");
                analysisType = "overlapping pair comparison mode (-s)";
            } else if (commandLine.hasOption(oR.getOpt())) {
                String sRefTreeFile = (String) commandLine.getOptionValue(oR.getOpt());
                cmd = new RunRCommand(0, "-r", sRefTreeFile);
                analysisType = " ref-to-all comparison mode (-r)";
            } else {
                System.out.println("Error: type of the analysis not specified correctly!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                return null;
            }

            printOptionsInEffect(analysisType, AMSet, inputFileName, outputFileName, custOpts);

            return cmd;
        } else {
            //Error during parsing command line
            return null;
        }
    } catch (ParseException ex) {
        log.log(Level.WARNING, "Could not parse command line arguments.", ex);
        System.out.println(CMD_ERROR);

        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

    } catch (NumberFormatException ex) {
        System.out.print("Error: ");
        System.out.println("window size should be an integer.\n");
        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

    }
    return cmd;
}