Example usage for org.apache.commons.cli CommandLine hasOption

List of usage examples for org.apache.commons.cli CommandLine hasOption

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine hasOption.

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.chschmid.huemorse.server.HueMorse.java

public static void main(String args[]) throws Exception {
    // Application Title
    System.out.println(TITLE);// w  w w .j av  a2s  . c o m

    // Apache CLI Parser
    Options options = getCLIOptions();
    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("b"))
            bridgeIP = line.getOptionValue("b");
        else if (!(line.hasOption("s"))) {
            System.out.println(ERROR_NO_IP);
            return;
        }
        if (line.hasOption("c"))
            cli = true;
        if (line.hasOption("d"))
            DEBUG = true;
        if (line.hasOption("l"))
            lightID = Integer.parseInt(line.getOptionValue("l"));
        if (line.hasOption("u"))
            username = line.getOptionValue("u");
        if (line.hasOption("s"))
            search = true;
        if (line.hasOption("h")) {
            printHelp();
            return;
        }
    } catch (ParseException exp) {
        System.out.println(HUEMORSE + ": " + exp.getMessage());
        System.out.println(ERROR_CLI);
        return;
    }

    hue = new HueMorseInterface();
    if (search && bridgeIP.equals(""))
        searchAndListBridges();
    else {
        if (DEBUG) {
            System.out.println("Bridge IP: " + bridgeIP);
            System.out.println("Username:  " + username);
        }
        hue.connect(bridgeIP, username);
        hue.setLightID(lightID);

        if (search)
            searchAndListLights();
        else {
            if (cli)
                simpleCommandLineInterface();
            else
                startServers();
        }
    }
    hue.close();
    System.exit(0);
}

From source file:edu.cwru.jpdg.JPDG.java

public static void main(String[] argv) throws pDG_Builder.Error {
    final Option helpOpt = new Option("h", "help", false, "print this message");
    final Option outputOpt = new Option("o", "output", true, "output file location");
    final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze");
    final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories");
    final Option classOpt = new Option("c", "classpath", true, "classpath for soot");
    final Option labelOpt = new Option("l", "label-type", true,
            "label type, valid choices are: expr-tree, inst");
    final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();

    options.addOption(helpOpt);//from w ww  .j av  a 2  s .  com
    options.addOption(outputOpt);
    options.addOption(baseOpt);
    options.addOption(classOpt);
    options.addOption(labelOpt);
    options.addOption(excludeOpt);

    String cp = null;
    String base_dir = null;
    String label_type = "expr-tree";
    String output_file = null;
    List<String> excluded = new ArrayList<String>();

    try {
        GnuParser parser = new GnuParser();
        CommandLine line = parser.parse(options, argv);

        if (line.hasOption(helpOpt.getLongOpt())) {
            Usage(options);
        }

        cp = line.getOptionValue(classOpt.getLongOpt());
        base_dir = line.getOptionValue(baseOpt.getLongOpt());
        label_type = line.getOptionValue(labelOpt.getLongOpt());
        output_file = line.getOptionValue(outputOpt.getLongOpt());
        String[] ex = line.getOptionValues(excludeOpt.getLongOpt());
        if (ex != null) {
            excluded = Arrays.asList(ex);
        }
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    List<String> dirs = new ArrayList<String>();
    dirs.add(base_dir);

    soot.Scene S = runSoot(cp, dirs, excluded);
    writeGraph(build_PDG(S, excluded, label_type), output_file);
}

From source file:ca.uqac.info.trace.TraceGenerator.java

public static void main(String[] args) {
    // Parse command line arguments
    Options options = setupOptions();//w ww. j  ava 2  s .c om
    CommandLine c_line = setupCommandLine(args, options);
    int verbosity = 0, max_events = 1000000;

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    String generator_name = "simplerandom";
    if (c_line.hasOption("g")) {
        generator_name = c_line.getOptionValue("generator");
    }
    long time_per_msg = 1000;
    if (c_line.hasOption("i")) {
        time_per_msg = Integer.parseInt(c_line.getOptionValue("i"));
    }
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (c_line.hasOption("e")) {
        max_events = Integer.parseInt(c_line.getOptionValue("e"));
    }
    String feeder_params = "";
    if (c_line.hasOption("parameters")) {
        feeder_params = c_line.getOptionValue("parameters");
    }
    MessageFeeder mf = instantiateFeeder(generator_name, feeder_params);
    if (mf == null) {
        System.err.println("Unrecognized feeder name");
        System.exit(ERR_ARGUMENTS);
    }
    // Trap Ctrl-C to send EOT before shutting down
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            char EOT = 4;
            System.out.print(EOT);
        }
    });
    for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) {
        long time_begin = System.nanoTime();
        String message = mf.next();
        StringBuilder out = new StringBuilder();
        out.append(message);
        System.out.print(out.toString());
        long time_end = System.nanoTime();
        long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f);
        if (duration > 0) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
            }
        }
        if (verbosity > 0) {
            System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg);
        }
    }
}

From source file:com.consol.citrus.Citrus.java

/**
 * Main CLI method./*from w  w w.  j  a  va  2s  .  c om*/
 * @param args
 */
public static void main(String[] args) {
    Options options = new CitrusCliOptions();
    HelpFormatter formatter = new HelpFormatter();

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

        if (cmd.hasOption("help")) {
            formatter.printHelp("CITRUS TestFramework", options);
            return;
        }

        Citrus citrus = new Citrus(cmd);
        citrus.run();
    } catch (ParseException e) {
        log.error("Failed to parse command line arguments", e);
        formatter.printHelp("CITRUS TestFramework", options);
    }
}

From source file:com.github.trohovsky.jira.analyzer.Main.java

public static void main(String[] args) throws Exception {

    final Options options = new Options();
    options.addOption("u", true, "username");
    options.addOption("p", true, "password (optional, if not provided, the password is prompted)");
    options.addOption("h", false, "show this help");
    options.addOption("s", true,
            "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or"
                    + " 'per_month'");
    options.addOption("d", true, "CSV delimiter");

    // parsing of the command line arguments
    final CommandLineParser parser = new DefaultParser();
    CommandLine cmdLine = null;
    try {//from   w  w  w  .  j av  a2s.co  m
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
            return;
        }
        if (cmdLine.getArgs().length != 3) {
            throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE"
                    + " PATH_TO_PARAMETER_FILE");
        }
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
        return;
    }
    final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d')
            : CSV_DELIMITER);

    final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]);
    final String jqlQueryTemplate = cmdLine.getArgs()[1];
    final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter);
    final String username = cmdLine.getOptionValue("u");
    String password = cmdLine.getOptionValue("p");
    final String strategy = cmdLine.getOptionValue("s");

    try {
        // initialization of the REST client
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        if (username != null) {
            if (password == null) {
                final Console console = System.console();
                final char[] passwordCharacters = console.readPassword("Password: ");
                password = new String(passwordCharacters);
            }
            restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password);
        } else {
            restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler());
        }
        final SearchRestClient searchRestClient = restClient.getSearchClient();

        // choosing of an analyzer strategy
        AnalyzerStrategy analyzer = null;
        if (strategy != null) {
            switch (strategy) {
            case "issues_total":
                analyzer = new IssuesTotalStrategy(searchRestClient);
                break;
            case "issues_per_month":
                analyzer = new IssuesPerMonthStrategy(searchRestClient);
                break;
            default:
                System.err.println("The strategy does not exist");
                return;
            }
        } else {
            analyzer = new IssuesTotalStrategy(searchRestClient);
        }

        // analyzing
        for (List<String> queryParameters : queryParametersData) {
            analyzer.analyze(jqlQueryTemplate, queryParameters);
        }
    } finally {
        // destroy the REST client, otherwise it stucks
        restClient.close();
    }
}

From source file:com.examples.cloud.speech.StreamingRecognizeClient.java

public static void main(String[] args) throws Exception {

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;//from w w  w.j  a  va 2s .  co  m
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("file").withDescription("path to audio file").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("file")) {
            audioFile = line.getOptionValue("file");
        } else {
            System.err.println("An Audio file must be specified (e.g. /foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port);
    StreamingRecognizeClient client = new StreamingRecognizeClient(channel, audioFile, sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:com.google.testing.pogen.PageObjectGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    if (args.length == 0) {
        printUsage(System.out);//from   www.j  a  v a  2  s . c om
        return;
    }

    String commandName = args[0];
    // @formatter:off
    Options options = new Options()
            .addOption(OptionBuilder.withDescription(
                    "Attribute name to be assigned in tagas containing template variables (default is 'id').")
                    .hasArg().withLongOpt("attr").create('a'))
            .addOption(OptionBuilder.withDescription("Print help for this command.").withLongOpt("help")
                    .create('h'))
            .addOption(OptionBuilder.withDescription("Print processed files verbosely.").withLongOpt("verbose")
                    .create('v'));
    // @formatter:on

    String helpMessage = null;
    if (commandName.equals(GENERATE_COMMAND)) {
        // @formatter:off
        options.addOption(OptionBuilder.withDescription("Package name of generating skeleton test code.")
                .hasArg().isRequired().withLongOpt("package").create('p'))
                .addOption(OptionBuilder.withDescription("Output directory of generating skeleton test code.")
                        .hasArg().isRequired().withLongOpt("out").create('o'))
                .addOption(OptionBuilder.withDescription(
                        "Root input directory of html template files for analyzing the suffixes of the package name.")
                        .hasArg().isRequired().withLongOpt("in").create('i'))
                .addOption(OptionBuilder.withDescription("Regex for finding html template files.").hasArg()
                        .withLongOpt("regex").create('e'))
                .addOption(OptionBuilder.withDescription("Option for finding html template files recursively.")
                        .withLongOpt("recursive").create('r'));
        // @formatter:on
        helpMessage = "java PageObjectGenerator generate -o <test_out_dir> -p <package_name> -i <root_directory> "
                + " [OPTIONS] <template_file1> <template_file2> ...\n"
                + "e.g. java PageObjectGenerator generate -a class -o PageObjectGeneratorTest/src/test/java/com/google/testing/pogen/pages"
                + " -i PageObjectGeneratorTest/src/main/resources -p com.google.testing.pogen.pages -e (.*)\\.html -v";
    } else if (commandName.equals(MEASURE_COMMAND)) {
        helpMessage = "java PageObjectGenerator measure [OPTIONS] <template_file1> <template_file2> ...";
    } else if (commandName.equals(LIST_COMMAND)) {
        helpMessage = "java PageObjectGenerator list <template_file1> <template_file2> ...";
    } else {
        System.err.format("'%s' is not a PageObjectGenerator command.", commandName);
        printUsage(System.err);
        System.exit(-1);
    }

    BasicParser cmdParser = new BasicParser();
    HelpFormatter f = new HelpFormatter();
    try {
        CommandLine cl = cmdParser.parse(options, Arrays.copyOfRange(args, 1, args.length));
        if (cl.hasOption('h')) {
            f.printHelp(helpMessage, options);
            return;
        }

        Command command = null;
        String[] templatePaths = cl.getArgs();
        String attributeName = cl.getOptionValue('a');
        attributeName = attributeName != null ? attributeName : "id";
        if (commandName.equals(GENERATE_COMMAND)) {
            String rootDirectoryPath = cl.getOptionValue('i');
            String templateFilePattern = cl.getOptionValue('e');
            boolean isRecusive = cl.hasOption('r');
            command = new GenerateCommand(templatePaths, cl.getOptionValue('o'), cl.getOptionValue('p'),
                    attributeName, cl.hasOption('v'), rootDirectoryPath, templateFilePattern, isRecusive);
        } else if (commandName.equals(MEASURE_COMMAND)) {
            command = new MeasureCommand(templatePaths, attributeName, cl.hasOption('v'));
        } else if (commandName.equals(LIST_COMMAND)) {
            command = new ListCommand(templatePaths, attributeName);
        }
        try {
            command.execute();
            return;
        } catch (FileProcessException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println("Errors occur in processing files.");
            System.err.println(e.getMessage());
        }
    } catch (ParseException e) {
        System.err.println("Errors occur in parsing the command arguments.");
        System.err.println(e.getMessage());
        f.printHelp(helpMessage, options);
    }
    System.exit(-1);
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

public static void main(String[] args) {
    Options options = new Options().addOption("t", "trace", false, "Enable tracing.")
            .addOption("d", "debug", false, "Enable debug output.")
            .addOption("s", "size", true, "Sets amount of memory available.")
            .addOption("v", "version", false, "Prints the TVI version number.")
            .addOption("r", "renumber", true, "Renumbers the lines in a files.")
            .addOption("h", "help", false, "Prints this help message");
    CommandLineParser parser = new DefaultParser();
    try {/*  w w w  .j a v  a2s .  c om*/
        CommandLine opts = parser.parse(options, args);
        if (opts.hasOption('h')) {
            help(options);
            return;
        }
        if (opts.hasOption('v')) {
            System.out.println();
            System.out.println("The Vassar Interpreter v" + Version.getVersion());
            System.out.println(COPYRIGHT);
            System.out.println();
            return;
        }
        if (opts.hasOption('r')) {
            int returnCode = 0;
            try {
                renumber(opts.getOptionValue('r'));
            } catch (IOException e) {
                e.printStackTrace();
                returnCode = 1;
            }
            System.exit(returnCode);
        }
        files = opts.getArgs();
        if (files.length == 0) {
            System.out.println("ERROR: No file names given.");
            help(options);
            System.exit(1);
        }
        if (opts.hasOption('s')) {
            try {
                memory = Integer.parseInt(opts.getOptionValue('s'));
            } catch (NumberFormatException e) {
                System.out.println("ERROR: Invalid --size parameter.");
                help(options);
                System.exit(1);
            }
        }
        if (opts.hasOption('t')) {
            tracing = true;
        }
        if (opts.hasOption('d')) {
            debugging = true;
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        help(options);
        System.exit(1);
    }
    Main app = new Main();
    Arrays.stream(files).forEach(app::run);
}

From source file:boa.evaluator.BoaEvaluator.java

public static void main(final String[] args) {
    final Options options = new Options();

    options.addOption("i", "input", true, "input Boa source file (*.boa)");
    options.addOption("d", "data", true, "path to local data directory");
    options.addOption("o", "output", true, "output directory");

    options.getOption("i").setRequired(true);
    options.getOption("d").setRequired(true);

    try {/*from   w ww . j  a va2 s .c o m*/
        if (args.length == 0) {
            printHelp(options, null);
            return;
        } else {
            final CommandLine cl = new PosixParser().parse(options, args);

            if (cl.hasOption('i') && cl.hasOption('d')) {
                final BoaEvaluator evaluator;
                try {
                    if (cl.hasOption('o')) {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'),
                                cl.getOptionValue('o'));
                    } else {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'));
                    }
                } catch (final IOException e) {
                    System.err.print(e);
                    return;
                }

                if (!evaluator.compile()) {
                    System.err.println("Compilation Failed");
                    return;
                }

                final long start = System.currentTimeMillis();
                evaluator.evaluate();
                final long end = System.currentTimeMillis();

                System.out.println("Total Time Taken: " + (end - start));
                System.out.println(evaluator.getResults());
            } else {
                printHelp(options, "missing required options: -i <arg> and -d <arg>");
                return;
            }
        }
    } catch (final org.apache.commons.cli.ParseException e) {
        printHelp(options, e.getMessage());
    }
}

From source file:com.nubits.nubot.launch.MainLaunch.java

/**
 * Start the NuBot. start if config is valid and other instance is running
 *
 * @param args a list of valid arguments
 *///from w  w  w.  j  ava 2s .c o  m
public static void main(String args[]) {

    Global.sessionPath = "logs" + "/" + Settings.SESSION_LOG + System.currentTimeMillis();
    MDC.put("session", Global.sessionPath);
    LOG.info("defined session path " + Global.sessionPath);

    CommandLine cli = parseArgs(args);

    boolean runGUI = false;
    String configFile;

    boolean defaultCfg = false;
    if (cli.hasOption(CLIOptions.GUI)) {
        runGUI = true;
        LOG.info("Running " + Settings.APP_NAME + " with GUI");

        if (!cli.hasOption(CLIOptions.CFG)) {
            LOG.info("Setting default config file location :" + Settings.DEFAULT_CONFIG_FILE_PATH);
            //Cancel any previously existing file, if any
            File f = new File(Settings.DEFAULT_CONFIG_FILE_PATH);
            if (f.exists() && !f.isDirectory()) {
                LOG.warn("Detected a non-empty configuration file, resetting it to default. "
                        + "Printing existing file content, for reference:\n"
                        + FilesystemUtils.readFromFile(Settings.DEFAULT_CONFIG_FILE_PATH));
                FilesystemUtils.deleteFile(Settings.DEFAULT_CONFIG_FILE_PATH);
            }
            //Create a default file
            SaveOptions.optionsReset(Settings.DEFAULT_CONFIG_FILE_PATH);
            defaultCfg = true;
        }
    }
    if (cli.hasOption(CLIOptions.CFG) || defaultCfg) {
        if (defaultCfg) {
            configFile = Settings.DEFAULT_CONFIG_FILE_PATH;
        } else {
            configFile = cli.getOptionValue(CLIOptions.CFG);
        }

        if (runGUI) {
            SessionManager.setConfigGlobal(configFile, true);
            try {
                UiServer.startUIserver(configFile, defaultCfg);
                Global.createShutDownHook();
            } catch (Exception e) {
                LOG.error("error setting up UI server " + e);
            }

        } else {
            LOG.info("Run NuBot from CLI");
            //set global config
            SessionManager.setConfigGlobal(configFile, false);
            sessionLOG.debug("launch bot");
            try {
                SessionManager.setModeStarting();
                SessionManager.launchBot(Global.options);
                Global.createShutDownHook();
            } catch (NuBotRunException e) {
                exitWithNotice("could not launch bot " + e);
            }
        }

    } else {
        exitWithNotice("Missing " + CLIOptions.CFG + ". run nubot with \n" + CLIOptions.USAGE_STRING);
    }

}