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:co.cask.cdap.security.tools.AccessTokenClient.java

/**
 * Parse the command line arguments./*  w  w w .ja  va 2s . c  o m*/
 */
void parseArguments(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.err.println("Could not parse arguments correctly.");
        usage(true);
    }

    if (commandLine.hasOption(ConfigurableOptions.HELP)) {
        usage(false);
        help = true;
        return;
    }

    useSsl = commandLine.hasOption(ConfigurableOptions.SSL);
    disableCertCheck = commandLine.hasOption(ConfigurableOptions.DISABLE_CERT_CHECK);

    host = commandLine.getOptionValue(ConfigurableOptions.HOST, "localhost");

    if (commandLine.hasOption(ConfigurableOptions.PORT)) {
        try {
            port = Integer.parseInt(commandLine.getOptionValue(ConfigurableOptions.PORT));
        } catch (NumberFormatException e) {
            usage("--port must be an integer value");
        }
    } else {
        port = (useSsl) ? SSL_PORT : NO_SSL_PORT;
    }

    username = commandLine.getOptionValue(ConfigurableOptions.USER_NAME, System.getProperty("user.name"));

    if (username == null) {
        usage("Specify --username to login as a user.");
    }

    password = commandLine.getOptionValue(ConfigurableOptions.PASSWORD);

    if (password == null) {
        Console console = System.console();
        password = String.valueOf(console.readPassword(String.format("Password for %s: ", username)));
    }

    if (commandLine.hasOption(ConfigurableOptions.FILE)) {
        filePath = commandLine.getOptionValue(ConfigurableOptions.FILE);
    } else {
        usage("Specify --file to save to file");
    }

    if (commandLine.getArgs().length > 0) {
        usage(true);
    }
}

From source file:co.cask.cdap.gateway.tools.ClientToolBase.java

/**
 * Parses args based on the options that were added when buildOptions was called.
 *
 * @param args The array of arguments to parse.
 * @return Returns true if the parsing succeeded and the help option was not specified.
 *//*  w ww . j  av a  2s  . c  o  m*/
protected boolean parseArguments(String[] args) {
    // parse generic args first
    CommandLineParser parser = new BasicParser();
    // Check all the options of the command line
    try {
        CommandLine line = parser.parse(options, args);
        parseBasicArgs(line);
        if (help) {
            return false;
        }
        return parseAdditionalArguments(line);
    } catch (ParseException e) {
        printUsage(true);
    } catch (IndexOutOfBoundsException e) {
        printUsage(true);
    }
    return true;
}

From source file:com.spidasoftware.EclipseFormatter.Formatter.java

/**
 * A no-argument method that will return the command-line arguments as a 
 * CommandLine object.//  w  ww. jav a2 s .  c o  m
 *
 * @param args The command line arguments. 
 * @param options The options that this class can identify.
 * @return the CommandLine object holding the command line arguments.
 */
public static CommandLine getOptions(String[] args, Options options) {
    options.addOption("b", false, "create a backup file");
    options.addOption("help", false, "print this message");
    options.addOption("version", false, "version of the formatter");
    options.addOption("java", false, "only format java files");
    options.addOption("groovy", false, "only format groovy files");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        log.error(e, e);
    }
    return cmd;
}

From source file:com.boundary.plugin.sdk.jmx.ExportMBeans.java

private void parseCommandLineOptions(String[] args) throws Exception {

    buildOptions();/*from ww  w. ja  v a 2 s.c  om*/

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

    // If the help argument is present then display usage
    if (cmd.hasOption("?") == true) {
        usage();
    }

    setExportType();
}

From source file:co.cask.cdap.data.tools.ReplicationStatusTool.java

private static CommandLine parseArgs(String[] args) throws ParseException {
    options.addOption(MASTER_OPTION, false, "Use when running on Master Cluster");
    options.addOption(OUTPUT_OPTION, true, "FilePath to dump Master Cluster Status");
    options.addOption(INPUT_OPTION, true, "Status File copied from the Master Cluster");
    options.addOption(FILE_OPTION, true, "File with HDFS Paths");
    options.addOption(SHUTDOWNTIME_OPTION, true,
            "Override cdap-master Shutdown Time on Master Cluster [epoch time]");
    options.addOption(DEBUG_OPTION, false, "Dump Cluster Status for debugging");
    options.addOption(HELP_OPTION, false, "Show this Usage");
    CommandLineParser parser = new BasicParser();
    return parser.parse(options, args);
}

From source file:com.asakusafw.yaess.bootstrap.Yaess.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    LOG.debug("Analyzing YAESS bootstrap arguments: {}", Arrays.toString(args));

    ArgumentList argList = ArgumentList.parse(args);
    LOG.debug("Argument List: {}", argList);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, argList.getStandardAsArray());

    String profile = cmd.getOptionValue(OPT_PROFILE.getOpt());
    LOG.debug("Profile: {}", profile);
    String script = cmd.getOptionValue(OPT_SCRIPT.getOpt());
    LOG.debug("Script: {}", script);
    String batchId = cmd.getOptionValue(OPT_BATCH_ID.getOpt());
    LOG.debug("Batch ID: {}", batchId);
    String flowId = cmd.getOptionValue(OPT_FLOW_ID.getOpt());
    LOG.debug("Flow ID: {}", flowId);
    String executionId = cmd.getOptionValue(OPT_EXECUTION_ID.getOpt());
    LOG.debug("Execution ID: {}", executionId);
    String phaseName = cmd.getOptionValue(OPT_PHASE_NAME.getOpt());
    LOG.debug("Phase name: {}", phaseName);
    String plugins = cmd.getOptionValue(OPT_PLUGIN.getOpt());
    LOG.debug("Plug-ins: {}", plugins);
    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());
    LOG.debug("Execution arguments: {}", arguments);
    Properties variables = cmd.getOptionProperties(OPT_ENVIRONMENT_VARIABLE.getOpt());
    LOG.debug("Environment variables: {}", variables);
    Properties definitions = cmd.getOptionProperties(OPT_DEFINITION.getOpt());
    LOG.debug("YAESS feature definitions: {}", definitions);

    LOG.debug("Loading plugins: {}", plugins);
    List<File> pluginFiles = CommandLineUtil.parseFileList(plugins);
    ClassLoader loader = CommandLineUtil.buildPluginLoader(Yaess.class.getClassLoader(), pluginFiles);

    Configuration result = new Configuration();
    result.mode = computeMode(flowId, executionId, phaseName);

    LOG.debug("Loading profile: {}", profile);
    File file = new File(profile);
    file = findCustomProfile(file, definitions.getProperty(KEY_CUSTOM_PROFILE));
    try {/*from ww w.  j  a  va2  s.co  m*/
        definitions.remove(KEY_CUSTOM_PROFILE);
        Map<String, String> env = new HashMap<>();
        env.putAll(System.getenv());
        env.putAll(toMap(variables));
        result.context = new ProfileContext(loader, new VariableResolver(env));
        Properties properties = CommandLineUtil.loadProperties(file);
        result.profile = YaessProfile.load(properties, result.context);
    } catch (Exception e) {
        YSLOG.error(e, "E01001", file.getPath());
        throw new IllegalArgumentException(MessageFormat.format("Invalid profile \"{0}\".", file), e);
    }

    LOG.debug("Loading script: {}", script);
    try {
        Properties properties = CommandLineUtil.loadProperties(new File(script));
        result.script = properties;
    } catch (Exception e) {
        YSLOG.error(e, "E01002", script);
        throw new IllegalArgumentException(MessageFormat.format("Invalid script \"{0}\".", script), e);
    }

    result.batchId = batchId;
    result.flowId = flowId;
    result.executionId = executionId;
    if (phaseName != null) {
        result.phase = ExecutionPhase.findFromSymbol(phaseName);
        if (result.phase == null) {
            throw new IllegalArgumentException(MessageFormat.format("Unknown phase name \"{0}\".", phaseName));
        }
    }

    result.arguments = toMap(arguments);
    result.definitions = toMap(definitions);
    result.extensions = CommandLineUtil.loadExtensions(loader, argList.getExtended());

    LOG.debug("Analyzed YAESS bootstrap arguments");
    return result;
}

From source file:com.carlstahmer.estc.recordimport.daemon.Conf.java

/**
 * <p>Checks for passed command line arguments and replaces .yml loaded values with those
 * entered at the command line as appropriate.</p>
 *
 * @param  args       command line String[] args array
 * @return         a boolean value indicate whether or not method executed successfully
 *///from w  w w. j  a va  2s . c  o m
public boolean checkArgs(String[] args) {

    boolean loaded = false;

    try {
        Options options = new Options();
        options.addOption("listendir", true, "full directory path to listen directory");
        options.addOption("writedir", true, "full directory path to write output records");
        options.addOption("orgcode", true, "the marc orgcode of the cataloge owner");
        options.addOption("runinterval", true, "the time to wait between process spawning");
        options.addOption("dbserver", true, "the sql server");
        options.addOption("dbname", true, "the sql server database name");
        options.addOption("dbuser", true, "the sql user");
        options.addOption("dbpass", true, "the sql user");
        options.addOption("langscope", true, "a csv list of MARC language codes for in-scope languages");
        options.addOption("debug", false, "run in debug mode - verbose logging");
        options.addOption("console", false, "write log to console instead of database");
        options.addOption("liberal", false, "keep records with missing control data");
        options.addOption("estccodes", false,
                "csv list of institutional codes that represent ESTC bib records");
        options.addOption("help", false, "get help");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("listendir")) {
            String ldirVal = cmd.getOptionValue("listendir");
            if (ldirVal != null) {
                listenDir = ldirVal;
            }
        }
        if (cmd.hasOption("writedir")) {
            String wdirVal = cmd.getOptionValue("writedir");
            if (wdirVal != null) {
                writeDir = wdirVal;
            }
        }
        if (cmd.hasOption("orgcode")) {
            String ocVal = cmd.getOptionValue("orgcode");
            if (ocVal != null) {
                orgcode = ocVal;
            }
        }
        if (cmd.hasOption("runinterval")) {
            String riVal = cmd.getOptionValue("runinterval");
            if (riVal != null) {
                runInterval = Integer.parseInt(riVal);
            }
        }

        if (cmd.hasOption("dbserver")) {
            String srvVal = cmd.getOptionValue("dbserver");
            if (srvVal != null) {
                dbserver = srvVal;
            }
        }
        if (cmd.hasOption("dbname")) {
            String dbnameVal = cmd.getOptionValue("dbname");
            if (dbnameVal != null) {
                dbname = dbnameVal;
            }
        }
        if (cmd.hasOption("dbuser")) {
            String dbuserVal = cmd.getOptionValue("dbuser");
            if (dbuserVal != null) {
                dbuser = dbuserVal;
            }
        }
        if (cmd.hasOption("dbpass")) {
            String dbpassVal = cmd.getOptionValue("dbpass");
            if (dbpassVal != null) {
                dbpass = dbpassVal;
            }
        }
        if (cmd.hasOption("debug")) {
            debug = true;
        }
        if (cmd.hasOption("console")) {
            console = true;
        }
        if (cmd.hasOption("liberal")) {
            liberal = true;
        }
        if (cmd.hasOption("langscope")) {
            String langscopeVal = cmd.getOptionValue("langscope");
            if (langscopeVal != null) {
                langscope = langscopeVal;
            }
        }
        if (cmd.hasOption("estccodes")) {
            String langscopeVal = cmd.getOptionValue("estccodes");
            if (langscopeVal != null) {
                estcCodesCSV = langscopeVal;
            }
        }
        if (cmd.hasOption("help")) {
            String HelpString = "Requires the presence of a config.yml in the application root to run correcly. ";
            HelpString = HelpString + "Values in the config can be overwritten at runtime via command line ";
            HelpString = HelpString + "arguments as follows:\n\n";
            HelpString = HelpString + "-listendir [/dirctory/path/of/listen/directory]\n";
            HelpString = HelpString + "-writedir [/directory/path/of/output/directory]\n";
            HelpString = HelpString + "-runinterval [the interval to wait between listinging attempts]\n";
            HelpString = HelpString + "-orgcode [the marc org code to use in constucting the new records]\n";
            HelpString = HelpString + "-dbserver [the sql database server]\n";
            HelpString = HelpString + "-dbname [the sql database name]\n";
            HelpString = HelpString + "-dbuser [the sql database user]\n";
            HelpString = HelpString + "-dbpass [the sql database password]\n";
            HelpString = HelpString + "-debug [runs application in debug mode - verbose logging]\n";
            HelpString = HelpString + "-console [writes log output to console instead of database]\n";
            HelpString = HelpString + "-help [runs this help message]\n\n";
            HelpString = HelpString + "Config.yml file must be in place even if you are supplying information ";
            HelpString = HelpString + "via the command line.";
            System.out.println(HelpString);
            System.exit(0);
        }

        if (langscope.length() > 0) {
            setLangCodes();
        }

        loaded = true;

    } catch (ParseException e) {
        System.err.println("ERROR:\tCommand Line Argument Error: " + e.getMessage());
        loaded = false;
    }

    return loaded;

}

From source file:com.spidasoftware.EclipseFormatter.FormatterTest.java

/**
 * Test where Formatter.formatOne does not return a backup file when ran on a java file
 *//*from w w w .j  a va  2s .  co m*/
public void testformatOneNoBackupFileJava() {
    log.info("Formatter.formatOne returns no backup file when ran on a java file when the option is not set");
    Options options = new Options();
    CommandLine cmd = null;
    CommandLineParser parser = new BasicParser();
    try {
        cmd = parser.parse(options, new String[] {});
        FileUtils.writeStringToFile(javaFile, "package groovyTest;\npublic class genericJavaClass"
                + "{\npublic static void main(String[] args) {\n// TODO Auto-generated method stub\n}\n}");
    } catch (ParseException e) {
        log.error(e, e);
    } catch (IOException e) {
        log.error(e, e);
    }
    nameWithDate = Formatter.formatOne(javaFile, cmd);
    assertTrue("Formatter.formatOne did not return a backup file", nameWithDate == null);
}

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

private static void start(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);
    String sourcePath = cmd.getOptionValue(OPT_SOURCEPATH.getOpt());
    String output = cmd.getOptionValue(OPT_OUTPUT.getOpt());
    String encoding = cmd.getOptionValue(OPT_ENCODING.getOpt(), "UTF-8"); //$NON-NLS-1$
    String[] classes = cmd.getOptionValues(OPT_CLASSES.getOpt());

    List<Class<?>> operatorClasses = Lists.create();
    for (String className : classes) {
        Class<?> oc = Class.forName(className);
        operatorClasses.add(oc);//from   w ww.  j  av  a 2  s  . c o  m
    }
    compile(new File(sourcePath), new File(output), Charset.forName(encoding), operatorClasses);
}

From source file:com.logicmonitor.ft.jmxstat.JMXStatMain.java

/**
 * @param args : arguments array//from   ww  w.  j av  a  2  s . c o m
 * @return Run Parameter
 */
private static RunParameter ARGSAnalyser(String[] args) {

    Options options = new Options();
    options.addOption(new Option("h", "help", false, "show this help message"))
            .addOption(new Option("u", true, "User name for remote process"))
            .addOption(new Option("p", true, "Password for remote process"))
            .addOption(new Option("f", true, "Path to the configure file"))
            .addOption(new Option("t", true, "Exit after scanning jmx-paths n times"))
            .addOption(new Option("i", true, "Interval between two scan tasks, unit is second"))
            .addOption(new Option("a", false, "Show alias names instead of jmx paths"));

    CommandLineParser parser = new BasicParser();
    RunParameter runParameter = new RunParameter();
    ArrayList<JMXInPath> inputtedPaths = new ArrayList<JMXInPath>();
    try {
        CommandLine cli = parser.parse(options, args);
        if (args.length == 0 || cli.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jmxstat jmxURL [jmx path lists]", "To view statuses of jmx paths:", options,
                    "@Support by LogicMonitor", true);
            exit(0);
        }

        runParameter.setValid(true);
        if (cli.hasOption('a')) {
            runParameter.setShowAliasTitle(true);
        }
        if (cli.hasOption('f')) {
            List<JMXInPath> paths_from_file = getPathsFromFile(cli.getOptionValue('f'));
            inputtedPaths.addAll(paths_from_file);
        }
        if (cli.hasOption('t')) {
            try {
                int times = Integer.valueOf(cli.getOptionValue('t'));
                if (times < 0)
                    System.out.println("The argument after <-t> is useless here since it's a negative number.");
                else
                    runParameter.setTimes(times);
            } catch (Exception e) {
                runParameter.setValid(false);
                runParameter.setValidInfo(
                        runParameter.getValidInfo() + "Argument after <-t> should be an integer\n");
            }
        }
        if (cli.hasOption('u')) {
            runParameter.setUsername(cli.getOptionValue('u'));
        }
        if (cli.hasOption('p')) {
            runParameter.setPassword(cli.getOptionValue('p'));
        }
        if (cli.hasOption('i')) {
            try {
                int interval = Integer.valueOf(cli.getOptionValue('i'));
                if (interval < 0)
                    System.err.println("The interval value is negative! Using default set!");
                else {
                    runParameter.setInterval(interval);
                }
            } catch (Exception e) {
                runParameter.setValid(false);
                runParameter.setValidInfo(
                        runParameter.getValidInfo() + "Argument after <-i> should be an integer\n");
            }
        }
        List<String> others = cli.getArgList();
        boolean jmxurl_found = false;
        for (String other : others) {
            if (other.toLowerCase().startsWith("service:jmx")) {
                if (jmxurl_found) {
                    runParameter.setValid(false);
                    runParameter.setValidInfo(runParameter.getValidInfo() + "multiple jmxurl found\n");
                    return runParameter;
                } else {
                    jmxurl_found = true;
                    runParameter.setSurl(other.toLowerCase());
                }
            } else {
                inputtedPaths.add(new JMXInPath(other));
            }
        }
        if (!jmxurl_found) {
            runParameter.setValid(false);
            runParameter.setValidInfo(runParameter.getValidInfo()
                    + "No jmxurl found. The jmxurl should start with \"service:jmx\" \n");
        }
    } catch (ParseException e) {
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "Exception caught while parse arguments!\n");
    }

    if (inputtedPaths.isEmpty()) {
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "No jmx paths inputted");
    } else {
        runParameter.setPaths(inputtedPaths);
    }
    return runParameter;
}