下面列出了怎么用org.apache.commons.cli.Options的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt adminExt = new DefaultMQAdminExt(rpcHook);
adminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String topic = commandLine.getOptionValue('t').trim();
if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
adminExt.start();
deleteTopic(adminExt, clusterName, topic);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
e.printStackTrace();
} finally {
adminExt.shutdown();
}
}
static Options buildGeneralOptions(Options opts) {
Options r = new Options();
for (Object o : opts.getOptions())
r.addOption((Option) o);
Option libjars =
OptionBuilder.withArgName("paths").hasArg().withDescription("comma separated jars to be used by the submitted topology").create("libjars");
r.addOption(libjars);
optionProcessors.put("libjars", new LibjarsProcessor());
Option conf = OptionBuilder.withArgName("configuration file").hasArg().withDescription("an application configuration file").create("conf");
r.addOption(conf);
optionProcessors.put("conf", new ConfFileProcessor());
// Must come after `conf': this option is of higher priority
Option extraConfig = OptionBuilder.withArgName("D").hasArg().withDescription("extra configurations (preserving types)").create("D");
r.addOption(extraConfig);
optionProcessors.put("D", new ExtraConfigProcessor());
return r;
}
/**
* Displays the command line options on stdout
*
* @param options
*/
private static void displayCommandLineOptions(Options options) {
// Display help
final String commandLineSyntax = "java transitime.jar";
final PrintWriter writer = new PrintWriter(System.out);
final HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(writer,
80, // printedRowWidth
commandLineSyntax,
"args:", // header
options,
2, // spacesBeforeOption
2, // spacesBeforeOptionDescription
null, // footer
true); // displayUsage
writer.write("Also need to set VM parameters: \n" +
" -Dtransitime.core.agencyId=<agencyId>\n");
writer.close();
}
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
String topic = commandLine.getOptionValue('t').trim();
try {
defaultMQAdminExt.start();
Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic);
for (String value : clusters) {
System.out.printf("%s%n", value);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
@Override
public int run(String[] args) throws Exception {
Options options = new Options();
log.info("----- jobs args: " + Arrays.toString(args));
try {
options.addOption(OPTION_DELETE);
parseOptions(options, args);
log.info("options: '" + getOptionsAsString() + "'");
log.info("delete option value: '" + getOptionValue(OPTION_DELETE) + "'");
delete = Boolean.parseBoolean(getOptionValue(OPTION_DELETE));
Configuration conf = HBaseConfiguration.create(getConf());
cleanUnusedHdfsFiles(conf);
cleanUnusedHBaseTables(conf);
cleanUnusedIntermediateHiveTable(conf);
return 0;
} catch (Exception e) {
e.printStackTrace(System.err);
throw e;
}
}
@Override
protected void configureOptions(Options options) {
Option nameOption = Option.builder("n")
.longOpt("name")
.desc("Specify the name of the Waltz cluster")
.hasArg()
.build();
Option forceOption = Option.builder("f")
.longOpt("force")
.desc("Delete cluster even if cluster names don't match")
.hasArg(false)
.build();
Option cliCfgOption = Option.builder("c")
.longOpt("cli-config-path")
.desc("Specify the cli config file path required for ZooKeeper connection string, ZooKeeper root path")
.hasArg()
.build();
cliCfgOption.setRequired(true);
nameOption.setRequired(true);
forceOption.setRequired(false);
options.addOption(cliCfgOption);
options.addOption(nameOption);
options.addOption(forceOption);
}
/**
* Parses the arguments. The valid arguments are:
* --help or -h : prints out help message for this main class.
* --json or -j : the JSON file.
* @param args the arguments passed in as options.
*/
@Override
public void parseArgs(String [] args) throws AdeUsageException{
Options options = new Options();
buildOptions(options);
CommandLineParser parser = new GnuParser();
CommandLine line = parseLine(parser,options,args);
if (line.hasOption('h')) {
new HelpFormatter().printHelp(this.getClass().getSimpleName(), options);
System.exit(0);
}
if (line.hasOption('j')){
String jsonFile = line.getOptionValue("j");
inputJSONFile = new File(jsonFile);
validateFile(inputJSONFile);
} else{
new HelpFormatter().printHelp(this.getClass().getSimpleName(), options);
throw new AdeUsageException("Must specify a JSON file path using the -j option.");
}
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt adminExt = new DefaultMQAdminExt(rpcHook);
adminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String topic = commandLine.getOptionValue('t').trim();
if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
adminExt.start();
deleteTopic(adminExt, clusterName, topic);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
adminExt.shutdown();
}
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
final String topic = commandLine.getOptionValue('t').trim();
final String key = commandLine.getOptionValue('k').trim();
this.queryByKey(defaultMQAdminExt, topic, key);
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultMQAdminExt.shutdown();
}
}
public static void main(String[] args) throws Exception {
Options options = buildOptions();
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
runCommand(cmd);
} catch (ParseException e) {
System.out.println(e.getMessage());
new HelpFormatter().printHelp("mpt", options);
System.exit(-1);
}
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
final String msgId = commandLine.getOptionValue('i').trim();
final String topic = commandLine.getOptionValue('t').trim();
if (commandLine.hasOption('g') && commandLine.hasOption('d')) {
final String consumerGroup = commandLine.getOptionValue('g').trim();
final String clientId = commandLine.getOptionValue('d').trim();
ConsumeMessageDirectlyResult result =
defaultMQAdminExt.consumeMessageDirectly(consumerGroup, clientId, topic, msgId);
System.out.printf("%s", result);
} else {
queryById(defaultMQAdminExt, topic, msgId);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultMQAdminExt.shutdown();
}
}
@Test
public void testExecute() {
TopicRouteSubCommand cmd = new TopicRouteSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
GetConsumerStatusCommand cmd = new GetConsumerStatusCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-t unit-test", "-i clientid"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
public static void main(String[] args) {
System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, "127.0.0.1:9876");
ResetOffsetByTimeCommand cmd = new ResetOffsetByTimeCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs =
new String[] { "-t qatest_TopicTest", "-g qatest_consumer", "-s 1389098416742", "-f true" };
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs,
cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
/**
* Prints the usage message and exits.
*
* @param options The command line {@code Options}.
* @param status The status to exit with.
*/
private static void printUsage(Options options, int status) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -Xmx1G -jar freecol.jar [OPTIONS]",
options);
quit(status);
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
boolean result = false;
defaultMQAdminExt.start();
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
result = defaultMQAdminExt.cleanExpiredConsumerQueueByAddr(addr);
}
else {
String cluster = commandLine.getOptionValue('c');
if (null != cluster)
cluster = cluster.trim();
result = defaultMQAdminExt.cleanExpiredConsumerQueue(cluster);
}
System.out.println(result ? "success" : "false");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
defaultMQAdminExt.shutdown();
}
}
@Test
public void testBadCommandLineArguments5() throws ParseException {
String[] args = {"badargument"};
Options options = DGACommandLineUtil.generateOptions();
DGAConfiguration conf = DGACommandLineUtil.parseCommandLine(args, options);
assertEquals(conf.getCustomArgumentProperties().size(), 0);
assertEquals(conf.getGiraphProperties().size(), 0);
}
@Override
@SuppressWarnings("static-access")
public Options getOptions() {
Options options = new Options();
options.addOption(Option.builder().longOpt("workflow")
.desc("the workflow id")
.hasArg()
.required()
.argName("ID")
.build());
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt adminExt = new DefaultMQAdminExt(rpcHook);
adminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
adminExt.start();
String topic = commandLine.getOptionValue('t').trim();
String ips = commandLine.getOptionValue('i').trim();
final String[] split = ips.split(",");
final List<String> ipList = new LinkedList<String>();
for (String ip : split) {
ipList.add(ip);
}
final TopicRouteData topicRouteData = adminExt.examineTopicRouteInfo(topic);
final Set<MessageQueue> mqs = MQClientInstance.topicRouteData2TopicSubscribeInfo(topic, topicRouteData);
final AllocateMessageQueueAveragely averagely = new AllocateMessageQueueAveragely();
RebalanceResult rr = new RebalanceResult();
for (String i : ipList) {
final List<MessageQueue> mqResult = averagely.allocate("aa", i, new ArrayList<MessageQueue>(mqs), ipList);
rr.getResult().put(i, mqResult);
}
final String json = RemotingSerializable.toJson(rr, false);
System.out.printf("%s%n", json);
} catch (Exception e) {
e.printStackTrace();
} finally {
adminExt.shutdown();
}
}
public static Options createOptions(){
Option help = new Option( "help", "print this message" );
Option modelFile = Option.builder("model").argName("file").hasArg()
.desc("use given file for configuration and model").build();
Option testDataSet = Option.builder("test").argName("file").hasArg()
.desc("use given file for testing the model").build();
Option reportFile = Option.builder("report").argName("file").hasArg()
.desc("specify report file name").build();
Option evalType = Option.builder("eval").argName("evalType").hasArg()
.desc("specify type of evaluator").build();
Option k = Option.builder("k").argName("k").hasArg()
.desc("specify k-value for evaluators which use @k").build();
Option version = new Option( "version", "print the version information and exit" );
Option verbose = new Option( "verbose", "be extra verbose" );
Option noverbose = new Option( "noverbose", "override verboseness" );
Option debug = new Option( "debug", "print debugging information" );
Options options = new Options();
options.addOption(help)
.addOption(modelFile)
.addOption(testDataSet)
.addOption(reportFile)
.addOption(evalType)
.addOption(k)
.addOption(version)
.addOption(verbose)
.addOption(noverbose)
.addOption(debug);
return options;
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ProducerConnectionSubCommand cmd = new ProducerConnectionSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-producer-group", "-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String group = commandLine.getOptionValue('g').trim();
String topic = commandLine.getOptionValue('t').trim();
ProducerConnection pc = defaultMQAdminExt.examineProducerConnectionInfo(group, topic);
int i = 1;
for (Connection conn : pc.getConnectionSet()) {
System.out.printf("%04d %-32s %-22s %-8s %s%n",
i++,
conn.getClientId(),
conn.getClientAddr(),
conn.getLanguage(),
MQVersion.getVersionDesc(conn.getVersion())
);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultMQAdminExt.shutdown();
}
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ConsumerProgressSubCommand cmd = new ConsumerProgressSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
public static Options buildOptions() {
Options options = new Options();
options.addOption("a", GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME, true,
"Application name");
options.addOption("d", GobblinClusterConfigurationKeys.APPLICATION_ID_OPTION_NAME, true,
"Application id");
options.addOption("i", GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME, true,
"Helix instance name");
options.addOption(Option.builder("t").longOpt(GobblinClusterConfigurationKeys.HELIX_INSTANCE_TAGS_OPTION_NAME)
.hasArg(true).required(false).desc("Helix instance tags").build());
return options;
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "topic name");
opt.setRequired(true);
options.addOption(opt);
return options;
}
/**
* Parses the set of input parameters for things that look like "-Pkey=value" and will return the
* key/value pairs as a Properties object.
*/
public static Properties getTripleaProperties(final String... args) {
final Options options = getOptions();
final CommandLineParser parser = new DefaultParser();
try {
final CommandLine cli = parser.parse(options, args);
return cli.getOptionProperties(TRIPLEA_PROPERTY_PREFIX);
} catch (final ParseException e) {
throw new IllegalArgumentException("Failed to parse args: " + Arrays.toString(args), e);
}
}
public SparkCubingByLayer() {
options = new Options();
options.addOption(OPTION_INPUT_TABLE);
options.addOption(OPTION_INPUT_PATH);
options.addOption(OPTION_CUBE_NAME);
options.addOption(OPTION_SEGMENT_ID);
options.addOption(OPTION_META_URL);
options.addOption(OPTION_OUTPUT_PATH);
}
public static void main(String[] args) throws IOException, InterruptedException, ParseException {
final Options options = new Options();
options.addOption("f", "force", false, "Force auto balance");
options.addOption("d", "dryrun", false, "Dry run");
options.addOption("r", "noresolve", false, "Don't resolve host names");
options.addOption("h", "host", true, "Host to connect to (default: localhost)");
options.addOption("p", "port", true, "Port to connect to (default: 7199)");
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(options, args);
new Main().run(cmd);
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("i", "messageId", true, "unique message ID");
opt.setRequired(false);
options.addOption(opt);
return options;
}