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.linkedin.pinot.transport.perf.ScatterGatherPerfServer.java

/**
 * @param args//from  w w  w .  j  av a2  s  .  co m
 */
public static void main(String[] args) throws Exception {

    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = buildCommandLineOptions();

    CommandLine cmd = cliParser.parse(cliOptions, args, true);

    if (!cmd.hasOption(RESPONSE_SIZE_OPT_NAME) || !cmd.hasOption(SERVER_PORT_OPT_NAME)) {
        System.err.println("Missing required arguments !!");
        System.err.println(cliOptions);
        throw new RuntimeException("Missing required arguments !!");
    }

    int responseSize = Integer.parseInt(cmd.getOptionValue(RESPONSE_SIZE_OPT_NAME));
    int serverPort = Integer.parseInt(cmd.getOptionValue(SERVER_PORT_OPT_NAME));

    ScatterGatherPerfServer server = new ScatterGatherPerfServer(serverPort, responseSize, 2); // 2ms latency
    server.run();
}

From source file:com.k42b3.quantum.Entry.java

public static void main(String[] args) throws Exception {
    // logging/*from  w  ww. j a  v  a 2 s .  c  o m*/
    Layout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);

    Logger.getLogger("com.k42b3.quantum").addAppender(new WriterAppender(layout, System.out));

    // options
    Options options = new Options();
    options.addOption("p", "port", false, "Port for the web server default is 8080");
    options.addOption("i", "interval", false,
            "The interval how often each worker gets triggered in minutes default is 2");
    options.addOption("d", "database", false, "Path to the sqlite database default is \"quantum.db\"");
    options.addOption("l", "log", false,
            "Defines the log level default is ERROR possible is (ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)");
    options.addOption("v", "version", false, "Shows the current version");
    options.addOption("h", "help", false, "Shows the help");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    // start app
    Quantum app = new Quantum();

    if (cmd.hasOption("p")) {
        try {
            int port = Integer.parseInt(cmd.getOptionValue("p"));

            app.setPort(port);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Port must be an integer");
        }
    }

    if (cmd.hasOption("i")) {
        try {
            int pollInterval = Integer.parseInt(cmd.getOptionValue("i"));

            app.setPollInterval(pollInterval);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Interval must be an integer");
        }
    }

    if (cmd.hasOption("d")) {
        String dbPath = cmd.getOptionValue("d");

        if (!dbPath.isEmpty()) {
            app.setDbPath(dbPath);
        }
    }

    if (cmd.hasOption("l")) {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.toLevel(cmd.getOptionValue("l")));
    } else {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.ERROR);
    }

    if (cmd.hasOption("v")) {
        System.out.println("Version: " + Quantum.VERSION);
        System.exit(0);
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("quantum.jar", options);
        System.exit(0);
    }

    app.run();
}

From source file:ee.ria.xroad.proxy.opmonitoring.OpMonitoringBufferMemoryUsage.java

/**
 * Main function./*  w w w  .  ja va2 s . co m*/
 * @param args args
 * @throws Exception if something goes wrong.
 */
public static void main(String args[]) throws Exception {

    CommandLine cmd = parseCommandLine(args);

    if (cmd.hasOption("help")) {
        usage();

        System.exit(0);
    }

    int count = cmd.getOptionValue("count") != null ? Integer.parseInt(cmd.getOptionValue("count"))
            : DEFAULT_COUNT;

    int shortStrLen = cmd.getOptionValue("short-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("short-string-length"))
            : DEFAULT_SHORT_LONG_STRING_LENGTH;

    int longStrLen = cmd.getOptionValue("long-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("long-string-length"))
            : DEFAULT_LONG_STRING_LENGTH;

    Runtime runtime = Runtime.getRuntime();

    long before = getUsedBytes(runtime);

    createBuffer(count, shortStrLen, longStrLen);

    long after = getUsedBytes(runtime);

    log.info("Records count {}, used heap {}MB", count, (after - before) / MB);
}

From source file:io.github.gsteckman.doorcontroller.INA219Util.java

/**
 * Reads the Current from the INA219 with an I2C address and for a duration specified on the command line.
 * //from   w  w  w .  ja  v a  2 s  . c om
 * @param args
 *            Command line arguments.
 * @throws IOException
 *             If an error occurs reading/writing to the INA219
 * @throws ParseException
 *             If the command line arguments could not be parsed.
 */
public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("addr", true, "I2C Address");
    options.addOption("d", true, "Acquisition duration, in seconds");
    options.addOption("bv", false, "Also read bus voltage");
    options.addOption("sv", false, "Also read shunt voltage");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    Address addr = Address.ADDR_40;
    if (cmd.hasOption("addr")) {
        int opt = Integer.parseInt(cmd.getOptionValue("addr"), 16);
        Address a = Address.getAddress(opt);
        if (a != null) {
            addr = a;
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("INA219Util", options);
            return;
        }
    }

    int duration = 0;
    if (cmd.hasOption("d")) {
        String opt = cmd.getOptionValue("d");
        duration = Integer.parseInt(opt);
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("INA219Util", options);
        return;

    }

    boolean readBusVoltage = false;
    if (cmd.hasOption("bv")) {
        readBusVoltage = true;
    }

    boolean readShuntVoltage = false;
    if (cmd.hasOption("sv")) {
        readShuntVoltage = true;
    }

    INA219 i219 = new INA219(addr, 0.1, 3.2, INA219.Brng.V16, INA219.Pga.GAIN_8, INA219.Adc.BITS_12,
            INA219.Adc.SAMPLES_128);

    System.out.printf("Time\tCurrent");
    if (readBusVoltage) {
        System.out.printf("\tBus");
    }
    if (readShuntVoltage) {
        System.out.printf("\tShunt");
    }
    System.out.printf("\n");
    long start = System.currentTimeMillis();
    do {
        try {
            System.out.printf("%d\t%f", System.currentTimeMillis() - start, i219.getCurrent());
            if (readBusVoltage) {
                System.out.printf("\t%f", i219.getBusVoltage());
            }
            if (readShuntVoltage) {
                System.out.printf("\t%f", i219.getShuntVoltage());
            }
            System.out.printf("\n");
            Thread.sleep(100);
        } catch (IOException e) {
            LOG.error("Exception while reading I2C bus", e);
        } catch (InterruptedException e) {
            break;
        }
    } while (System.currentTimeMillis() - start < duration * 1000);
}

From source file:net.kahowell.xsd.fuzzer.XmlGenerator.java

/**
 * Drives the application, parsing command-line arguments to determine
 * options./*w w  w  .  j  av  a  2s .  c o  m*/
 * 
 * @param args command line args
 */
public static void main(String[] args) {
    try {
        setupLog4j();
        CommandLine commandLine = parser.parse(ConsoleOptions.OPTIONS, args);
        if (commandLine.hasOption("d")) {
            Logger.getLogger("net.kahowell.xsd.fuzzer").setLevel(Level.DEBUG);
        }
        for (Option option : commandLine.getOptions()) {
            if (option.getValue() != null) {
                log.debug("Using " + option.getDescription() + ": " + option.getValue());
            } else {
                log.debug("Using " + option.getDescription());
            }
        }

        Injector injector = Guice.createInjector(
                Modules.override(Modules.combine(new DefaultGeneratorsModule(), new DefaultOptionsModule()))
                        .with(new CommandLineArgumentsModule(commandLine)));

        log.debug(injector.getBindings());

        XsdParser xsdParser = injector.getInstance(XsdParser.class);
        XmlOptions xmlOptions = injector
                .getInstance(Key.get(XmlOptions.class, Names.named("xml save options")));
        XmlGenerator xmlGenerator = injector.getInstance(XmlGenerator.class);
        XmlGenerationOptions xmlGenerationOptions = injector.getInstance(XmlGenerationOptions.class);

        doPostModuleConfig(commandLine, xmlGenerationOptions, injector);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        XmlObject generatedXml = xsdParser.generateXml(commandLine.getOptionValue("root"));
        generatedXml.save(stream, xmlOptions);
        if (commandLine.hasOption("v")) {
            if (xsdParser.validate(stream)) {
                log.info("Valid XML file produced.");
            } else {
                log.info("Invalid XML file produced.");
                System.exit(4);
            }
        }
        xmlGenerator.showOrSave(stream);
    } catch (MissingOptionException e) {
        if (e.getMissingOptions().size() != 0) {
            System.err.println("Missing argument(s): " + Arrays.toString(e.getMissingOptions().toArray()));
        }
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(1);
    } catch (ParseException e) {
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(2);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:edu.msu.cme.rdp.classifier.train.ClassifierTraineeMaker.java

/** This is the main method to create training files from raw taxonomic information.
 * <p>/*ww  w. ja  va  2  s  .co  m*/
 * Usage: java ClassifierTraineeMaker tax_file rawseq.fa trainsetNo version version_modification output_directory.
 * See the ClassifierTraineeMaker constructor for more detail.
 * @param args
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void main(String[] args) throws FileNotFoundException, IOException {
    String taxFile;
    String cnFile = null;
    String seqFile;
    int trainset_no = 1;
    String version = null;
    String modification = null;
    String outdir = null;

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

        if (line.hasOption("t")) {
            taxFile = line.getOptionValue("t");
        } else {
            throw new Exception("taxon file must be specified");
        }
        if (line.hasOption("c")) {
            cnFile = line.getOptionValue("c");
        }
        if (line.hasOption("s")) {
            seqFile = line.getOptionValue("s");
        } else {
            throw new Exception("seq file must be specified");
        }

        if (line.hasOption("n")) {
            try {
                trainset_no = Integer.parseInt(line.getOptionValue("n"));
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("trainset_no needs to be an integer.");
            }
        }
        if (line.hasOption("o")) {
            outdir = line.getOptionValue("o");
        } else {
            throw new Exception("output directory must be specified");
        }
        if (line.hasOption("v")) {
            version = line.getOptionValue("v");
        }
        if (line.hasOption("m")) {
            modification = line.getOptionValue("m");
        }

    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120, "train", "", options, "", true);
        return;
    }

    ClassifierTraineeMaker maker = new ClassifierTraineeMaker(taxFile, seqFile, cnFile, trainset_no, version,
            modification, outdir);
}

From source file:com.flaptor.indextank.storage.LogWriterServer.java

public static void main(String[] args) throws IOException, InterruptedException {
    // create the parser
    CommandLineParser parser = new PosixParser();

    int port;/*from  ww w  . j ava  2  s  . c  o  m*/

    LogWriterServer server;
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
            return;
        }

        String val = null;
        val = line.getOptionValue("port", null);
        if (null != val) {
            port = Integer.valueOf(val);
        } else {
            printHelp(getOptions(), "Must specify a server port");
            System.exit(1);
            return;
        }

        String path = null;
        path = line.getOptionValue("path", null);
        if (null != path) {
            server = new LogWriterServer(new File(path), port);
        } else {
            server = new LogWriterServer(port);
        }
    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
        System.exit(1);
        return;
    }

    server.start();
}

From source file:com.gordcorp.jira2db.App.java

public static void main(String[] args) throws Exception {
    File log4jFile = new File("log4j.xml");
    if (log4jFile.exists()) {
        DOMConfigurator.configure("log4j.xml");
    }//w  w w .  j a  v  a2 s .c  o m

    Option help = new Option("h", "help", false, "print this message");

    @SuppressWarnings("static-access")
    Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT")
            .hasArg().withArgName("PROJECT").create();

    @SuppressWarnings("static-access")
    Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D");

    @SuppressWarnings("static-access")
    Option testJira = OptionBuilder.withLongOpt("test-jira")
            .withDescription("Test the connection to Jira and print the results").create();

    @SuppressWarnings("static-access")
    Option forever = OptionBuilder.withLongOpt("forever")
            .withDescription("Will continue polling Jira and syncing forever").create();

    Options options = new Options();
    options.addOption(help);
    options.addOption(project);
    options.addOption(property);
    options.addOption(testJira);
    options.addOption(forever);

    CommandLineParser parser = new GnuParser();
    try {

        CommandLine line = parser.parse(options, args);

        if (line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        // Overwrite the properties file with command line arguments
        if (line.hasOption("D")) {
            String[] values = line.getOptionValues("D");
            for (int i = 0; i < values.length; i = i + 2) {
                String key = values[i];
                // If user does not provide a value for this property, use
                // an empty string
                String value = "";
                if (i + 1 < values.length) {
                    value = values[i + 1];
                }

                log.info("Setting key=" + key + " value=" + value);
                PropertiesWrapper.set(key, value);
            }

        }

        if (line.hasOption("test-jira")) {
            testJira();
        } else {
            JiraSynchroniser jira = new JiraSynchroniser();

            if (line.hasOption("project")) {

                jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") }));
            }

            if (line.hasOption("forever")) {
                jira.syncForever();
            } else {
                jira.syncAll();
            }
        }
    } catch (ParseException exp) {

        log.error("Parsing failed: " + exp.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:edu.msu.cme.rdp.readseq.utils.ResampleSeqFile.java

public static void main(String[] args) throws IOException {
    int numOfSelection = 0;
    int subregion_length = 0;

    try {/*from www  .  ja  v a  2  s .  co  m*/
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("num-selection")) {
            numOfSelection = Integer.parseInt(line.getOptionValue("num-selection"));
            if (numOfSelection < 1) {
                throw new Exception("num-selection should be at least 1");
            }
        }
        if (line.hasOption("subregion_length")) {
            subregion_length = Integer.parseInt(line.getOptionValue("subregion_length"));
            if (subregion_length < 1) {
                throw new Exception("subregion_length should be at least 1");
            }
        }

        args = line.getArgs();
        if (args.length != 2) {
            throw new Exception("Incorrect number of command line arguments");
        }
        ResampleSeqFile.select(args[0], args[1], numOfSelection, subregion_length);
    } catch (Exception e) {
        new HelpFormatter().printHelp(120, "ResampleSeqFile [options] <infile(dir)> <outdir>", "", options, "");
        System.out.println("ERROR: " + e.getMessage());
        return;
    }
}

From source file:net.skyebook.zerocollada.ZeroCollada.java

/**
 * @param args//from ww w . ja  va  2 s  . c o  m
 * @throws ParseException 
 * @throws IOException 
 * @throws JDOMException 
 */
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // Setup Apache Commons CLI
    optionsSetup();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption(ZCOpts.help)) {
        showHelp();
    }

    // was there a valid operation specified?
    if (hasValidOption(cmd)) {
        File fileFromCommandLine = new File(args[args.length - 1]);
        if (!fileFromCommandLine.exists()) {
            System.err.println(
                    "The file located at " + fileFromCommandLine.toString() + " does not exist!  Qutting.");
            return;
        } else if (fileFromCommandLine.isFile() && fileFromCommandLine.toString().endsWith(".dae")) {
            // we've been given a single file.  Act on this single file
            doRequestedAction(fileFromCommandLine, cmd);
        } else if (fileFromCommandLine.isDirectory()) {
            // We've been given a directory of files process the ones that are .dae
            for (File file : fileFromCommandLine.listFiles()) {
                if (file.isFile() && file.toString().endsWith(".dae")) {
                    doRequestedAction(file, cmd);
                } else {
                    System.err.println(file.toString() + " does not seem to be a COLLADA file");
                }
            }
        }
    } else {
        // Then why are we here?
        if (cmd.hasOption(ZCOpts.includeY)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        } else if (cmd.hasOption(ZCOpts.anchorCenter)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        }
    }

}