下面列出了怎么用org.apache.commons.cli.PosixParser的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) {
// startup checks and logging
EnvironmentInformation.logEnvironmentInfo(LOG, MesosJobClusterEntrypoint.class.getSimpleName(), args);
SignalHandler.register(LOG);
JvmShutdownSafeguard.installAsShutdownHook(LOG);
// load configuration incl. dynamic properties
CommandLineParser parser = new PosixParser();
CommandLine cmd;
try {
cmd = parser.parse(ALL_OPTIONS, args);
}
catch (Exception e){
LOG.error("Could not parse the command-line options.", e);
System.exit(STARTUP_FAILURE_RETURN_CODE);
return;
}
Configuration dynamicProperties = BootstrapTools.parseDynamicProperties(cmd);
Configuration configuration = MesosEntrypointUtils.loadConfiguration(dynamicProperties, LOG);
MesosJobClusterEntrypoint clusterEntrypoint = new MesosJobClusterEntrypoint(configuration, dynamicProperties);
ClusterEntrypoint.runClusterEntrypoint(clusterEntrypoint);
}
@Test
public void testCommandLineShortOpts() throws Exception {
String[] argv = {
"-g testGeoUrl",
"-a testAsnUrl",
"-r /test/remoteDirGeo",
"-ra", "/test/remoteDirAsn",
"-t /test/tmpDir",
"-z test:2181"
};
String[] otherArgs = new GenericOptionsParser(argv).getRemainingArgs();
CommandLine cli = MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.parse(new PosixParser(), otherArgs);
assertEquals("testGeoUrl", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.GEO_URL.get(cli).trim());
assertEquals("testAsnUrl", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.ASN_URL.get(cli).trim());
assertEquals("/test/remoteDirGeo", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.REMOTE_GEO_DIR.get(cli).trim());
assertEquals("/test/remoteDirAsn", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.REMOTE_ASN_DIR.get(cli).trim());
assertEquals("/test/tmpDir", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.TMP_DIR.get(cli).trim());
assertEquals("test:2181", MaxmindDbEnrichmentLoader.GeoEnrichmentOptions.ZK_QUORUM.get(cli).trim());
}
@Test
public void testNonExistingJarFile() {
try {
String[] arguments = {"-j", "/some/none/existing/path", "-a", "plenty", "of", "arguments"};
CommandLine line = new PosixParser().parse(CliFrontend.getProgramSpecificOptions(new Options()), arguments, false);
CliFrontend frontend = new CliFrontend();
Object result = frontend.buildProgram(line);
assertTrue(result == null);
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail("Program caused an exception: " + e.getMessage());
}
}
@Test
public void testManualOptionsOverridesConfig() {
try {
String[] arguments = {"-m", "10.221.130.22:7788"};
CommandLine line = new PosixParser().parse(CliFrontend.getJobManagerAddressOption(new Options()), arguments, false);
TestingCliFrontend frontend = new TestingCliFrontend(CliFrontendTestUtils.getConfigDir());
InetSocketAddress address = frontend.getJobManagerAddress(line);
assertNotNull(address);
assertEquals("10.221.130.22", address.getAddress().getHostAddress());
assertEquals(7788, address.getPort());
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail("Program caused an exception: " + e.getMessage());
}
}
@Test
public void testExecuteDefaultWhenPullMessageByQueueGotException() throws SubCommandException, InterruptedException, RemotingException, MQClientException, MQBrokerException, NoSuchFieldException, IllegalAccessException {
DefaultMQPullConsumer defaultMQPullConsumer = mock(DefaultMQPullConsumer.class);
when(defaultMQPullConsumer.pull(any(MessageQueue.class), anyString(), anyLong(), anyInt())).thenThrow(Exception.class);
Field producerField = ConsumeMessageCommand.class.getDeclaredField("defaultMQPullConsumer");
producerField.setAccessible(true);
producerField.set(consumeMessageCommand, defaultMQPullConsumer);
PrintStream out = System.out;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t topic-not-existu", "-n localhost:9876"};
CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + consumeMessageCommand.commandName(),
subargs, consumeMessageCommand.buildCommandlineOptions(options), new PosixParser());
consumeMessageCommand.execute(commandLine, options, null);
System.setOut(out);
String s = new String(bos.toByteArray());
Assert.assertTrue(!s.contains("Consume ok"));
}
@SuppressWarnings("static-access")
private static CommandLine parse(String[] otherArgs, Writer out) {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("startwith").hasArg().withDescription("The value to start with.")
.create("s"));
options.addOption(OptionBuilder.withArgName("size").hasArg().withDescription("The number of terms to return.")
.create("n"));
options.addOption(OptionBuilder.withDescription("Get the frequency of each term.").create("F"));
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, otherArgs);
} catch (ParseException e) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(out, true);
formatter.printHelp(pw, HelpFormatter.DEFAULT_WIDTH, "terms", null, options, HelpFormatter.DEFAULT_LEFT_PAD,
HelpFormatter.DEFAULT_DESC_PAD, null, false);
return null;
}
return cmd;
}
@Test
public void testExecuteDefaultWhenPullMessageByQueueGotException() throws SubCommandException, InterruptedException, RemotingException, MQClientException, MQBrokerException, NoSuchFieldException, IllegalAccessException {
DefaultMQPullConsumer defaultMQPullConsumer = mock(DefaultMQPullConsumer.class);
when(defaultMQPullConsumer.pull(any(MessageQueue.class), anyString(), anyLong(), anyInt())).thenThrow(Exception.class);
Field producerField = ConsumeMessageCommand.class.getDeclaredField("defaultMQPullConsumer");
producerField.setAccessible(true);
producerField.set(consumeMessageCommand, defaultMQPullConsumer);
PrintStream out = System.out;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t topic-not-existu", "-n localhost:9876"};
CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + consumeMessageCommand.commandName(),
subargs, consumeMessageCommand.buildCommandlineOptions(options), new PosixParser());
consumeMessageCommand.execute(commandLine, options, null);
System.setOut(out);
String s = new String(bos.toByteArray());
Assert.assertTrue(!s.contains("Consume ok"));
}
@Test
public void testExecuteByConditionWhenPullMessageByQueueGotException() throws IllegalAccessException, InterruptedException, RemotingException, MQClientException, MQBrokerException, NoSuchFieldException, SubCommandException {
DefaultMQPullConsumer defaultMQPullConsumer = mock(DefaultMQPullConsumer.class);
when(defaultMQPullConsumer.pull(any(MessageQueue.class), anyString(), anyLong(), anyInt())).thenThrow(Exception.class);
Field producerField = ConsumeMessageCommand.class.getDeclaredField("defaultMQPullConsumer");
producerField.setAccessible(true);
producerField.set(consumeMessageCommand, defaultMQPullConsumer);
PrintStream out = System.out;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t mytopic", "-b localhost", "-i 0", "-n localhost:9876"};
CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + consumeMessageCommand.commandName(), subargs, consumeMessageCommand.buildCommandlineOptions(options), new PosixParser());
consumeMessageCommand.execute(commandLine, options, null);
System.setOut(out);
String s = new String(bos.toByteArray());
Assert.assertTrue(!s.contains("Consume ok"));
}
@Test
public void testNonExistingFileWithoutArguments() {
try {
String[] parameters = {"/some/none/existing/path"};
CommandLine line = new PosixParser().parse(CliFrontend.getProgramSpecificOptions(new Options()), parameters, false);
CliFrontend frontend = new CliFrontend();
Object result = frontend.buildProgram(line);
assertTrue(result == null);
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail("Program caused an exception: " + e.getMessage());
}
}
@Test
public void testVariantWithExplicitJarAndNoArgumentsOption() {
try {
String[] parameters = {"-j", getTestJarPath(), "some", "program", "arguments"};
CommandLine line = new PosixParser().parse(CliFrontend.getProgramSpecificOptions(new Options()), parameters, false);
CliFrontend frontend = new CliFrontend();
Object result = frontend.buildProgram(line);
assertTrue(result instanceof PackagedProgram);
PackagedProgram prog = (PackagedProgram) result;
Assert.assertArrayEquals(new String[] {"some", "program", "arguments"}, prog.getArguments());
Assert.assertEquals(TEST_JAR_MAIN_CLASS, prog.getMainClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail("Program caused an exception: " + e.getMessage());
}
}
@Test
public void testExecute() {
UpdateTopicSubCommand cmd = new UpdateTopicSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {
"-b 127.0.0.1:10911",
"-t unit-test",
"-r 8",
"-w 8",
"-p 6",
"-o false",
"-u false",
"-s false"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('b').trim()).isEqualTo("127.0.0.1:10911");
assertThat(commandLine.getOptionValue('r').trim()).isEqualTo("8");
assertThat(commandLine.getOptionValue('w').trim()).isEqualTo("8");
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
assertThat(commandLine.getOptionValue('p').trim()).isEqualTo("6");
assertThat(commandLine.getOptionValue('o').trim()).isEqualTo("false");
assertThat(commandLine.getOptionValue('u').trim()).isEqualTo("false");
assertThat(commandLine.getOptionValue('s').trim()).isEqualTo("false");
}
@Test
public void testExecute() throws SubCommandException {
PrintStream out = System.out;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t mytopic","-p 'send message test'","-c tagA","-k order-16546745756"};
CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + sendMessageCommand.commandName(), subargs, sendMessageCommand.buildCommandlineOptions(options), new PosixParser());
sendMessageCommand.execute(commandLine, options, null);
subargs = new String[] {"-t mytopic","-p 'send message test'","-c tagA","-k order-16546745756","-b brokera","-i 1"};
commandLine = ServerUtil.parseCmdLine("mqadmin " + sendMessageCommand.commandName(), subargs, sendMessageCommand.buildCommandlineOptions(options), new PosixParser());
sendMessageCommand.execute(commandLine, options, null);
System.setOut(out);
String s = new String(bos.toByteArray());
Assert.assertTrue(s.contains("SEND_OK"));
}
private String dumpConfigs(ConfigurationType type, Optional<String> configName) throws Exception {
String[] args = new String[]{
"-z", zookeeperUrl,
"--mode", "DUMP",
"--config_type", type.toString()
};
if (configName.isPresent()) {
args = ArrayUtils.addAll(args, "--config_name", configName.get());
}
ConfigurationManager manager = new ConfigurationManager();
return redirectSystemOut(args, (a) -> {
manager.run(ConfigurationManager.ConfigurationOptions.parse(new PosixParser(), a));
});
}
@Test
public void testExecute() {
UpdateTopicPermSubCommand cmd = new UpdateTopicPermSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster", "-t unit-test", "-p 6"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
assertThat(commandLine.getOptionValue('b').trim()).isEqualTo("127.0.0.1:10911");
assertThat(commandLine.getOptionValue('c').trim()).isEqualTo("default-cluster");
assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
assertThat(commandLine.getOptionValue('p').trim()).isEqualTo("6");
}
@Test
public void testExecute() {
TopicStatusSubCommand cmd = new TopicStatusSubCommand();
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");
}
@Test
public void testFind() throws Exception {
File.createTempFile("temp", ".duck");
final File f = File.createTempFile("temp", ".duck");
File.createTempFile("temp", ".false");
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "rackspace://cdn.cyberduck.ch/remote", f.getParent() + "/*.duck"});
final Set<TransferItem> found = new GlobTransferItemFinder().find(input, TerminalAction.upload, new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.file)));
assertFalse(found.isEmpty());
assertTrue(found.contains(new TransferItem(
new Path(new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.directory)), f.getName(), EnumSet.of(Path.Type.file)),
new Local(f.getAbsolutePath()))));
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ConsumerConnectionSubCommand cmd = new ConsumerConnectionSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-consumer-group"};
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) {
QueryConsumeQueueCommand cmd = new QueryConsumeQueueCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t TopicTest", "-q 0", "-i 6447", "-b 100.81.165.119:10911"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options),
new PosixParser());
cmd.execute(commandLine, options, null);
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ConsumerStatusSubCommand cmd = new ConsumerStatusSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-i cid_one"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
@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);
}
@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);
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ResetOffsetByTimeCommand cmd = new ResetOffsetByTimeCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-group", "-t unit-test", "-s 1412131213231", "-f false"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
GetBrokerConfigCommand cmd = new GetBrokerConfigCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
@Test
public void testExecute() {
UpdateBrokerConfigSubCommand cmd = new UpdateBrokerConfigSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster", "-k topicname", "-v 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(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
PosixParser parser = new PosixParser();
CommandLine line = parser.parse(GET_PHYSICAL_PROPERTY_OPTIONS.options, newArgs);
String waitTime = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.waitTime.getOpt());
String propertyName = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.propertyName.getOpt());
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
if (propertyName != null) {
uriSpec = uriSpec.queryParam("propertyName", propertyName);
}
if (waitTime != null) {
uriSpec = uriSpec.queryParam("waitTime", waitTime);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
/**
* Create a Stellar REPL.
* @param args The commmand-line arguments.
*/
public StellarShell(String[] args) throws Exception {
// define valid command-line options
CommandLineParser parser = new PosixParser();
Options options = defineCommandLineOptions();
CommandLine commandLine = parser.parse(options, args);
// print help
if(commandLine.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("stellar", options);
System.exit(0);
}
// validate the command line options
try {
StellarShellOptionsValidator.validateOptions(commandLine);
} catch(IllegalArgumentException e){
System.err.println(e.getMessage());
System.exit(1);
}
// setup logging, if specified
if(commandLine.hasOption("l")) {
PropertyConfigurator.configure(commandLine.getOptionValue("l"));
}
console = createConsole(commandLine);
autoCompleter = new DefaultStellarAutoCompleter();
Properties props = getStellarProperties(commandLine);
executor = createExecutor(commandLine, console, props, autoCompleter);
loadVariables(commandLine, executor);
console.setPrompt(new Prompt(EXPRESSION_PROMPT));
console.addCompletion(this);
console.setConsoleCallback(this);
}
@Test
public void testCommandLine() throws Exception {
Configuration conf = HBaseConfiguration.create();
String[] argv = {"-c connection.json", "-e extractor.json", "-n enrichment_config.json", "-l log4j", "-p 10", "-b 04/14/2016 12:00:00"};
String[] otherArgs = new GenericOptionsParser(conf, argv).getRemainingArgs();
CommandLine cli = TaxiiLoader.TaxiiOptions.parse(new PosixParser(), otherArgs);
assertEquals(extractorJson,TaxiiLoader.TaxiiOptions.EXTRACTOR_CONFIG.get(cli).trim());
assertEquals(connectionConfig, TaxiiLoader.TaxiiOptions.CONNECTION_CONFIG.get(cli).trim());
assertEquals(beginTime,TaxiiLoader.TaxiiOptions.BEGIN_TIME.get(cli).trim());
assertEquals(enrichmentJson,TaxiiLoader.TaxiiOptions.ENRICHMENT_CONFIG.get(cli).trim());
assertEquals(timeInteval,TaxiiLoader.TaxiiOptions.TIME_BETWEEN_POLLS.get(cli).trim());
assertEquals(log4jProperty, TaxiiLoader.TaxiiOptions.LOG4J_PROPERTIES.get(cli).trim());
}
@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);
}
@Test
public void testProfile() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(new Options(), new String[]{});
final ProtocolFactory factory = new ProtocolFactory(new LinkedHashSet<>(Collections.singleton(new SwiftProtocol())));
factory.register(new ProfilePlistReader(factory).read(this.getClass().getResourceAsStream("/Rackspace US.cyberduckprofile")));
assertEquals(0, new Host(factory.forName("rackspace"), "identity.api.rackspacecloud.com", 443, "/cdn.cyberduck.ch/", new Credentials("u", null))
.compareTo(new CommandLineUriParser(input, factory).parse("rackspace://[email protected]/")));
}
@Test
public void testExecute() {
TopicClusterSubCommand cmd = new TopicClusterSubCommand();
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");
}