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:com.linkedin.restli.datagenerator.csharp.CSharpRythmGenerator.java

public static void main(String[] args) throws IOException {
    CommandLine cl = null;//  w  w  w.  j a va  2 s  .c  o  m
    try {
        final CommandLineParser parser = new DefaultParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        LOG.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final CSharpRythmGenerator generator = new CSharpRythmGenerator(cl);
    generator.setupRythmEngine();
    generator.generate();

    Rythm.shutdown();
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *///from w ww.ja  v  a  2 s .c om
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}

From source file:com.google.api.codegen.CodeGeneratorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "show usage");
    options.addOption(Option.builder().longOpt("descriptor_set")
            .desc("The descriptor set representing the compiled input protos.").hasArg()
            .argName("DESCRIPTOR-SET").required(true).build());
    options.addOption(//ww  w  .  j a  v a  2  s . c  o  m
            Option.builder().longOpt("service_yaml").desc("The service YAML configuration file or files.")
                    .hasArg().argName("SERVICE-YAML").required(true).build());
    options.addOption(Option.builder().longOpt("gapic_yaml").desc("The GAPIC YAML configuration file or files.")
            .hasArg().argName("GAPIC-YAML").required(true).build());
    options.addOption(Option.builder().longOpt("package_yaml")
            .desc("The package metadata YAML configuration file.").hasArg().argName("PACKAGE-YAML").build());
    options.addOption(Option.builder("o").longOpt("output")
            .desc("The directory in which to output the generated client library.").hasArg()
            .argName("OUTPUT-DIRECTORY").build());
    options.addOption(Option.builder().longOpt("enabled_artifacts")
            .desc("Optional. Artifacts enabled for the generator. "
                    + "Currently supports 'surface' and 'test'.")
            .hasArg().argName("ENABLED_ARTIFACTS").required(false).build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    if (cl.hasOption("help")) {
        HelpFormatter formater = new HelpFormatter();
        formater.printHelp("CodeGeneratorTool", options);
    }

    int exitCode = generate(cl.getOptionValue("descriptor_set"), cl.getOptionValues("service_yaml"),
            cl.getOptionValues("gapic_yaml"), cl.getOptionValue("package_yaml"),
            cl.getOptionValue("output", ""), cl.getOptionValues("enabled_artifacts"));
    System.exit(exitCode);
}

From source file:com.chezzverse.timelogger.server.TimeLoggerServerMain.java

public static void main(String[] args) {

    // Initialize the default configuration file to the hard coded default path value.
    String configFileName = _DEFAULT_CONFIG_FILE;

    // Create all the available options
    Option portOpt = new Option("p", "port", true, "Set the listen port for the http server " + "instance.");
    portOpt.setArgName("number");

    Option htmlOpt = new Option("h", "html-root", true,
            "Set the root directory that " + "contains the required html files.");
    htmlOpt.setArgName("directory");

    Option configOpt = new Option("c", "config", true,
            "Get configuration options from the " + "specified file");
    Option backlogOpt = new Option("b", "backlog", true,
            "Set the number of connections to " + "queue for the server.");

    Options opts = new Options();
    opts.addOption(portOpt);/*from  ww w. ja v a 2s .co m*/
    opts.addOption(htmlOpt);
    opts.addOption(configOpt);
    opts.addOption(backlogOpt);

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

    try {
        // Parse the command line arguments.
        cmd = parser.parse(opts, args);

        // Fist check to see if there is a custom defined config file, and load the config file.
        if (cmd.hasOption("c")) {
            configFileName = cmd.getOptionValue("c");
        }

        TimeLoggerConfig.getInstance().LoadConfigFile(configFileName);

        // Process the rest of the args and override any settings in the config file.
        if (cmd.hasOption("h")) {
            TimeLoggerConfig.getInstance().htmlRoot = cmd.getOptionValue("h");
        }

        if (cmd.hasOption("p")) {
            TimeLoggerConfig.getInstance().port = Integer.parseInt(cmd.getOptionValue("p"));
        }

        if (cmd.hasOption("b")) {
            TimeLoggerConfig.getInstance().maxBackLog = Integer.parseInt(cmd.getOptionValue("b"));
        }

    } catch (ParseException e) {
        System.out.println("Invalid argument.");
        formatter.printHelp("TimeLoggerServer", opts);
        System.exit(1);
    } catch (NumberFormatException e) {
        System.out.println("Invalid argument.");
        formatter.printHelp("TimeLoggerServer", opts);
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }

    TimeLoggerApp app = new TimeLoggerApp();

    if (app != null) {
        app.run();
    } else {
        System.exit(3); // Strange termination
    }
}

From source file:edu.cmu.tetrad.cli.data.sim.DiscreteTabularData.java

/**
 * @param args the command line arguments
 *//*from www . ja v a  2  s . c  o  m*/
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        return;
    }

    try {
        CommandLineParser cmdParser = new DefaultParser();
        CommandLine cmd = cmdParser.parse(MAIN_OPTIONS, args);

        numOfVars = Args.getIntegerMin(cmd.getOptionValue("variable"), 0);
        numOfCases = Args.getIntegerMin(cmd.getOptionValue("case"), 0);
        edgeFactor = Args.getDoubleMin(cmd.getOptionValue("edge"), 1.0);
    } catch (ParseException exception) {
        System.err.println(exception.getLocalizedMessage());
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        System.exit(-127);
    }

    List<Node> vars = new ArrayList<>();
    for (int i = 0; i < numOfVars; i++) {
        vars.add(new ContinuousVariable("X" + i));
    }
    Graph graph = GraphUtils.randomGraphRandomForwardEdges(vars, 0, (int) (numOfVars * edgeFactor), 30, 12, 15,
            false, true);
    BayesPm pm = new BayesPm(graph, 3, 3);
    BayesIm im = new MlBayesIm(pm, MlBayesIm.RANDOM);
    DataSet data = im.simulateData(numOfCases, false);

    String[] variables = data.getVariableNames().toArray(new String[0]);
    int lastIndex = variables.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        System.out.printf("%s,", variables[i]);
    }
    System.out.printf("%s%n", variables[lastIndex]);

    DataBox dataBox = ((BoxDataSet) data).getDataBox();
    VerticalIntDataBox box = (VerticalIntDataBox) dataBox;
    //        int[][] matrix = box.getVariableVectors();
    //        int numOfColumns = matrix.length;
    //        int numOfRows = matrix[0].length;
    //        int[][] dataset = new int[numOfRows][numOfColumns];
    //        for (int i = 0; i < matrix.length; i++) {
    //            for (int j = 0; j < matrix[i].length; j++) {
    //                dataset[j][i] = matrix[i][j];
    //            }
    //        }
    //        for (int[] rowData : dataset) {
    //            lastIndex = rowData.length - 1;
    //            for (int i = 0; i < lastIndex; i++) {
    //                System.out.printf("%d,", rowData[i]);
    //            }
    //            System.out.printf("%s%n", rowData[lastIndex]);
    //        }
}

From source file:Jimbo.Cheerlights.TweetListener.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException//from   w ww .jav  a 2  s .c o  m
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException In case of command line error
 */
public static void main(String[] args) throws TwitterException, IOException, ParseException {
    // Set up simpler logging to stdout
    Jimbo.Logging.Logging.useStdout();

    LOG.log(Level.INFO, "Starting twitter listener");

    Options options = new Options();

    options.addOption("b", Listener.MQTT_BROKER_KEY, true, "URL of the broker")
            .addOption("c", Listener.MQTT_CLIENT_KEY, true, "The MQTT client name to use")
            .addOption("t", Listener.MQTT_TOPIC_KEY, true, "The MQTT topic to use");

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

    MQTTClient mqtt = null;
    String mqtt_topic = Listener.DEFAULT_MQTT_TOPIC;

    if (command.hasOption(Listener.MQTT_BROKER_KEY)) {
        if (!command.hasOption(Listener.MQTT_CLIENT_KEY))
            throw new ParseException("MQTT without client name");

        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            mqtt_topic = command.getOptionValue(Listener.MQTT_TOPIC_KEY);

        try {
            mqtt = new MQTTClient(command.getOptionValue(Listener.MQTT_BROKER_KEY),
                    command.getOptionValue(Listener.MQTT_CLIENT_KEY));
            mqtt.run();
        }

        catch (MqttException e) {
            LOG.log(Level.WARNING, "Failed to create MQTT client: {0}", e.toString());
        }
    } else {
        if (command.hasOption(Listener.MQTT_TOPIC_KEY))
            LOG.warning("MQTT topic supplied but no broker");

        if (command.hasOption(Listener.MQTT_CLIENT_KEY))
            LOG.warning("MQTT client name but no broker");
    }

    Twitter twitter = new TwitterFactory().getInstance();
    StatusListener listener = new listener("224.1.1.1", (short) 5123, mqtt, mqtt_topic);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "#cheerlights" };

    fq.track(keywords);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.filter(fq);

    LOG.log(Level.INFO, "Up and running....");
}

From source file:com.dattack.dbcopy.cli.DbCopyCli.java

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

    final Options options = createOptions();

    try {
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmd = parser.parse(options, args);
        final String[] filenames = cmd.getOptionValues(FILE_OPTION);
        final String[] jobNames = cmd.getOptionValues(JOB_NAME_OPTION);
        final String[] propertiesFiles = cmd.getOptionValues(PROPERTIES_OPTION);

        HashSet<String> jobNameSet = null;
        if (jobNames != null) {
            jobNameSet = new HashSet<>(Arrays.asList(jobNames));
        }

        CompositeConfiguration configuration = new CompositeConfiguration();
        if (propertiesFiles != null) {
            for (final String fileName : propertiesFiles) {
                configuration.addConfiguration(new PropertiesConfiguration(fileName));
            }
        }

        final DbCopyEngine ping = new DbCopyEngine();
        ping.execute(filenames, jobNameSet, configuration);

    } catch (@SuppressWarnings("unused") final ParseException e) {
        showUsage(options);
    } catch (final ConfigurationException | DattackParserException e) {
        System.err.println(e.getMessage());
    }
}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main./*from ww  w  .j a va2s .  com*/
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

From source file:de.onyxbits.raccoon.cli.Router.java

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

    Option property = Option.builder("D").argName("property=value").numberOfArgs(2).valueSeparator()
            .desc(Messages.getString(DESC + "D")).build();
    options.addOption(property);/*from w ww .j av  a  2s . co m*/

    Option help = new Option("h", "help", false, Messages.getString(DESC + "h"));
    options.addOption(help);

    Option version = new Option("v", "version", false, Messages.getString(DESC + "v"));
    options.addOption(version);

    // GPA: Google Play Apps (we might add different markets later)
    Option playAppDetails = new Option(null, "gpa-details", true, Messages.getString(DESC + "gpa-details"));
    playAppDetails.setArgName("package");
    options.addOption(playAppDetails);

    Option playAppBulkDetails = new Option(null, "gpa-bulkdetails", true,
            Messages.getString(DESC + "gpa-bulkdetails"));
    playAppBulkDetails.setArgName("file");
    options.addOption(playAppBulkDetails);

    Option playAppBatchDetails = new Option(null, "gpa-batchdetails", true,
            Messages.getString(DESC + "gpa-batchdetails"));
    playAppBatchDetails.setArgName("file");
    options.addOption(playAppBatchDetails);

    Option playAppSearch = new Option(null, "gpa-search", true, Messages.getString(DESC + "gpa-search"));
    playAppSearch.setArgName("query");
    options.addOption(playAppSearch);

    CommandLine commandLine = null;
    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    if (commandLine.hasOption(property.getOpt())) {
        System.getProperties().putAll(commandLine.getOptionProperties(property.getOpt()));
    }

    if (commandLine.hasOption(help.getOpt())) {
        new HelpFormatter().printHelp("raccoon", Messages.getString("header"), options,
                Messages.getString("footer"), true);
        System.exit(0);
    }

    if (commandLine.hasOption(version.getOpt())) {
        System.out.println(GlobalsProvider.getGlobals().get(Version.class));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppDetails.getLongOpt())) {
        Play.details(commandLine.getOptionValue(playAppDetails.getLongOpt()));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppBulkDetails.getLongOpt())) {
        Play.bulkDetails(new File(commandLine.getOptionValue(playAppBulkDetails.getLongOpt())));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppBatchDetails.getLongOpt())) {
        Play.details(new File(commandLine.getOptionValue(playAppBatchDetails.getLongOpt())));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppSearch.getLongOpt())) {
        Play.search(commandLine.getOptionValue(playAppSearch.getLongOpt()));
        System.exit(0);
    }
}

From source file:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;//from w  w w. j a v  a  2s  .c  o  m
    String sqlpath = "", host = "", port = "3306", username = "", password = "", database = "";
    Boolean query = false;
    Option option_sql = Option.builder("s").argName("sql").hasArg()
            .desc("Path to a file containing a valid MySQL sql statement").build();
    Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname")
            .build();
    Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build();
    Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username")
            .build();
    Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password")
            .build();
    Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name")
            .build();
    Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build();
    Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_sql);
    options.addOption(option_hostname);
    options.addOption(option_port);
    options.addOption(option_username);
    options.addOption(option_password);
    options.addOption(option_dbname);
    options.addOption(option_query);
    options.addOption(option_help);

    try {
        commandLine = parser.parse(options, params);
    } catch (MissingOptionException e) {
        help(options);
    } catch (MissingArgumentException e) {
        help(options);
    } catch (ParseException e) {
        System.out.println(e);
    }

    if (commandLine.hasOption("w") || params.length == 0) {
        help(options);
    }

    if (commandLine.hasOption("s")) {
        sqlpath = commandLine.getOptionValue("s");
    } else {
        System.out.println("Missing path to a SQL statement file");
        help(options);
    }
    if (commandLine.hasOption("h")) {
        host = commandLine.getOptionValue("h");
    } else {
        System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)");
        help(options);
    }
    if (commandLine.hasOption("n")) {
        port = commandLine.getOptionValue("n");
    } else {
        System.out.println("Missing ClearDB Port Value.  Defaulting to 3306");
    }
    if (commandLine.hasOption("u")) {
        username = commandLine.getOptionValue("u");
    } else {
        System.out.println("Missing ClearDB Username");
        help(options);
    }
    if (commandLine.hasOption("p")) {
        password = commandLine.getOptionValue("p");
    } else {
        System.out.println("Missing ClearDB Password");
        help(options);
    }
    if (commandLine.hasOption("d")) {
        database = commandLine.getOptionValue("d");
    } else {
        System.out.println("Missing ClearDB Database Name");
        help(options);
    }

    if (commandLine.hasOption("query")) {
        query = true;
    }

    String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port)
            .append("/").append(database).append("?reconnect=true").toString();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }

    try {
        Connection con = DriverManager.getConnection(connectionURL, username, password);
        Statement stmt = con.createStatement();
        if (query) {
            System.out.println("Querying target MySQL DB ...");
            ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset()));
            while (rs.next())
                System.out.println(rs.getInt("emp_no") + "  " + rs.getDate("birth_date") + "  "
                        + rs.getString("first_name") + "  " + rs.getString("last_name") + "  "
                        + rs.getString("gender") + "  " + rs.getDate("hire_date"));
        } else {
            System.out.println("Updating target MySQL DB ...");
            int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset()));
            System.out.println(result);
        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}