Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*  www  .  ja  v  a  2s .  c  o  m*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoMqttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration();
    config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password"));
    config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection"));
    config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id"));
    config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username"));
    config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password"));
    config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms")));

    MqttIndegoAdapter adapter = new MqttIndegoAdapter(config);
    adapter.startup();
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoIftttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*from www .ja  v  a 2s  . c  om*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoIftttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    IftttIndegoAdapterConfiguration config = new IftttIndegoAdapterConfiguration();
    config.setIftttMakerKey(properties.getProperty("indego.ifttt.maker.key"));
    config.setIftttIgnoreServerCertificate(
            Integer.parseInt(properties.getProperty("indego.ifttt.maker.ignore-server-certificate")) != 0);
    config.setIftttReceiverPort(Integer.parseInt(properties.getProperty("indego.ifttt.maker.receiver-port")));
    config.setIftttReceiverSecret(properties.getProperty("indego.ifttt.maker.receiver-secret"));
    config.setIftttOfflineEventName(properties.getProperty("indego.ifttt.maker.eventname-offline"));
    config.setIftttOnlineEventName(properties.getProperty("indego.ifttt.maker.eventname-online"));
    config.setIftttErrorEventName(properties.getProperty("indego.ifttt.maker.eventname-error"));
    config.setIftttErrorClearedEventName(properties.getProperty("indego.ifttt.maker.eventname-error-cleared"));
    config.setIftttStateChangeEventName(properties.getProperty("indego.ifttt.maker.eventname-state-change"));
    config.setIndegoBaseUrl(properties.getProperty("indego.ifttt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.ifttt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.ifttt.device.password"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.ifttt.polling-interval-ms")));

    IftttIndegoAdapter adapter = new IftttIndegoAdapter(config);
    adapter.startup();
}

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;/*from  w w w . ja v a  2 s. co m*/
    try {
        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.dattack.dbping.cli.PingAnalyzerCli.java

/**
 * The <code>main</code> method.
 *
 * @param args/*from  w  w  w  .j  a va 2  s.co  m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    try {

        // create Options object
        final Options options = new Options();

        // add t option
        options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin");
        options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish");
        options.addOption(SPAN_OPTION, true, "the period of time between points");
        options.addOption(DATA_FILE_OPTION, true, "the data file to analyze");
        options.addOption(METRIC_OPTION, true, "the metric to analyze");
        options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use");
        options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use");

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

        final ReportContext context = new ReportContext();
        context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION)));
        context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION)));
        context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION)));
        context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION)));
        context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION)));
        if (cmd.hasOption(METRIC_OPTION)) {
            for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) {
                context.addMetricNameFilter(MetricName.parse(metricName));
            }
        }

        final PingAnalyzerCli ping = new PingAnalyzerCli();
        for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) {
            ping.execute(new File(file), context);
        }

    } catch (final ParseException | ConfigurationException e) {
        System.err.println(e.getMessage());
    }
}

From source file:gov.nasa.jpl.mudrod.xsd2owl.Mapper.java

/**
 * @param args//from   w  ww.j a  v a2 s. c  om
 */
public static void main(String[] args) {
    Option sOpt = Option.builder().hasArg(true).numberOfArgs(1).argName("file").required(false)
            .longOpt(INPUTFILE).desc("A path to a local XSD file.").build();

    Options opts = new Options();
    opts.addOption(sOpt);

    DefaultParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Mapper.class.getSimpleName(), opts);
        System.exit(-1);
    }
    File file = null;
    if (cmd.hasOption(INPUTFILE)) {
        try {
            is = new FileInputStream(cmd.getOptionValue(INPUTFILE));
            //file = new File(cmd.getOptionValue(INPUTFILE));
        } catch (FileNotFoundException e) {
            LOG.error("Error processing input XSD from path: {}", e);
        }
    }
    Mapper mapper = new Mapper();
    mapper.executeMapping(is);
}

From source file:com.dattack.dbtools.ping.PingAnalyzer.java

/**
 * The <code>main</code> method.
 *
 * @param args//w ww.j a  va 2  s  .  c o  m
 *            the program arguments
 */
public static void main(final String[] args) {

    try {

        // create Options object
        final Options options = new Options();

        // add t option
        options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin");
        options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish");
        options.addOption(SPAN_OPTION, true, "the period of time between points");
        options.addOption(DATA_FILE_OPTION, true, "the data file to analyze");
        options.addOption(METRIC_OPTION, true, "the metric to analyze");
        options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use");
        options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use");

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

        final ReportContext context = new ReportContext();
        context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION)));
        context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION)));
        context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION)));
        context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION)));
        context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION)));
        if (cmd.hasOption(METRIC_OPTION)) {
            for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) {
                context.addMetricNameFilter(MetricName.parse(metricName));
            }
        }

        final PingAnalyzer ping = new PingAnalyzer();
        for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) {
            ping.execute(new File(file), context);
        }

    } catch (final ParseException | ConfigurationException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.microsoft.kafkaavailability.App.java

public static void main(String[] args) throws IOException, MetaDataManagerException, InterruptedException {
    System.out.println("Starting KafkaAvailability Tool");
    IPropertiesManager appPropertiesManager = new PropertiesManager<AppProperties>("appProperties.json",
            AppProperties.class);
    appProperties = (AppProperties) appPropertiesManager.getProperties();
    Options options = new Options();
    options.addOption("r", "run", true,
            "Number of runs. Don't use this argument if you want to run infintely.");
    options.addOption("s", "sleep", true,
            "Time (in milliseconds) to sleep between each run. Default is 300000");
    Option clusterOption = Option.builder("c").hasArg().required(true).longOpt("cluster")
            .desc("(REQUIRED) Cluster name").build();
    options.addOption(clusterOption);//from   ww w  .jav a  2s  .  c o m
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        int howManyRuns;

        m_cluster = line.getOptionValue("cluster");
        MDC.put("cluster", m_cluster);

        if (line.hasOption("sleep")) {
            m_sleepTime = Integer.parseInt(line.getOptionValue("sleep"));
        }
        if (line.hasOption("run")) {
            howManyRuns = Integer.parseInt(line.getOptionValue("run"));
            for (int i = 0; i < howManyRuns; i++) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        } else {
            while (true) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("KafkaAvailability", options);
    }

}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();/*w  w  w .ja v a  2  s. com*/
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);/*from ww w . j  a  va2  s .co m*/
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:com.boozallen.cognition.kom.KafakOffsetMonitor.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;//w ww  .j  av  a  2 s .c  o  m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("KafakOffsetMonitor", options);
        System.exit(1);
    }

    KafakOffsetMonitor monitor = new KafakOffsetMonitor();
    monitor.zkHosts = cmd.getOptionValue("zkHosts");
    monitor.zkRoot = cmd.getOptionValue("zkRoot", "/storm-kafka");
    monitor.spoutId = cmd.getOptionValue("spoutId");
    monitor.logstashHost = cmd.getOptionValue("logstashHost");
    monitor.logstashPort = Integer.parseInt(cmd.getOptionValue("logstashPort"));

    int refresh = Integer.parseInt(cmd.getOptionValue("refresh", "15"));

    Timer timer = new Timer();
    int period = refresh * 1000;
    int delay = 0;
    timer.schedule(monitor, delay, period);
}