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.thoughtworks.xstream.tools.benchmark.parsers.ParserBenchmark.java

public static void main(String[] args) {
    int counter = 1000;

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Harness harness = new Harness();
    harness.addMetric(new DeserializationSpeedMetric(0, false) {
        public String toString() {
            return "Initial run deserialization";
        }/*from w ww.  j  ava  2s. c  om*/
    });

    Parser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        String name = null;
        if (commandLine.hasOption('p')) {
            name = commandLine.getOptionValue('p');
        }
        if (name == null || name.equals("DOM")) {
            harness.addProduct(new XStreamDom());
        }
        if (name == null || name.equals("JDOM")) {
            harness.addProduct(new XStreamJDom());
        }
        if (name == null || name.equals("DOM4J")) {
            harness.addProduct(new XStreamDom4J());
        }
        if (name == null || name.equals("XOM")) {
            harness.addProduct(new XStreamXom());
        }
        if (name == null || name.equals("BEAStAX")) {
            harness.addProduct(new XStreamBEAStax());
        }
        if (name == null || name.equals("Woodstox")) {
            harness.addProduct(new XStreamWoodstox());
        }
        if (JVM.is16() && (name == null || name.equals("SJSXP"))) {
            harness.addProduct(new XStreamSjsxp());
        }
        if (name == null || name.equals("Xpp3")) {
            harness.addProduct(new XStreamXpp3());
        }
        if (name == null || name.equals("kXML2")) {
            harness.addProduct(new XStreamKXml2());
        }
        if (name == null || name.equals("Xpp3DOM")) {
            harness.addProduct(new XStreamXpp3DOM());
        }
        if (name == null || name.equals("kXML2DOM")) {
            harness.addProduct(new XStreamKXml2DOM());
        }
        if (commandLine.hasOption('n')) {
            counter = Integer.parseInt(commandLine.getOptionValue('n'));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.addTarget(new JavaBeanTarget());
    if (false) {
        harness.addTarget(new FieldReflection());
        harness.addTarget(new HierarchyLevelReflection());
        harness.addTarget(new InnerClassesReflection());
        harness.addTarget(new StaticInnerClassesReflection());
    }
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
}

From source file:com.evolveum.midpoint.tools.gui.Main.java

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

    Option propertiesLocaleDelimiter = new Option("d", "delimiter", true,
            "Delimiter for locale name in properties file. Default is '_' (underscore).");
    options.addOption(propertiesLocaleDelimiter);
    Option targetFolder = new Option("t", "targetFolder", true,
            "Target folder where properties file is generated.");
    targetFolder.setRequired(true);//ww w  .  j a  va  2  s  .c  o m
    options.addOption(targetFolder);
    Option baseFolder = new Option("b", "baseFolder", true, "Base folder used for properties files searching.");
    baseFolder.setRequired(true);
    options.addOption(baseFolder);
    Option localesToCheck = new Option("l", "locale", true, "Locales to check.");
    localesToCheck.setRequired(true);
    options.addOption(localesToCheck);
    Option recursiveFolderToCheck = new Option("r", "folderRecursive", true,
            "Folder used for recursive search for properties files.");
    options.addOption(recursiveFolderToCheck);
    Option nonRecursiveFolderToCheck = new Option("n", "folderNonRecursive", true,
            "Folder used for non recursive search for properties files.");
    options.addOption(nonRecursiveFolderToCheck);
    Option help = new Option("h", "help", false, "Print this help.");
    options.addOption(help);
    Option disableBackup = new Option("db", "disableBackup", false, "Disable backuping property files.");
    options.addOption(disableBackup);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        if (!line.hasOption(recursiveFolderToCheck.getOpt())
                && !line.hasOption(nonRecursiveFolderToCheck.getOpt())) {
            printHelp(options);
            return;
        }

        GeneratorConfiguration config = new GeneratorConfiguration();
        if (line.hasOption(baseFolder.getOpt())) {
            config.setBaseFolder(new File(line.getOptionValue(baseFolder.getOpt())));
        }
        if (line.hasOption(targetFolder.getOpt())) {
            config.setTargetFolder(new File(line.getOptionValue(targetFolder.getOpt())));
        }
        if (line.hasOption(propertiesLocaleDelimiter.getOpt())) {
            config.setPropertiesLocaleDelimiter(line.getOptionValue(propertiesLocaleDelimiter.getOpt()));
        }
        if (line.hasOption(recursiveFolderToCheck.getOpt())) {
            String[] recursives = line.getOptionValues(recursiveFolderToCheck.getOpt());
            if (recursives != null && recursives.length > 0) {
                for (String recursive : recursives) {
                    config.getRecursiveFolderToCheck().add(recursive);
                }
            }
        }
        if (line.hasOption(nonRecursiveFolderToCheck.getOpt())) {
            String[] nonRecursives = line.getOptionValues(nonRecursiveFolderToCheck.getOpt());
            if (nonRecursives != null && nonRecursives.length > 0) {
                for (String nonRecursive : nonRecursives) {
                    config.getNonRecursiveFolderToCheck().add(nonRecursive);
                }
            }
        }

        if (line.hasOption(localesToCheck.getOpt())) {
            String[] locales = line.getOptionValues(localesToCheck.getOpt());
            for (String locale : locales) {
                config.getLocalesToCheck().add(getLocaleFromString(locale));
            }
        }

        if (line.hasOption(disableBackup.getOpt())) {
            config.setDisableBackup(true);
        }

        PropertiesGenerator generator = new PropertiesGenerator(config);
        generator.generate();
    } catch (ParseException ex) {
        System.out.println("Error: " + ex.getMessage());
        printHelp(options);
    } catch (Exception ex) {
        System.out.println("Something is broken.");
        ex.printStackTrace();
    }
}

From source file:edu.mines.acmX.exhibit.runner.ModuleManagerRunner.java

/**
 * Main function for the ModuleManager framework. Creates an instance of
 * ModuleManager and runs it.//from w w w  . ja v a2s. c o m
 * 
 * Arguments: The single argument that is needed is the path to a valid
 * module manager manifest file. This is specified using the --manifest arg.
 * For additional documentation on running the module manager please refer
 * to the wiki in Common.REPOSITORY
 */
public static void main(String[] args) {
    CommandLineParser cl = new GnuParser();
    CommandLine cmd;
    Options opts = generateCLOptions();
    try {
        cmd = cl.parse(opts, args);

        if (cmd.hasOption("help")) {
            printHelp(opts);
        } else {

            if (cmd.hasOption("manifest")) {
                ModuleManager.configure(cmd.getOptionValue("manifest"));
            } else {
                System.out.println("A Module Manager Manifest is required to run the module manager"
                        + "Please specify with the --manifest switch");
                System.exit(1);
            }
            ModuleManager m;
            m = ModuleManager.getInstance();
            //publicizeRmiInterface(m, RMI_REGISTRY_PORT);
            m.run();
        }

    } catch (ParseException e) {
        printHelp(opts);
        logger.error("Incorrect command line arguments");
        e.printStackTrace();
    } catch (ManifestLoadException e) {
        logger.fatal("Could not load the module manager manifest");
        e.printStackTrace();
    } catch (ModuleLoadException e) {
        logger.fatal("Could not load the default module");
        e.printStackTrace();
    }

}

From source file:edu.msu.cme.rdp.readseq.writers.StkWriter.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("r", "removeref", false, "is set, do not write the GC reference sequences to output");
    options.addOption("h", "header", true,
            "the header of the output file in case a differenet stk version, default is " + STK_HEADER);
    String header = STK_HEADER;//  w ww.  j a  v a 2 s .  co  m
    boolean removeRef = false;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("removeref")) {
            removeRef = true;
        }
        if (line.hasOption("header")) {
            header = line.getOptionValue("header");
        }

        args = line.getArgs();
        if (args.length < 2) {
            throw new Exception("Need input and output files");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-stk <input-file> <out-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SequenceReader reader = new SequenceReader(new File(args[0]));
    PrintStream out = new PrintStream(new File(args[1]));
    StkWriter writer = new StkWriter(reader, out, header);
    reader = new SequenceReader(new File(args[0]));
    Sequence seq;
    while ((seq = reader.readNextSequence()) != null) {
        if (seq.getSeqName().startsWith("#") && removeRef) {
            continue;
        }
        writer.writeSeq(seq);
    }
    writer.writeEndOfBlock();
    writer.close();
    reader.close();

}

From source file:eu.itesla_project.commons.tools.Main.java

public static void main(String[] args) throws IOException {
    if (args.length < 1) {
        printUsage();/*w  w  w .j  a v a 2s. com*/
    }

    Tool tool = findTool(args[0]);
    if (tool == null) {
        printUsage();
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(getOptionsWithHelp(tool.getCommand().getOptions()),
                Arrays.copyOfRange(args, 1, args.length));
        if (line.hasOption("help")) {
            printCommandUsage(tool.getCommand());
        } else {
            tool.run(line);
        }
    } catch (ParseException e) {
        System.err.println("error: " + e.getMessage());
        printCommandUsage(tool.getCommand());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jlite.cli.ProxyInfo.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//from w  w  w. j  av  a 2  s . c o m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        }
        if (line.hasOption("xml")) {
            System.out.println("<output>");
        }
        run(line);
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);/*w  w  w .j  a v  a 2s .  c o  m*/

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:gobblin.aws.GobblinAWSTaskRunner.java

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

    try {/*ww  w. java  2s  .  c o m*/
        final CommandLine cmd = new DefaultParser().parse(options, args);
        if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME)
                || !cmd.hasOption(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME)
                || !cmd.hasOption(GobblinAWSConfigurationKeys.APP_WORK_DIR)) {
            printUsage(options);
            System.exit(1);
        }

        Log4jConfigHelper.updateLog4jConfiguration(GobblinTaskRunner.class,
                GobblinAWSConfigurationKeys.GOBBLIN_AWS_LOG4J_CONFIGURATION_FILE);

        LOGGER.info(JvmUtils.getJvmInputArguments());

        final String applicationName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME);
        final String helixInstanceName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME);
        final String appWorkDir = cmd.getOptionValue(GobblinAWSConfigurationKeys.APP_WORK_DIR);

        final GobblinTaskRunner gobblinTaskRunner = new GobblinAWSTaskRunner(applicationName, helixInstanceName,
                ConfigFactory.load(), Optional.of(new Path(appWorkDir)));
        gobblinTaskRunner.start();
    } catch (ParseException pe) {
        printUsage(options);
        System.exit(1);
    }
}

From source file:CircularGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption(OptionBuilder.withLongOpt("input").withArgName("INPUT")
            .withDescription("the input FastA File").isRequired().hasArg().create("i"));
    options.addOption(OptionBuilder.withLongOpt("elongation").withArgName("ELONGATION")
            .withDescription("the elongation factor [INT]").isRequired().hasArg().create("e"));
    options.addOption(OptionBuilder.withLongOpt("seq").withArgName("SEQ")
            .withDescription("the names of the sequences that should to be elongated").isRequired().hasArg()
            .hasOptionalArgs().hasArg().create("s"));
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {/* ww  w  . j  a v  a2  s  .  c o m*/
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME + "v" + VERSION, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }
    String input = "";
    String tmpElongation = "";
    Integer elongation = 0;
    String[] names = new String[0];
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
        }
        if (cmd.hasOption('e')) {
            tmpElongation = cmd.getOptionValue('e');
            try {
                elongation = Integer.parseInt(tmpElongation);
            } catch (Exception e) {
                System.err.println("elongation not an Integer: " + tmpElongation);
                System.exit(0);
            }
        }
        if (cmd.hasOption('s')) {
            names = cmd.getOptionValues('s');
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }

    CircularGenerator cg = new CircularGenerator(elongation);
    File f = new File(input);
    for (String s : names) {
        cg.keys_to_treat_circular.add(s);
    }
    cg.extendFastA(f);

}

From source file:SuperPeer.java

/**
 * The good stuff./*from w w w  .ja  va2  s  .  co m*/
 */
public static void main(String[] argv) {
    int mbits = 5;
    ArgumentHandler cli = new ArgumentHandler("SuperPeer [-h]",
            "Run a DHT SuperPeer and attached to the specified superpeer.",
            "Bala Subrahmanyam Kambala, Daniel William DaCosta - GPLv3 (http://www.gnu.org/copyleft/gpl.html)");
    cli.addOption("h", "help", false, "Print this usage information.");
    cli.addOption("m", "mbits", true,
            "The maximum number of unique keys in terms of 2^m (Default is " + Integer.toString(mbits) + ").");

    CommandLine commandLine = cli.parse(argv);
    if (commandLine.hasOption('h')) {
        cli.usage("");
        System.exit(0);
    }
    if (commandLine.hasOption('m')) {
        //XXX:uncaught exception!
        mbits = Integer.parseInt((commandLine.getOptionValue('m')));
    }
    try {
        Naming.rebind("SuperPeer", new SuperPeer(mbits));
    } catch (Exception e) {
        System.out.println("SuperPeer failed: " + e);
    }
}