The following examples show how to use
org.apache.commons.cli.DefaultParser
.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
CommandLine commandLine;
CommandLineParser parser = new DefaultParser();
Options options = new Options();
Option directoryOption = new Option("d", "dir", true, "directory to count scenarios in (e.g. story/release).");
Option topOption = new Option("t", "top", true, "the number of most popular steps");
options.addOption(directoryOption);
options.addOption(topOption);
commandLine = parser.parse(options, args);
StoryLoader storyLoader = BeanFactory.getBean(StoryLoader.class);
IPathFinder pathFinder = BeanFactory.getBean(IPathFinder.class);
String storyLocation = commandLine.hasOption(directoryOption.getOpt())
? commandLine.getOptionValue(directoryOption.getOpt()) : DEFAULT_STORY_LOCATION;
ExtendedConfiguration configuration = BeanFactory.getBean(ExtendedConfiguration.class);
fillStepList(configuration, storyLoader, pathFinder, storyLocation);
fillStepCandidates();
fillStepsWithStats(configuration);
printResults(commandLine, topOption, System.out);
commandLine = new DefaultParser().parse(OPTIONS, args);
} catch (ParseException e) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(
"java -jar org.mitre.quaerite.solrtools.WinnowAnalyzedElevate",
OPTIONS);
return;
Path inputElevate = Paths.get(commandLine.getOptionValue("e"));
Path winnowElevate = Paths.get(commandLine.getOptionValue("w"));
SearchClient client = SearchClientFactory.getClient(commandLine.getOptionValue("s"));
String analysisField = commandLine.getOptionValue("f");
DocSorter docSorter = new DocSorter(commandLine.getOptionValue("i"));
boolean commentWinnowed = (commandLine.hasOption("c") ? true : false);
WinnowAnalyzedElevate winnowAnalyzedElevate = new WinnowAnalyzedElevate(docSorter, commentWinnowed);
winnowAnalyzedElevate.execute(inputElevate, winnowElevate, client, analysisField);
commandLine = new DefaultParser().parse(OPTIONS, args);
} catch (ParseException e) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(
"java -jar org.mitre.quaerite.solrtools.ElevateQueryComparer",
OPTIONS);
return;
Matcher idMatcher = null;
if (commandLine.hasOption("r")) {
idMatcher = Pattern.compile(commandLine.getOptionValue("r")).matcher("");
SearchClient client = SearchClientFactory.getClient(commandLine.getOptionValue("s"));
String analysisField = commandLine.getOptionValue("f");
ElevateElevateComparer comparer = new ElevateElevateComparer();
comparer.compare(Paths.get(commandLine.getOptionValue("e1")),
Paths.get(commandLine.getOptionValue("e2")),
idMatcher,
client,
analysisField);
public static void prepare(String[] args) throws Exception {
// commons-cli命令行参数,需要带参数值
Options options = new Options();
// sql文件路径
options.addOption("sql", true, "sql config");
// 任务名称
options.addOption("name", true, "job name");
// 解析命令行参数
CommandLineParser parser = new DefaultParser();
CommandLine cl = parser.parse(options, args);
String sql = cl.getOptionValue("sql");
String name = cl.getOptionValue("name");
System.out.println("sql : " + sql);
System.out.println("name : " + name);
commandLine = new DefaultParser().parse(OPTIONS, args);
} catch (ParseException e) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(
"java -jar org.mitre.quaerite.cli.AddExperiments",
OPTIONS);
return;
Path resultsDir = Paths.get(commandLine.getOptionValue("d"));
Path dbDir = Paths.get(commandLine.getOptionValue("db"));
String scorer = "ndcg_10";
if (commandLine.hasOption("s")) {
scorer = commandLine.getOptionValue("s");
List<String> experiments = Arrays.asList(commandLine.getOptionValue("e")
.split(","));
if (experiments.size() < 2) {
System.err.println("must have > 1 experiment to compare");
dump(resultsDir, dbDir, scorer, experiments);
commandLine = new DefaultParser().parse(OPTIONS, args);
} catch (ParseException e) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(
"java -jar org.mitre.quaerite.cli.DumpExperiments",
OPTIONS);
return;
Path file = Paths.get(commandLine.getOptionValue("f"));
Path dbDir = Paths.get(commandLine.getOptionValue("db"));
dump(file, dbDir);
public static CliOptions parseEmbeddedModeClient(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(EMBEDDED_MODE_CLIENT_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
checkSessionId(line),
checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public static CliOptions parseGatewayModeClient(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(GATEWAY_MODE_CLIENT_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
checkSessionId(line),
checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
null,
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public static CliOptions parseGatewayModeGateway(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(GATEWAY_MODE_GATEWAY_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
null,
null,
checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public static void main(String[] args) throws IOException, ModelException, TranslateException {
Options options = Arguments.getOptions();
try {
DefaultParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args, null, false);
Arguments arguments = new Arguments(cmd);
Classifications classifications = predict(arguments);
logger.info("{}", classifications);
} catch (ParseException e) {
HelpFormatter formatter = new HelpFormatter();
formatter.setLeftPadding(1);
formatter.setWidth(120);
formatter.printHelp(e.getMessage(), options);
public static CliOptions parseEmbeddedModeClient(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(EMBEDDED_MODE_CLIENT_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
checkSessionId(line),
checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public static CliOptions parseGatewayModeClient(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(GATEWAY_MODE_CLIENT_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
checkSessionId(line),
checkUrl(line, CliOptionsParser.OPTION_ENVIRONMENT),
null,
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
line.getOptionValue(CliOptionsParser.OPTION_UPDATE.getOpt())
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public static CliOptions parseGatewayModeGateway(String[] args) {
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(GATEWAY_MODE_GATEWAY_OPTIONS, args, true);
return new CliOptions(
line.hasOption(CliOptionsParser.OPTION_HELP.getOpt()),
null,
null,
checkUrl(line, CliOptionsParser.OPTION_DEFAULTS),
checkUrls(line, CliOptionsParser.OPTION_JAR),
checkUrls(line, CliOptionsParser.OPTION_LIBRARY),
catch (ParseException e) {
throw new SqlClientException(e.getMessage());
public UicdCLIArgs(String[] args) throws ParseException {
options = new Options();
options.addOption(INPUT_OPTION_SHORT_NAME, "input", true, "Input File/Folder Path");
options.addOption(OUTPUT_OPTION_SHORT_NAME, "output", true, "Output Folder");
options.addOption(
DEVICES_OPTION_SHORT_NAME,
"devices",
true,
"Devices Serial Number (Separated by comma if more than one)");
options.addOption(CONFIG_OPTION_SHORT_NAME, "config", true, "Config File Path");
options.addOption(SCREEN_OPTION_SHORT_NAME, "screen", false, "Input File/Folder Path");
options.addOption(
MODE_OPTION_SHORT_NAME, "mode", true, "Play Mode (SINGLE|MULTIDEVICE|PLAYALL)");
options.addOption(
GLOBAL_VARIABLE_OPTION_SHORT_NAME,
"global_variable",
true,
"Global variable (uicd_key1=value1, uicd_key2=value2)");
CommandLineParser parser = new DefaultParser();
commandLine = parser.parse(options, args);
public boolean open(String[] args) {
CommandLineParser parser = new DefaultParser();
Options options = new Options();
options.addRequiredOption("m", "model", true, "set FILE for model file");
options.addOption("n", "nbest", true, "output n-best results");
options.addOption("v", "verbose", true, "set INT for verbose level");
options.addOption("c", "cost-factor", true, "set cost factor");
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch(ParseException e) {
System.err.println("invalid arguments");
return false;
String model = cmd.getOptionValue("m");
int nbest = Integer.valueOf(cmd.getOptionValue("n", "0"));
int vlevel = Integer.valueOf(cmd.getOptionValue("v", "0"));
double costFactor = Double.valueOf(cmd.getOptionValue("c", "1.0"));
return open(model, nbest, vlevel, costFactor);
public static CliOptions parseClient(String[] args) {
if (args.length < 1) {
throw new RuntimeException("./sql-submit -w <work_space_dir> -f <sql-file>");
try {
DefaultParser parser = new DefaultParser();
CommandLine line = parser.parse(CLIENT_OPTIONS, args, true);
return new CliOptions(
line.getOptionValue(CliOptionsParser.OPTION_SQL_FILE.getOpt()),
line.getOptionValue(CliOptionsParser.OPTION_WORKING_SPACE.getOpt())
catch (ParseException e) {
throw new RuntimeException(e.getMessage());
* The main method of this app.
* @param args The port the app will listen on.
* @throws Exception An Exception.
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port the will listen to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
final int port = Integer.parseInt(cmd.getOptionValue("port"));
// Idle timeout until actor instance is deactivated.
ActorRuntime.getInstance().getConfig().setActorIdleTimeout(Duration.ofSeconds(30));
// How often actor instances are scanned for deactivation and balance.
ActorRuntime.getInstance().getConfig().setActorScanInterval(Duration.ofSeconds(10));
// How long to wait until for draining an ongoing API call for an actor instance.
ActorRuntime.getInstance().getConfig().setDrainOngoingCallTimeout(Duration.ofSeconds(10));
// Determines whether to drain API calls for actors instances being balanced.
ActorRuntime.getInstance().getConfig().setDrainBalancedActors(true);
// Register the Actor class.
ActorRuntime.getInstance().registerActor(DemoActorImpl.class);
// Start Dapr's callback endpoint.
DaprApplication.start(port);
protected CommandLine doParse(String[] args) throws CommandLineParseException {
CommandLineParser parser = new DefaultParser();
CommandLine commandLine;
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption(HELP_ARG)) {
return printUsageAndThrow(null, ExitCode.HELP);
certificateAuthorityHostname = commandLine.getOptionValue(CERTIFICATE_AUTHORITY_HOSTNAME_ARG, TlsConfig.DEFAULT_HOSTNAME);
days = getIntValue(commandLine, DAYS_ARG, TlsConfig.DEFAULT_DAYS);
keySize = getIntValue(commandLine, KEY_SIZE_ARG, TlsConfig.DEFAULT_KEY_SIZE);
keyAlgorithm = commandLine.getOptionValue(KEY_ALGORITHM_ARG, TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM);
keyStoreType = commandLine.getOptionValue(KEY_STORE_TYPE_ARG, getKeyStoreTypeDefault());
if (KeystoreType.PKCS12.toString().equalsIgnoreCase(keyStoreType)) {
logger.info("Command line argument --" + KEY_STORE_TYPE_ARG + "=" + keyStoreType + " only applies to keystore, recommended truststore type of " + KeystoreType.JKS.toString() +
" unaffected.");
signingAlgorithm = commandLine.getOptionValue(SIGNING_ALGORITHM_ARG, TlsConfig.DEFAULT_SIGNING_ALGORITHM);
differentPasswordForKeyAndKeystore = commandLine.hasOption(DIFFERENT_KEY_AND_KEYSTORE_PASSWORDS_ARG);
} catch (ParseException e) {
return printUsageAndThrow("Error parsing command line. (" + e.getMessage() + ")", ExitCode.ERROR_PARSING_COMMAND_LINE);
return commandLine;
private static CommandLine parseAndValidateCommandLineArguments(String[] args) throws ParseException {
Options options = new Options();
options.addOption("help", false, "Print the help message.");
options.addOption("url", true, "The broker connection url.");
options.addOption("user", true, "The user to connect to the broker.");
options.addOption("password", true, "The password for the user.");
options.addOption("mode", true, "Whether to act as 'sender' or 'receiver'");
options.addOption("type", true, "Whether to use a queue or a topic.");
options.addOption("destination", true, "The name of the queue or topic");
options.addOption("name", true, "The name of the sender");
options.addOption("interval", true, "The interval in msec at which messages are generated. Default 1000");
options.addOption("notPersistent", false, "Send messages in non-persistent mode");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
printUsage(options);
if (!(cmd.hasOption("url") && cmd.hasOption("type") && cmd.hasOption("mode") && cmd.hasOption("destination"))) {
printUsage(options);
return cmd;
private static CommandLine parseAndValidateCommandLineArguments(String[] args) throws ParseException {
Options options = new Options();
options.addOption("help", false, "Print the help message.");
options.addOption("url", true, "The broker connection url.");
options.addOption("user", true, "The user to connect to the broker.");
options.addOption("password", true, "The password for the user.");
options.addOption("mode", true, "Whether to act as 'sender' or 'receiver'");
options.addOption("destination", true, "The name of the queue or topic");
options.addOption("name", true, "The name of the sender");
options.addOption("interval", true, "The interval in msec at which messages are generated. Default 1000");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
printUsage(options);
if (!(cmd.hasOption("url") && cmd.hasOption("mode") && cmd.hasOption("destination"))) {
printUsage(options);
return cmd;
private static CommandLine parseAndValidateCommandLineArguments(String[] args) throws ParseException {
Options options = new Options();
options.addOption("help", false, "Print the help message.");
options.addOption("url", true, "The broker connection url.");
options.addOption("user", true, "The user to connect to the broker.");
options.addOption("password", true, "The password for the user.");
options.addOption("mode", true, "Whether to act as 'sender' or 'receiver'");
options.addOption("type", true, "Whether to use a queue or a topic.");
options.addOption("destination", true, "The name of the queue or topic");
options.addOption("name", true, "The name of the sender");
options.addOption("interval", true, "The interval in msec at which messages are generated. Default 1000");
options.addOption("notPersistent", false, "Send messages in non-persistent mode");
options.addOption("ttl", true, "The time to live value for the message.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
printUsage(options);
if (!(cmd.hasOption("url") && cmd.hasOption("type") && cmd.hasOption("mode") && cmd.hasOption("destination"))) {
printUsage(options);
return cmd;
private static CommandLine parseAndValidateCommandLineArguments(String[] args) throws ParseException {
Options options = new Options();
options.addOption("help", false, "Print the help message.");
options.addOption("url", true, "The broker connection url.");
options.addOption("user", true, "The user to connect to the broker.");
options.addOption("password", true, "The password for the user.");
options.addOption("mode", true, "Whether to act as 'sender' or 'receiver'");
options.addOption("type", true, "Whether to use a queue or a topic.");
options.addOption("destination", true, "The name of the queue or topic");
options.addOption("name", true, "The name of the sender");
options.addOption("interval", true, "The interval in msec at which messages are generated. Default 1000");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
printUsage(options);
if (!(cmd.hasOption("url") && cmd.hasOption("mode") && cmd.hasOption("destination"))) {
printUsage(options);
return cmd;
public void withoutStage() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties(null);
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api-config-with-variables.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, null, "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
Assert.assertEquals(apiConfig.getBackendBasepath(), "resolvedToSomething");
} catch (Exception e) {
LOG.error("Error running test: withoutStage", e);
throw e;
public void withStage() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties("variabletest");
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api-config-with-variables.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, null, "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
Assert.assertEquals(apiConfig.getBackendBasepath(), "resolvedToSomethingElse");
} catch (Exception e) {
LOG.error("Error running test: withStage", e);
throw e;
public void usingOSEnvVariable() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties(null);
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api-config-with-variables.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, null, "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
String osArch = System.getProperty("os.arch");
Assert.assertEquals(apiConfig.getOrganization(), "API Development "+osArch);
} catch (Exception e) {
LOG.error("Error running test: usingOSEnvVariable", e);
throw e;
public void notDeclaredVariable() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties(null);
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api-config-with-variables.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, null, "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
Assert.assertEquals(apiConfig.getVersion(), "${notDeclared}");
} catch (Exception e) {
LOG.error("Error running test: notDeclaredVariable", e);
throw e;
public void configFileWithSpaces() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties(null);
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api config with spaces.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, null, "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
Assert.assertEquals(apiConfig.getVersion(), "${notDeclared}");
} catch (Exception e) {
LOG.error("Error running test: notDeclaredVariable", e);
throw e;
public void stageConfigInSubDirectory() throws AppException, ParseException {
try {
EnvironmentProperties props = new EnvironmentProperties(null);
CommandLine cmd = new DefaultParser().parse(new Options(), new String[]{});
new CommandParameters(cmd, null, props, false);
String testConfig = this.getClass().getResource("/com/axway/apim/test/files/basic/api-config-with-variables.json").getFile();
APIImportConfigAdapter adapter = new APIImportConfigAdapter(testConfig, "testStageProd", "notRelavantForThis Test", false);
DesiredAPI apiConfig = (DesiredAPI)adapter.getApiConfig();
Assert.assertEquals(apiConfig.getVersion(), "9.0.0");
Assert.assertEquals(apiConfig.getName(), "API Config from testStageProd sub folder");
} catch (Exception e) {
LOG.error("Error running test: notDeclaredVariable", e);
throw e;
* @param _args an array of {@link java.lang.String} objects.
public static void main(String[] _args){
// Prepare parsing of cmd line arguments
final Options options = new Options();
options.addOption("digest", "digest", true, "Delete all existing results before upload; otherwise only upload results for AffectedLibraries not already existing in the backend");
try {
final CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, _args);
if(cmd.hasOption("digest")){
String digest = cmd.getOptionValue("digest");
log.info("Running patcheval to assess all bugs of digest["+digest+"], all other options will be ignored.");
DigestAnalyzer d = new DigestAnalyzer(digest);
d.analyze();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static LinuxCommand parse(String line) throws ParseException {
String[] array = splitIgnoreQuotes(line);
if (array.length == 0) {
throw new ParseException("Command can't be empty");
StandardCommand command = standardCommands.get(array[0]);
if (command == null) {
throw new ParseException("Illegal command " + array[0] + ", use " + standardCommands.keySet());
return new LinuxCommand(command, new DefaultParser().parse(command.getStandardOptions(), array));