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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.twitter.distributedlog.service.DistributedLogServerApp.java

private void run() {
    try {//w w w  .j a  v a 2s.c  o  m
        logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        logger.error("Argument error : {}", pe.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IllegalArgumentException iae) {
        logger.error("Argument error : {}", iae.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (ConfigurationException ce) {
        logger.error("Configuration error : {}", ce.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start distributedlog server : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}

From source file:ee.ria.xroad.opmonitordaemon.OperationalDataRecordsGenerator.java

private static CommandLine parseCommandLine(String args[]) {
    try {/*  w ww  . j a v a 2  s.c  o  m*/
        return new BasicParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        log.error("Parsing command line failed: {}", e.getMessage());

        usage();

        System.exit(1);
    }

    return null;
}

From source file:de.haber.xmind2latex.cli.CliParameters.java

/**
 * Creates a {@link XMindToLatexExporter} for the given arguments.
 * // ww w  .  j  a  v a2  s.  c  o  m
 * @param args Arguments to configure this {@link XMindToLatexExporter}.
 * 
 * @return A created {@link XMindToLatexExporter} or null, if no {@link CliParameters#INPUT} parameter is used.
 * 
 * @throws ParseException, NumberFormatException for invalid arguments
 * @throws ConfigurationException for invalid input files
 * @throws IllegalArgumentException if the given input file does not exist
 */
public static XMindToLatexExporter build(String[] args) throws ParseException {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

    if (cmd.getOptions().length == 0) {
        throw new ParseException("Parameter -" + INPUT + " expected.");
    }

    if (cmd.hasOption(VERSION)) {
        printVersion();
    }

    CliParameters.validateNumberOfArguments(cmd, INPUT, options);
    if (cmd.hasOption(INPUT)) {
        File in = new File(cmd.getOptionValue(INPUT));
        Builder builder = new Builder(in);
        if (cmd.hasOption(FORCE)) {
            CliParameters.validateNumberOfArguments(cmd, FORCE, options);
            builder.overwritesExistingFiles(true);
        }

        File out;
        if (cmd.hasOption(OUTPUT)) {
            CliParameters.validateNumberOfArguments(cmd, OUTPUT, options);
            out = new File(cmd.getOptionValue(OUTPUT));
            builder.withTargetFile(out);
        }

        if (cmd.hasOption(TEMPLATE_LEVEL)) {
            CliParameters.validateNumberOfArguments(cmd, TEMPLATE_LEVEL, options);

            String level = cmd.getOptionValue(TEMPLATE_LEVEL);
            try {
                int levelAsInt = Integer.parseInt(level);
                if (levelAsInt < 0) {
                    throw new NumberFormatException();
                }
                builder.withMaxLevel(levelAsInt);
            } catch (NumberFormatException e) {
                ParseException ex = new ParseException(
                        "The level argument of option " + TEMPLATE_LEVEL + " has to be a positive integer.");
                ex.addSuppressed(e);
                throw ex;
            }

        }
        if (cmd.hasOption(HELP)) {
            CliParameters.validateNumberOfArguments(cmd, HELP, options);

            showHelp();
        }

        if (cmd.hasOption(ENVIRONMENT)) {
            CliParameters.validateNumberOfArguments(cmd, ENVIRONMENT, options);

            String[] env = cmd.getOptionValues(ENVIRONMENT);
            for (int i = 0; i + 2 < env.length; i = i + 3) {
                String level = env[i];
                String start = env[i + 1];
                String end = env[i + 2];
                try {
                    int levelAsInt = Integer.parseInt(level);
                    builder.withEnvironmentTemplates(levelAsInt, start, end);
                } catch (NumberFormatException e) {
                    ParseException ex = new ParseException(
                            "The level argument of option " + ENVIRONMENT + " has to be an integer.");
                    ex.addSuppressed(e);
                    throw ex;
                }
            }
        }
        if (cmd.hasOption(LEVEL)) {
            CliParameters.validateNumberOfArguments(cmd, LEVEL, options);

            String[] tmp = cmd.getOptionValues(LEVEL);

            for (int i = 0; i + 1 < tmp.length; i = i + 2) {
                String level = tmp[i];
                String template = tmp[i + 1];
                try {
                    int levelAsInt = Integer.parseInt(level);
                    builder.withTemplate(levelAsInt, template);
                } catch (NumberFormatException e) {
                    ParseException ex = new ParseException(
                            "The level argument of option " + LEVEL + " has to be an integer.");
                    ex.addSuppressed(e);
                    throw ex;
                }
            }
        }
        return builder.build();
    } else {
        return null;
    }
}

From source file:cc.redpen.Main.java

@SuppressWarnings("static-access")
public static int run(String... args) throws RedPenException {
    Options options = new Options();
    options.addOption("h", "help", false, "Displays this help information and exits");

    options.addOption(OptionBuilder.withLongOpt("format")
            .withDescription("Input file format (markdown,plain,wiki,asciidoc,latex,rest)").hasArg()
            .withArgName("FORMAT").create("f"));

    options.addOption(OptionBuilder.withLongOpt("conf").withDescription("Configuration file (REQUIRED)")
            .hasArg().withArgName("CONF FILE").create("c"));

    options.addOption(OptionBuilder.withLongOpt("result-format")
            .withDescription("Output result format (json,json2,plain,plain2,xml)").hasArg()
            .withArgName("RESULT FORMAT").create("r"));

    options.addOption(OptionBuilder.withLongOpt("limit").withDescription("Error limit number").hasArg()
            .withArgName("LIMIT NUMBER").create("l"));

    options.addOption(OptionBuilder.withLongOpt("sentence").withDescription("Input sentences").hasArg()
            .withArgName("INPUT SENTENCES").create("s"));

    options.addOption(OptionBuilder.withLongOpt("lang").withDescription("Language of error messages").hasArg()
            .withArgName("LANGUAGE").create("L"));

    options.addOption(OptionBuilder.withLongOpt("threshold")
            .withDescription("Threshold of error level (info, warn, error)").hasArg().withArgName("THRESHOLD")
            .create("t"));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("Displays version information and exits").create("v"));

    CommandLineParser commandLineParser = new BasicParser();
    CommandLine commandLine;/*  w ww . jav a 2s .com*/
    try {
        commandLine = commandLineParser.parse(options, args);
    } catch (ParseException e) {
        LOG.error("Error occurred in parsing command line options ");
        printHelp(options);
        return -1;
    }

    String inputFormat = "plain";
    String configFileName = null;
    String resultFormat = "plain";
    String inputSentence = null;
    String language = "en";
    String threshold = "error";

    int limit = DEFAULT_LIMIT;

    if (commandLine.hasOption("h")) {
        printHelp(options);
        return 0;
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        return 0;
    }
    if (commandLine.hasOption("f")) {
        inputFormat = commandLine.getOptionValue("f");
    }
    if (commandLine.hasOption("c")) {
        configFileName = commandLine.getOptionValue("c");
    }
    if (commandLine.hasOption("r")) {
        resultFormat = commandLine.getOptionValue("r");
    }
    if (commandLine.hasOption("l")) {
        limit = Integer.valueOf(commandLine.getOptionValue("l"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (commandLine.hasOption("s")) {
        inputSentence = commandLine.getOptionValue("s");
    }
    if (commandLine.hasOption("t")) {
        threshold = commandLine.getOptionValue("t");
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    String[] inputFileNames = commandLine.getArgs();
    if (!commandLine.hasOption("f")) {
        inputFormat = guessInputFormat(inputFileNames);
    }

    File configFile = resolveConfigLocation(configFileName);
    if (configFile == null) {
        LOG.error("Configuration file is not found.");
        printHelp(options);
        return 1;
    }

    if (inputFileNames.length == 0 && inputSentence == null) {
        LOG.error("Input is not given");
        printHelp(options);
        return 1;
    }

    RedPen redPen;
    try {
        redPen = new RedPen(configFile);
    } catch (RedPenException e) {
        LOG.error("Failed to parse input files: " + e);
        return -1;
    }

    List<Document> documents = getDocuments(inputFormat, inputSentence, inputFileNames, redPen);
    Map<Document, List<ValidationError>> documentListMap = redPen.validate(documents, threshold);

    Formatter formatter = FormatterUtils.getFormatterByName(resultFormat);
    if (formatter == null) {
        LOG.error("Unsupported format: " + resultFormat + " - please use xml, plain, plain2, json or json2");
        return -1;
    }
    String result = formatter.format(documentListMap);
    System.out.println(result);

    long errorCount = documentListMap.values().stream().mapToLong(List::size).sum();

    if (errorCount > limit) {
        LOG.error("The number of errors \"{}\" is larger than specified (limit is \"{}\").", errorCount, limit);
        return 1;
    } else {
        return 0;
    }
}

From source file:com.jktsoftware.amazondownloader.download.Application.java

private static boolean parseOptions(String[] args) {
    //add available command line options to the command line 
    //options object (for later parsing)
    Options options = addOptions();/* www. j av  a 2  s.c o m*/

    //create a basic command line parser object
    CommandLineParser parser = new BasicParser();

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

        //if the -rid option has been specified this
        //indicates we will not be using the default repository
        //specified within the spring.xml file and instead we
        //will be using the newly specified bucket repository
        if (cmd.hasOption("rid")) {
            _argrepoid = (cmd.getOptionValue("rid"));
        }
        //if the -oid has been specified we will be
        //downloading the specified object only from the
        //repository
        if (cmd.hasOption("oid")) {
            _argobjectidtodownload = (cmd.getOptionValue("oid"));
        }
        //these are the amazon access key and secret key parameters
        if (cmd.hasOption("s3ak")) {
            _awsS3accesskey = (cmd.getOptionValue("s3ak"));
        }
        if (cmd.hasOption("s3sk")) {
            _awsS3secretkey = (cmd.getOptionValue("s3sk"));
        }
        if (cmd.hasOption("sqsak")) {
            _awsSQSaccesskey = (cmd.getOptionValue("sqsak"));
        }
        if (cmd.hasOption("sqssk")) {
            _awsSQSsecretkey = (cmd.getOptionValue("sqssk"));
        }
        if (cmd.hasOption("sq")) {
            _awsSQSsuccessqueue = (cmd.getOptionValue("sq"));
        }
        if (cmd.hasOption("fq")) {
            _awsSQSfailqueue = (cmd.getOptionValue("fq"));
        }
        //if the -ls option has been specified then the program
        //will list the available objects within the repository
        if (cmd.hasOption("ls")) {
            _arglistobjects = true;
        }
        //if the -cdwn option has been specified we will
        //actually download the object. -download must be
        //within the command line to actually download the 
        //object as this will cost money
        if (cmd.hasOption("cdwn")) {
            _argstartdownloads = true;
        }
        //if the -wt option has been specified the 
        //program will wait for a specified period of time
        //in milliseconds before trying to download the
        //next file in the queue
        if (cmd.hasOption("wt")) {
            try {
                _argwaittime = new Long(cmd.getOptionValue("waittime")).longValue();
            } catch (Exception e) {
                _argwaittime = 0;
            }
        }
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar <name of jar> [options]", options);
            return false;
        }
    } catch (ParseException e1) {
        // if there is an error print the stack
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <name of jar> [options]", options);
        return false;
    }
    return true;
}

From source file:com.asakusafw.yaess.tools.GenerateExecutionId.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    String batchId = cmd.getOptionValue(OPT_BATCH_ID.getOpt());
    String flowId = cmd.getOptionValue(OPT_FLOW_ID.getOpt());
    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());

    SortedMap<String, String> pairs = new TreeMap<>();
    for (Map.Entry<Object, Object> entry : arguments.entrySet()) {
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (key instanceof String && value instanceof String) {
            pairs.put((String) key, (String) value);
        }// www.  jav  a  2 s. co m
    }
    Configuration result = new Configuration();
    result.batchId = batchId;
    result.flowId = flowId;
    result.arguments = pairs;
    return result;
}

From source file:com.example.geomesa.transformations.QueryTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args/*w w w  .j ava2s. c o m*/
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getCommonRequiredOptions();
    options.addOption(OptionBuilder.withArgName(FEATURE_NAME_ARG).hasArg().isRequired()
            .withDescription("the FeatureTypeName used to store the GDELT data, e.g.:  gdelt")
            .create(FEATURE_NAME_ARG));
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);
    //Disable states collection
    dsConf.put("collectStats", "false");
    DataStore dataStore = DataStoreFinder.getDataStore(dsConf);
    assert dataStore != null;

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(FEATURE_NAME_ARG);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // get the feature store used to query the GeoMesa data
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(simpleFeatureTypeName);

    // execute some queries
    basicQuery(simpleFeatureTypeName, featureStore);
    basicProjectionQuery(simpleFeatureTypeName, featureStore);
    basicTransformationQuery(simpleFeatureTypeName, featureStore);
    renamedTransformationQuery(simpleFeatureTypeName, featureStore);
    mutliFieldTransformationQuery(simpleFeatureTypeName, featureStore);
    geometricTransformationQuery(simpleFeatureTypeName, featureStore);

    // the list of available transform functions is available here:
    // http://docs.geotools.org/latest/userguide/library/main/filter.html - scroll to 'Function List'
}

From source file:geomesa.tutorial.QueryTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args//from   w w w .  j  a va  2 s  .  c  o  m
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getCommonRequiredOptions();
    options.addOption(OptionBuilder.withArgName(FEATURE_NAME_ARG).hasArg().isRequired()
            .withDescription("the FeatureTypeName used to store the GDELT data, e.g.:  gdelt")
            .create(FEATURE_NAME_ARG));
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);
    //Disable states collection
    dsConf.put("collectStats", "false");
    DataStore dataStore = DataStoreFinder.getDataStore(dsConf);
    assert dataStore != null;

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(FEATURE_NAME_ARG);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // get the feature store used to query the GeoMesa data
    FeatureStore featureStore = (AccumuloFeatureStore) dataStore.getFeatureSource(simpleFeatureTypeName);

    // execute some queries
    basicQuery(simpleFeatureTypeName, featureStore);
    basicProjectionQuery(simpleFeatureTypeName, featureStore);
    basicTransformationQuery(simpleFeatureTypeName, featureStore);
    renamedTransformationQuery(simpleFeatureTypeName, featureStore);
    mutliFieldTransformationQuery(simpleFeatureTypeName, featureStore);
    geometricTransformationQuery(simpleFeatureTypeName, featureStore);

    // the list of available transform functions is available here:
    // http://docs.geotools.org/latest/userguide/library/main/filter.html - scroll to 'Function List'
}

From source file:com.asakusafw.lang.inspection.cli.Cli.java

static Configuration parse(String... args) throws ParseException {
    LOG.debug("analyzing command line arguments: {}", Arrays.toString(args)); //$NON-NLS-1$

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

    Configuration results = new Configuration();
    results.input = parseFile(cmd, opts.input, true);
    results.output = parseFile(cmd, opts.output, false);
    results.path = parseOpt(cmd, opts.path, false);
    results.format = parseOpt(cmd, opts.format, false);
    results.properties = parseProperties(cmd, opts.properties);
    return results;
}

From source file:com.magnet.mmx.tsung.GenTestScriptCli.java

public void parse() throws IOException, TemplateException {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/* w  w w .  j  a  v a  2 s  .  com*/
    String servername = null, hostname = null, port = null, username = null, numusers = null;
    String templateDir = null, templateName = null, appKey = null, apiKey = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption(HELP_OPTION_SHORT)) {
            help();
        }

        if (cmd.hasOption(SERVER_OPTION_SHORT)) {
            servername = cmd.getOptionValue(SERVER_OPTION_SHORT);
        }
        if (cmd.hasOption(HOST_OPTION_SHORT)) {
            hostname = cmd.getOptionValue(HOST_OPTION_SHORT);
        }
        if (cmd.hasOption(PORT_OPTION_SHORT)) {
            port = cmd.getOptionValue(PORT_OPTION_SHORT);
        }
        if (cmd.hasOption(USERNAME_OPTION_SHORT)) {
            username = cmd.getOptionValue(USERNAME_OPTION_SHORT);
        }
        if (cmd.hasOption(APPID_OPTION_SHORT)) {
            appKey = cmd.getOptionValue(APPID_OPTION_SHORT);
        }
        if (cmd.hasOption(APIKEY_OPTION_SHORT)) {
            apiKey = cmd.getOptionValue(APIKEY_OPTION_SHORT);
        }

        if (cmd.hasOption(COUNT_OPTION_SHORT)) {
            numusers = cmd.getOptionValue(COUNT_OPTION_SHORT);
        }
        if (cmd.hasOption(TEMPLATE_DIR_OPTION_SHORT)) {
            templateDir = cmd.getOptionValue(TEMPLATE_DIR_OPTION_SHORT);
        }
        if (cmd.hasOption(TEMPLATE_NAME_OPTION_SHORT)) {
            templateName = cmd.getOptionValue(TEMPLATE_NAME_OPTION_SHORT);
        }
        if (servername == null || port == null || username == null || numusers == null) {
            log.log(Level.SEVERE, "Missing options");
            help();
        }
        GenTestScript.Settings settings = new GenTestScript.Settings();
        settings.userName = username;
        settings.appId = appKey;
        settings.apiKey = apiKey;
        settings.maxCount = Integer.valueOf(numusers);
        settings.outputDir = "output";
        settings.port = port;
        settings.servername = servername;
        settings.hostname = hostname;
        settings.templateDir = templateDir;
        settings.templateName = templateName;

        GenTestScript.generateScripts(settings);

        //      GenTestScript.generateScript(templateDir, templateName, servername, port, username, appId, numusers);
        //      GenTestScript.generateUserCsv(username, appId, Integer.valueOf(numusers), "output");

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse command line properties", e);
        help();
    }
}